diff --git a/cypress/e2e/DoenetML/equality/mathexpressions.cy.js b/cypress/e2e/DoenetML/equality/mathexpressions.cy.js index 900046bc7f..05f6fbbb01 100644 --- a/cypress/e2e/DoenetML/equality/mathexpressions.cy.js +++ b/cypress/e2e/DoenetML/equality/mathexpressions.cy.js @@ -861,7 +861,6 @@ describe('Math expressions equality tests', function () { symbolicSimplifyEqual: false, symbolicSimplifyExpandEqual: false, }, - { expr1: 'linesegment(A,B)', expr2: 'linesegment(B,A)', @@ -870,6 +869,38 @@ describe('Math expressions equality tests', function () { symbolicSimplifyEqual: true, symbolicSimplifyExpandEqual: true, }, + { + expr1: 'exists x elementof A union B', + expr2: 'exists x elementof B union A', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\exists x \\in A \\cup B', + expr2: '\\exists x \\in B \\cup A', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'forall x elementof A intersect B', + expr2: 'forall x elementof B intersect A', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\forall x \\in A \\cap B', + expr2: '\\forall x \\in B \\cap A', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, ] diff --git a/package-lock.json b/package-lock.json index d105a1a92d..c81a5c6306 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "json-stringify-deterministic": "^1.0.1", "lodash.debounce": "^4.0.8", "lorem-ipsum": "^2.0.4", - "math-expressions": "^2.0.0-alpha58", + "math-expressions": "^2.0.0-alpha59", "nanoid": "^3.1.31", "react": "^17.0.2", "react-copy-to-clipboard": "^5.0.3", @@ -8314,9 +8314,9 @@ "license": "Apache-2.0" }, "node_modules/math-expressions": { - "version": "2.0.0-alpha58", - "resolved": "https://registry.npmjs.org/math-expressions/-/math-expressions-2.0.0-alpha58.tgz", - "integrity": "sha512-7kWVsdbw7To6wJtrCjF0eBdMP/9jLWpdDdEAj6AzrDQLBAlsb1KLsSsBIPERj/2OON5VRAh5X6ivngL6nUmUKQ==", + "version": "2.0.0-alpha59", + "resolved": "https://registry.npmjs.org/math-expressions/-/math-expressions-2.0.0-alpha59.tgz", + "integrity": "sha512-3acLBzn3WqB2QkVvsBuCqxeP+DZwuFkGJiy5KixjbROST6WVzWGR+nKEpZJWFJ0q6pjDCAZZ9+G1ssxpjEesqw==", "dependencies": { "@babel/cli": "^7.0.0", "babel-upgrade": "^1.0.1", @@ -17960,9 +17960,9 @@ "dev": true }, "math-expressions": { - "version": "2.0.0-alpha58", - "resolved": "https://registry.npmjs.org/math-expressions/-/math-expressions-2.0.0-alpha58.tgz", - "integrity": "sha512-7kWVsdbw7To6wJtrCjF0eBdMP/9jLWpdDdEAj6AzrDQLBAlsb1KLsSsBIPERj/2OON5VRAh5X6ivngL6nUmUKQ==", + "version": "2.0.0-alpha59", + "resolved": "https://registry.npmjs.org/math-expressions/-/math-expressions-2.0.0-alpha59.tgz", + "integrity": "sha512-3acLBzn3WqB2QkVvsBuCqxeP+DZwuFkGJiy5KixjbROST6WVzWGR+nKEpZJWFJ0q6pjDCAZZ9+G1ssxpjEesqw==", "requires": { "@babel/cli": "^7.0.0", "babel-upgrade": "^1.0.1", diff --git a/package.json b/package.json index aece98a711..bb7c940c4e 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,7 @@ "json-stringify-deterministic": "^1.0.1", "lodash.debounce": "^4.0.8", "lorem-ipsum": "^2.0.4", - "math-expressions": "^2.0.0-alpha58", + "math-expressions": "^2.0.0-alpha59", "nanoid": "^3.1.31", "react": "^17.0.2", "react-copy-to-clipboard": "^5.0.3", diff --git a/src/Viewer/core.js b/src/Viewer/core.js index cc28ee9467..1dbf73069f 100644 --- a/src/Viewer/core.js +++ b/src/Viewer/core.js @@ -11,11 +11,11 @@ var Core=function(){"use strict";class ParameterStack{constructor(e){this.stack= * * Copyright (c) 2021, Robert Eisele (robert@xarg.org) * Dual licensed under the MIT or GPL Version 2 licenses. - **/!function(e,t){!function(t){var n={s:1,n:0,d:1};function r(e,t){if(isNaN(e=parseInt(e,10)))throw l.InvalidParameter;return e*t}function a(e,t){if(0===t)throw l.DivisionByZero;var n=Object.create(l.prototype);n.s=e<0?-1:1;var r=o(e=e<0?-e:e,t);return n.n=e/r,n.d=t/r,n}function i(e){for(var t={},n=e,r=2,a=4;a<=n;){for(;n%r==0;)n/=r,t[r]=(t[r]||0)+1;a+=1+2*r++}return n!==e?n>1&&(t[n]=(t[n]||0)+1):t[e]=(t[e]||0)+1,t}var s=function(e,t){var a,i=0,s=1,o=1,u=0,c=0,p=0,d=1,m=1,h=0,f=1,y=1,g=1,b=1e7;if(null==e);else if(void 0!==t){if(o=(i=e)*(s=t),i%1!=0||s%1!=0)throw l.NonIntegerParameter}else switch(typeof e){case"object":if("d"in e&&"n"in e)i=e.n,s=e.d,"s"in e&&(i*=e.s);else{if(!(0 in e))throw l.InvalidParameter;i=e[0],1 in e&&(s=e[1])}o=i*s;break;case"number":if(e<0&&(o=e,e=-e),e%1==0)i=e;else if(e>0){for(e>=1&&(e/=m=Math.pow(10,Math.floor(1+Math.log(e)/Math.LN10)));f<=b&&g<=b;){if(e===(a=(h+y)/(f+g))){f+g<=b?(i=h+y,s=f+g):g>f?(i=y,s=g):(i=h,s=f);break}e>a?(h+=y,f+=g):(y+=h,g+=f),f>b?(i=y,s=g):(i=h,s=f)}i*=m}else(isNaN(e)||isNaN(t))&&(s=i=NaN);break;case"string":if(null===(f=e.match(/\d+|./g)))throw l.InvalidParameter;if("-"===f[h]?(o=-1,h++):"+"===f[h]&&h++,f.length===h+1?c=r(f[h++],o):"."===f[h+1]||"."===f[h]?("."!==f[h]&&(u=r(f[h++],o)),(1+ ++h===f.length||"("===f[h+1]&&")"===f[h+3]||"'"===f[h+1]&&"'"===f[h+3])&&(c=r(f[h],o),d=Math.pow(10,f[h].length),h++),("("===f[h]&&")"===f[h+2]||"'"===f[h]&&"'"===f[h+2])&&(p=r(f[h+1],o),m=Math.pow(10,f[h+1].length)-1,h+=3)):"/"===f[h+1]||":"===f[h+1]?(c=r(f[h],o),d=r(f[h+2],1),h+=3):"/"===f[h+3]&&" "===f[h+1]&&(u=r(f[h],o),c=r(f[h+2],o),d=r(f[h+4],1),h+=5),f.length<=h){o=i=p+(s=d*m)*u+m*c;break}default:throw l.InvalidParameter}if(0===s)throw l.DivisionByZero;n.s=o<0?-1:1,n.n=Math.abs(i),n.d=Math.abs(s)};function o(e,t){if(!e)return t;if(!t)return e;for(;;){if(!(e%=t))return t;if(!(t%=e))return e}}function l(e,t){if(s(e,t),!(this instanceof l))return a(n.s*n.n,n.d);e=o(n.d,n.n),this.s=n.s,this.n=n.n/e,this.d=n.d/e}l.DivisionByZero=new Error("Division by Zero"),l.InvalidParameter=new Error("Invalid argument"),l.NonIntegerParameter=new Error("Parameters must be integer"),l.prototype={s:1,n:0,d:1,abs:function(){return a(this.n,this.d)},neg:function(){return a(-this.s*this.n,this.d)},add:function(e,t){return s(e,t),a(this.s*this.n*n.d+n.s*this.d*n.n,this.d*n.d)},sub:function(e,t){return s(e,t),a(this.s*this.n*n.d-n.s*this.d*n.n,this.d*n.d)},mul:function(e,t){return s(e,t),a(this.s*n.s*this.n*n.n,this.d*n.d)},div:function(e,t){return s(e,t),a(this.s*n.s*this.n*n.d,this.d*n.n)},clone:function(){return a(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new l(NaN);if(void 0===e)return a(this.s*this.n%this.d,1);if(s(e,t),0===n.n&&0===this.d)throw l.DivisionByZero;return a(this.s*(n.d*this.n)%(n.n*this.d),n.d*this.d)},gcd:function(e,t){return s(e,t),a(o(n.n,this.n)*o(n.d,this.d),n.d*this.d)},lcm:function(e,t){return s(e,t),0===n.n&&0===this.n?a(0,1):a(n.n*this.n,o(n.n,this.n)*o(n.d,this.d))},ceil:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return a(this.s*this.d,this.n)},pow:function(e,t){if(s(e,t),1===n.d)return n.s<0?a(Math.pow(this.s*this.d,n.n),Math.pow(this.n,n.n)):a(Math.pow(this.s*this.n,n.n),Math.pow(this.d,n.n));if(this.s<0)return null;var r=i(this.n),o=i(this.d),l=1,u=1;for(var c in r)if("1"!==c){if("0"===c){l=0;break}if(r[c]*=n.n,r[c]%n.d!=0)return null;r[c]/=n.d,l*=Math.pow(c,r[c])}for(var c in o)if("1"!==c){if(o[c]*=n.n,o[c]%n.d!=0)return null;o[c]/=n.d,u*=Math.pow(c,o[c])}return n.s<0?a(u,l):a(l,u)},equals:function(e,t){return s(e,t),this.s*this.n*n.d==n.s*n.n*this.d},compare:function(e,t){s(e,t);var r=this.s*this.n*n.d-n.s*n.n*this.d;return(0=0;s--)i=i.inverse().add(n[s]);if(i.sub(t).abs().valueOf()0&&(n+=t,n+=" ",r%=a),n+=r,n+="/",n+=a),n},toLatex:function(e){var t,n="",r=this.n,a=this.d;return this.s<0&&(n+="-"),1===a?n+=r:(e&&(t=Math.floor(r/a))>0&&(n+=t,r%=a),n+="\\frac{",n+=r,n+="}{",n+=a,n+="}"),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do{r.push(Math.floor(t/n)),e=t%n,t=n,n=e}while(1!==t);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return"NaN";e=e||15;var r=function(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(1===t)return 0;for(var n=10%t,r=1;1!==n;r++)if(n=10*n%t,r>2e3)return 0;return r}(0,n),a=function(e,t,n){for(var r=1,a=function(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)1&t&&(r=r*e%n);return r}(10,n,t),i=0;i<300;i++){if(r===a)return i;r=10*r%t,a=10*a%t}return 0}(0,n,r),i=this.s<0?"-":"";if(i+=t/n|0,t%=n,(t*=10)&&(i+="."),r){for(var s=a;s--;)i+=t/n|0,t%=n,t*=10;for(i+="(",s=r;s--;)i+=t/n|0,t%=n,t*=10;i+=")"}else for(s=e;t&&s--;)i+=t/n|0,t%=n,t*=10;return i}},Object.defineProperty(l,"__esModule",{value:!0}),l.default=l,l.Fraction=l,e.exports=l}()}(fraction$1);var Fraction$1=getDefaultExportFromCjs(fraction$1.exports),name$4z="Fraction",dependencies$4z=[],createFractionClass=factory(name$4z,dependencies$4z,(()=>(Fraction$1.prototype.type="Fraction",Fraction$1.prototype.isFraction=!0,Fraction$1.prototype.toJSON=function(){return{mathjs:"Fraction",n:this.s*this.n,d:this.d}},Fraction$1.fromJSON=function(e){return new Fraction$1(e)},Fraction$1)),{isClass:!0}),name$4y="Range",dependencies$4y=[],createRangeClass=factory(name$4y,dependencies$4y,(()=>{function e(t,n,r){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");var a=null!=t,i=null!=n,s=null!=r;if(a)if(isBigNumber(t))t=t.toNumber();else if("number"!=typeof t)throw new TypeError("Parameter start must be a number");if(i)if(isBigNumber(n))n=n.toNumber();else if("number"!=typeof n)throw new TypeError("Parameter end must be a number");if(s)if(isBigNumber(r))r=r.toNumber();else if("number"!=typeof r)throw new TypeError("Parameter step must be a number");this.start=a?parseFloat(t):0,this.end=i?parseFloat(n):0,this.step=s?parseFloat(r):1}return e.prototype.type="Range",e.prototype.isRange=!0,e.parse=function(t){if("string"!=typeof t)return null;var n=t.split(":").map((function(e){return parseFloat(e)}));if(n.some((function(e){return isNaN(e)})))return null;switch(n.length){case 2:return new e(n[0],n[1]);case 3:return new e(n[0],n[2],n[1]);default:return null}},e.prototype.clone=function(){return new e(this.start,this.end,this.step)},e.prototype.size=function(){var e=0,t=this.start,n=this.step,r=this.end-t;return sign$3(n)===sign$3(r)?e=Math.ceil(r/n):0===r&&(e=0),isNaN(e)&&(e=0),[e]},e.prototype.min=function(){var e=this.size()[0];return e>0?this.step>0?this.start:this.start+(e-1)*this.step:void 0},e.prototype.max=function(){var e=this.size()[0];return e>0?this.step>0?this.start+(e-1)*this.step:this.start:void 0},e.prototype.forEach=function(e){var t=this.start,n=this.step,r=this.end,a=0;if(n>0)for(;tr;)e(t,[a],this),t+=n,a++},e.prototype.map=function(e){var t=[];return this.forEach((function(n,r,a){t[r[0]]=e(n,r,a)})),t},e.prototype.toArray=function(){var e=[];return this.forEach((function(t,n){e[n[0]]=t})),e},e.prototype.valueOf=function(){return this.toArray()},e.prototype.format=function(e){var t=format$3(this.start,e);return 1!==this.step&&(t+=":"+format$3(this.step,e)),t+":"+format$3(this.end,e)},e.prototype.toString=function(){return this.format()},e.prototype.toJSON=function(){return{mathjs:"Range",start:this.start,end:this.end,step:this.step}},e.fromJSON=function(t){return new e(t.start,t.end,t.step)},e}),{isClass:!0}),name$4x="Matrix",dependencies$4x=[],createMatrixClass=factory(name$4x,dependencies$4x,(()=>{function e(){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator")}return e.prototype.type="Matrix",e.prototype.isMatrix=!0,e.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},e.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},e.prototype.create=function(e,t){throw new Error("Cannot invoke create on a Matrix interface")},e.prototype.subset=function(e,t,n){throw new Error("Cannot invoke subset on a Matrix interface")},e.prototype.get=function(e){throw new Error("Cannot invoke get on a Matrix interface")},e.prototype.set=function(e,t,n){throw new Error("Cannot invoke set on a Matrix interface")},e.prototype.resize=function(e,t){throw new Error("Cannot invoke resize on a Matrix interface")},e.prototype.reshape=function(e,t){throw new Error("Cannot invoke reshape on a Matrix interface")},e.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},e.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},e.prototype.map=function(e,t){throw new Error("Cannot invoke map on a Matrix interface")},e.prototype.forEach=function(e){throw new Error("Cannot invoke forEach on a Matrix interface")},e.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},e.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},e.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},e.prototype.format=function(e){throw new Error("Cannot invoke format on a Matrix interface")},e.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},e}),{isClass:!0}),name$4w="DenseMatrix",dependencies$4w=["Matrix"],createDenseMatrixClass=factory(name$4w,dependencies$4w,(e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))"DenseMatrix"===e.type?(this._data=clone$3(e._data),this._size=clone$3(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,validate(this._data,this._size),this._datatype=t||e.datatype;else if(isArray$1(e))this._data=o(e),this._size=arraySize(this._data),validate(this._data,this._size),this._datatype=t;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t}}function r(e,t,n,a){var i=a===n-1,s=t.dimension(a);return i?s.map((function(t){return validateIndex(t,e.length),e[t]})).valueOf():s.map((function(i){return validateIndex(i,e.length),r(e[i],t,n,a+1)})).valueOf()}function a(e,t,n,r,i){var s=i===r-1,o=t.dimension(i);s?o.forEach((function(t,r){validateIndex(t),e[t]=n[r[0]]})):o.forEach((function(s,o){validateIndex(s),a(e[s],t,n[o[0]],r,i+1)}))}function i(e,t,n){if(0===t.length){for(var r=e._data;isArray$1(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize$1(e._data,e._size,n),e}function s(e,t,n){for(var r=e._size.slice(0),a=!1;r.lengthr[s]&&(r[s]=t[s],a=!0);a&&i(e,r,n)}function o(e){for(var t=0,n=e.length;t");var p=t.max().map((function(e){return e+1}));s(e,p,r);var d=o.length;a(e._data,t,n,d,0)}return e}(this,e,t,i);default:throw new SyntaxError("Wrong number of arguments")}},n.prototype.get=function(e){if(!isArray$1(e))throw new TypeError("Array expected");if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;tArray.isArray(e)&&1===e.length?e[0]:e));return i(n?this.clone():this,r,t)},n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=reshape$1(n._data,e);var r=n._size.reduce(((e,t)=>e*t));return n._size=processSizesWildcard(e,r),n},n.prototype.clone=function(){return new n({data:clone$3(this._data),size:clone$3(this._size),datatype:this._datatype})},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=function n(r,a){return isArray$1(r)?r.map((function(e,t){return n(e,a.concat(t))})):e(r,a,t)}(this._data,[]);return new n(r,void 0!==this._datatype?getArrayDataType(r,typeOf$1):void 0)},n.prototype.forEach=function(e){var t=this;!function n(r,a){isArray$1(r)?r.forEach((function(e,t){n(e,a.concat(t))})):e(r,a,t)}(this._data,[])},n.prototype[Symbol.iterator]=function*(){yield*function*e(t,n){if(isArray$1(t))for(var r=0;r[e[r]]));t.push(new n(i,e._datatype))},s=0;s0?e:0,r=e<0?-e:0,a=this._size[0],i=this._size[1],s=Math.min(a-r,i-t),o=[],l=0;l0?r:0,o=r<0?-r:0,l=e[0],u=e[1],c=Math.min(l-o,u-s);if(isArray$1(t)){if(t.length!==c)throw new Error("Invalid value array length");i=function(e){return t[e]}}else if(isMatrix(t)){var p=t.size();if(1!==p.length||p[0]!==c)throw new Error("Invalid matrix length");i=function(e){return t.get([e])}}else i=function(){return t};a||(a=isBigNumber(i(0))?i(0).mul(0):0);var d=[];if(e.length>0){d=resize$1(d,e,a);for(var m=0;m{var{typed:t}=e;return t(name$4v,{any:clone$3})}));function _switch$1(e){var t,n,r=e.length,a=e[0].length,i=[];for(n=0;n=r.length)throw new IndexError(t,r.length);return isMatrix(e)?e.create(_reduce(e.valueOf(),t,n)):_reduce(e,t,n)}function _reduce(e,t,n){var r,a,i,s;if(t<=0){if(Array.isArray(e[0])){for(s=_switch$1(e),a=[],r=0;r{var{typed:t}=e;return t(name$4u,{number:isInteger$1,BigNumber:function(e){return e.isInt()},Fraction:function(e){return 1===e.d&&isFinite(e.n)},"Array | Matrix":function(e){return deepMap(e,this)}})})),n1$4="number",n2$2="number, number";function absNumber(e){return Math.abs(e)}function addNumber(e,t){return e+t}function multiplyNumber(e,t){return e*t}function unaryMinusNumber(e){return-e}function unaryPlusNumber(e){return e}function cbrtNumber(e){return cbrt$2(e)}function cubeNumber(e){return e*e*e}function expNumber(e){return Math.exp(e)}function expm1Number(e){return expm1$1(e)}function gcdNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function gcd must be integer numbers");for(var n;0!==t;)n=e%t,e=t,t=n;return e<0?-e:e}function lcmNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function lcm must be integer numbers");if(0===e||0===t)return 0;for(var n,r=e*t;0!==t;)t=e%(n=t),e=n;return Math.abs(r/e)}function logNumber(e,t){return t?Math.log(e)/Math.log(t):Math.log(e)}function log10Number(e){return log10$3(e)}function log2Number(e){return log2$2(e)}function modNumber(e,t){if(t>0)return e-t*Math.floor(e/t);if(0===t)return e;throw new Error("Cannot calculate mod for a negative divisor")}function nthRootNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2,n=t<0;if(n&&(t=-t),0===t)throw new Error("Root must be non-zero");if(e<0&&Math.abs(t)%2!=1)throw new Error("Root must be odd when a is negative.");if(0===e)return n?1/0:0;if(!isFinite(e))return n?0:e;var r=Math.pow(Math.abs(e),1/t);return r=e<0?-r:r,n?1/r:r}function signNumber(e){return sign$3(e)}function squareNumber(e){return e*e}function xgcdNumber(e,t){var n,r,a,i=0,s=1,o=1,l=0;if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function xgcd must be integer numbers");for(;t;)a=e-(r=Math.floor(e/t))*t,n=i,i=s-r*i,s=n,n=o,o=l-r*o,l=n,e=t,t=a;return e<0?[-e,-s,-l]:[e,e?s:0,l]}function powNumber(e,t){return e*e<1&&t===1/0||e*e>1&&t===-1/0?0:Math.pow(e,t)}function roundNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!isInteger$1(t)||t<0||t>15)throw new Error("Number of decimals in function round must be an integer from 0 to 15 inclusive");return parseFloat(toFixed$2(e,t))}absNumber.signature=n1$4,addNumber.signature=n2$2,multiplyNumber.signature=n2$2,unaryMinusNumber.signature=n1$4,unaryPlusNumber.signature=n1$4,cbrtNumber.signature=n1$4,cubeNumber.signature=n1$4,expNumber.signature=n1$4,expm1Number.signature=n1$4,gcdNumber.signature=n2$2,lcmNumber.signature=n2$2,log10Number.signature=n1$4,log2Number.signature=n1$4,modNumber.signature=n2$2,signNumber.signature=n1$4,squareNumber.signature=n1$4,xgcdNumber.signature=n2$2,powNumber.signature=n2$2;var n1$3="number",n2$1="number, number";function bitAndNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitAnd");return e&t}function bitNotNumber(e){if(!isInteger$1(e))throw new Error("Integer expected in function bitNot");return~e}function bitOrNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitOr");return e|t}function bitXorNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitXor");return e^t}function leftShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function leftShift");return e<>t}function rightLogShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function rightLogShift");return e>>>t}function product(e,t){if(t>1;return product(e,n)*product(n+1,t)}function combinationsNumber(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinations");if(t>e)throw new TypeError("k must be less than or equal to n");for(var n=e-t,r=1,a=2,i=t171?1/0:product(1,e-1);if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*gammaNumber(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,r=n*e,a=r*e,i=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*n)-139/(51840*r)-571/(2488320*a)+163879/(209018880*i)+5246819/(75246796800*i*e))}--e,t=gammaP[0];for(var s=1;s=1;r--)n+=lgammaSeries[r]/(e+r);return lnSqrt2PI+(e+.5)*Math.log(t)-t+Math.log(n)}lgammaNumber.signature="number";var n1$1="number";function acoshNumber(e){return acosh$3(e)}function acotNumber(e){return Math.atan(1/e)}function acothNumber(e){return isFinite(e)?(Math.log((e+1)/e)+Math.log(e/(e-1)))/2:0}function acscNumber(e){return Math.asin(1/e)}function acschNumber(e){var t=1/e;return Math.log(t+Math.sqrt(t*t+1))}function asecNumber(e){return Math.acos(1/e)}function asechNumber(e){var t=1/e,n=Math.sqrt(t*t-1);return Math.log(n+t)}function asinhNumber(e){return asinh$3(e)}function atanhNumber(e){return atanh$3(e)}function cotNumber(e){return 1/Math.tan(e)}function cothNumber(e){var t=Math.exp(2*e);return(t+1)/(t-1)}function cscNumber(e){return 1/Math.sin(e)}function cschNumber(e){return 0===e?Number.POSITIVE_INFINITY:Math.abs(2/(Math.exp(e)-Math.exp(-e)))*sign$3(e)}function secNumber(e){return 1/Math.cos(e)}function sechNumber(e){return 2/(Math.exp(e)+Math.exp(-e))}function sinhNumber(e){return sinh$3(e)}acoshNumber.signature=n1$1,acotNumber.signature=n1$1,acothNumber.signature=n1$1,acscNumber.signature=n1$1,acschNumber.signature=n1$1,asecNumber.signature=n1$1,asechNumber.signature=n1$1,asinhNumber.signature=n1$1,atanhNumber.signature=n1$1,cotNumber.signature=n1$1,cothNumber.signature=n1$1,cscNumber.signature=n1$1,cschNumber.signature=n1$1,secNumber.signature=n1$1,sechNumber.signature=n1$1,sinhNumber.signature=n1$1;var n1="number";function isNegativeNumber(e){return e<0}function isPositiveNumber(e){return e>0}function isZeroNumber(e){return 0===e}function isNaNNumber(e){return Number.isNaN(e)}isNegativeNumber.signature=n1,isPositiveNumber.signature=n1,isZeroNumber.signature=n1,isNaNNumber.signature=n1;var name$4t="isNegative",dependencies$4t=["typed"],createIsNegative=factory(name$4t,dependencies$4t,(e=>{var{typed:t}=e;return t(name$4t,{number:isNegativeNumber,BigNumber:function(e){return e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s<0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4s="isNumeric",dependencies$4s=["typed"],createIsNumeric=factory(name$4s,dependencies$4s,(e=>{var{typed:t}=e;return t(name$4s,{"number | BigNumber | Fraction | boolean":function(){return!0},"Complex | Unit | string | null | undefined | Node":function(){return!1},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4r="hasNumericValue",dependencies$4r=["typed","isNumeric"],createHasNumericValue=factory(name$4r,dependencies$4r,(e=>{var{typed:t,isNumeric:n}=e;return t(name$4r,{string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})})),name$4q="isPositive",dependencies$4q=["typed"],createIsPositive=factory(name$4q,dependencies$4q,(e=>{var{typed:t}=e;return t(name$4q,{number:isPositiveNumber,BigNumber:function(e){return!e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s>0&&e.n>0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4p="isZero",dependencies$4p=["typed"],createIsZero=factory(name$4p,dependencies$4p,(e=>{var{typed:t}=e;return t(name$4p,{number:isZeroNumber,BigNumber:function(e){return e.isZero()},Complex:function(e){return 0===e.re&&0===e.im},Fraction:function(e){return 1===e.d&&0===e.n},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4o="isNaN",dependencies$4o=["typed"],createIsNaN=factory(name$4o,dependencies$4o,(e=>{var{typed:t}=e;return t(name$4o,{number:isNaNNumber,BigNumber:function(e){return e.isNaN()},Fraction:function(e){return!1},Complex:function(e){return e.isNaN()},Unit:function(e){return Number.isNaN(e.value)},"Array | Matrix":function(e){return deepMap(e,Number.isNaN)}})})),name$4n="typeOf",dependencies$4n=["typed"],createTypeOf=factory(name$4n,dependencies$4n,(e=>{var{typed:t}=e;return t(name$4n,{any:typeOf$1})}));function nearlyEqual(e,t,n){if(null==n)return e.eq(t);if(e.eq(t))return!0;if(e.isNaN()||t.isNaN())return!1;if(e.isFinite()&&t.isFinite()){var r=e.minus(t).abs();if(r.isZero())return!0;var a=e.constructor.max(e.abs(),t.abs());return r.lte(a.times(n))}return!1}function complexEquals(e,t,n){return nearlyEqual$1(e.re,t.re,n)&&nearlyEqual$1(e.im,t.im,n)}var name$4m="equalScalar",dependencies$4m=["typed","config"],createEqualScalar=factory(name$4m,dependencies$4m,(e=>{var{typed:t,config:n}=e;return t(name$4m,{"boolean, boolean":function(e,t){return e===t},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.eq(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return e.equals(t)},"Complex, Complex":function(e,t){return complexEquals(e,t,n.epsilon)},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)}})}));factory(name$4m,["typed","config"],(e=>{var{typed:t,config:n}=e;return t(name$4m,{"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)}})}));var name$4l="SparseMatrix",dependencies$4l=["typed","equalScalar","Matrix"],createSparseMatrixClass=factory(name$4l,dependencies$4l,(e=>{var{typed:t,equalScalar:n,Matrix:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))!function(e,t,n){"SparseMatrix"===t.type?(e._values=t._values?clone$3(t._values):void 0,e._index=clone$3(t._index),e._ptr=clone$3(t._ptr),e._size=clone$3(t._size),e._datatype=n||t._datatype):i(e,t.valueOf(),n||t._datatype)}(this,e,t);else if(e&&isArray$1(e.index)&&isArray$1(e.ptr)&&isArray$1(e.size))this._values=e.values,this._index=e.index,this._ptr=e.ptr,this._size=e.size,this._datatype=t||e.datatype;else if(isArray$1(e))i(this,e,t);else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=t}}function i(e,r,a){e._values=[],e._index=[],e._ptr=[],e._datatype=a;var i=r.length,s=0,o=n,l=0;if(isString$1(a)&&(o=t.find(n,[a,a])||n,l=t.convert(0,a)),i>0){var u=0;do{e._ptr.push(e._index.length);for(var c=0;ch){for(c=h;cm){if(d){var f=0;for(c=0;cr-1&&(e._values.splice(p,1),e._index.splice(p,1),g++)}e._ptr[c]=e._values.length}return e._size[0]=r,e._size[1]=a,e}function u(e,t,n,r,a){var i,s,o=r[0],l=r[1],u=[];for(i=0;i");if(1===i.length)t.dimension(0).forEach((function(t,a){validateIndex(t),e.set([t,0],n[a[0]],r)}));else{var u=t.dimension(0),c=t.dimension(1);u.forEach((function(t,a){validateIndex(t),c.forEach((function(i,s){validateIndex(i),e.set([t,i],n[a[0]][s[0]],r)}))}))}}return e}(this,e,t,n);default:throw new SyntaxError("Wrong number of arguments")}},a.prototype.get=function(e){if(!isArray$1(e))throw new TypeError("Array expected");if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);if(!this._values)throw new Error("Cannot invoke get on a Pattern only matrix");var t=e[0],n=e[1];validateIndex(t,this._size[0]),validateIndex(n,this._size[1]);var r=s(t,this._ptr[n],this._ptr[n+1],this._index);return rc-1||u>p-1)&&(l(this,Math.max(i+1,c),Math.max(u+1,p),a),c=this._size[0],p=this._size[1]),validateIndex(i,c),validateIndex(u,p);var h=s(i,this._ptr[u],this._ptr[u+1],this._index);return hArray.isArray(e)&&1===e.length?e[0]:e));if(2!==r.length)throw new Error("Only two dimensions matrix are supported");return r.forEach((function(e){if(!isNumber$1(e)||!isInteger$1(e)||e<0)throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(r)+")")})),l(n?this.clone():this,r[0],r[1],t)},a.prototype.reshape=function(e,t){if(!isArray$1(e))throw new TypeError("Array expected");if(2!==e.length)throw new Error("Sparse matrices can only be reshaped in two dimensions");e.forEach((function(t){if(!isNumber$1(t)||!isInteger$1(t)||t<=-2||0===t)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+format$1(e)+")")}));var n=this._size[0]*this._size[1];if(n!==(e=processSizesWildcard(e,n))[0]*e[1])throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var r=t?this.clone():this;if(this._size[0]===e[0]&&this._size[1]===e[1])return r;for(var a=[],i=0;i=0&&N<=i&&f(e._values[v],N-0,y-0)}else{for(var T={},C=g;C "+(this._values?format$1(this._values[l],e):"X");return a},a.prototype.toString=function(){return format$1(this.toArray())},a.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},a.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger$1(e))throw new TypeError("The parameter k must be an integer number")}else e=0;var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],s=Math.min(r-n,i-t),o=[],l=[],u=[];u[0]=0;for(var c=t;c0?i:0,d=i<0?-i:0,m=e[0],h=e[1],f=Math.min(m-d,h-p);if(isArray$1(r)){if(r.length!==f)throw new Error("Invalid value array length");c=function(e){return r[e]}}else if(isMatrix(r)){var y=r.size();if(1!==y.length||y[0]!==f)throw new Error("Invalid matrix length");c=function(e){return r.get([e])}}else c=function(){return r};for(var g=[],b=[],v=[],N=0;N=0&&T=u||a[p]!==t)){var m=r?r[c]:void 0;a.splice(p,0,t),r&&r.splice(p,0,m),a.splice(p<=c?c+1:c,1),r&&r.splice(p<=c?c+1:c,1)}else if(p=u||a[c]!==e)){var h=r?r[p]:void 0;a.splice(c,0,e),r&&r.splice(c,0,h),a.splice(c<=p?p+1:p,1),r&&r.splice(c<=p?p+1:p,1)}}},a}),{isClass:!0}),name$4k="number",dependencies$4k=["typed"];function getNonDecimalNumberParts(e){var t=e.match(/(0[box])([0-9a-fA-F]*)\.([0-9a-fA-F]*)/);return t?{input:e,radix:{"0b":2,"0o":8,"0x":16}[t[1]],integerPart:t[2],fractionalPart:t[3]}:null}function makeNumberFromNonDecimalParts(e){for(var t=parseInt(e.integerPart,e.radix),n=0,r=0;r{var{typed:t}=e,n=t("number",{"":function(){return 0},number:function(e){return e},string:function(e){if("NaN"===e)return NaN;var t=getNonDecimalNumberParts(e);if(t)return makeNumberFromNonDecimalParts(t);var n=0,r=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);r&&(n=Number(r[2]),e=r[1]);var a=Number(e);if(isNaN(a))throw new SyntaxError('String "'+e+'" is no valid number');if(r){if(a>2**n-1)throw new SyntaxError('String "'.concat(e,'" is out of range'));a>=2**(n-1)&&(a-=2**n)}return a},BigNumber:function(e){return e.toNumber()},Fraction:function(e){return e.valueOf()},Unit:function(e){throw new Error("Second argument with valueless unit expected")},null:function(e){return 0},"Unit, string | Unit":function(e,t){return e.toNumber(t)},"Array | Matrix":function(e){return deepMap(e,this)}});return n.fromJSON=function(e){return parseFloat(e.value)},n})),name$4j="string",dependencies$4j=["typed"],createString=factory(name$4j,dependencies$4j,(e=>{var{typed:t}=e;return t(name$4j,{"":function(){return""},number:format$3,null:function(e){return"null"},boolean:function(e){return e+""},string:function(e){return e},"Array | Matrix":function(e){return deepMap(e,this)},any:function(e){return String(e)}})})),name$4i="boolean",dependencies$4i=["typed"],createBoolean=factory(name$4i,dependencies$4i,(e=>{var{typed:t}=e;return t(name$4i,{"":function(){return!1},boolean:function(e){return e},number:function(e){return!!e},null:function(e){return!1},BigNumber:function(e){return!e.isZero()},string:function(e){var t=e.toLowerCase();if("true"===t)return!0;if("false"===t)return!1;var n=Number(e);if(""!==e&&!isNaN(n))return!!n;throw new Error('Cannot convert "'+e+'" to a boolean')},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4h="bignumber",dependencies$4h=["typed","BigNumber"],createBignumber=factory(name$4h,dependencies$4h,(e=>{var{typed:t,BigNumber:n}=e;return t("bignumber",{"":function(){return new n(0)},number:function(e){return new n(e+"")},string:function(e){var t=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);if(t){var r=t[2],a=n(t[1]),i=new n(2).pow(Number(r));if(a.gt(i.sub(1)))throw new SyntaxError('String "'.concat(e,'" is out of range'));var s=new n(2).pow(Number(r)-1);return a.gte(s)?a.sub(i):a}return new n(e)},BigNumber:function(e){return e},Fraction:function(e){return new n(e.n).div(e.d).times(e.s)},null:function(e){return new n(0)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4g="complex",dependencies$4g=["typed","Complex"],createComplex=factory(name$4g,dependencies$4g,(e=>{var{typed:t,Complex:n}=e;return t("complex",{"":function(){return n.ZERO},number:function(e){return new n(e,0)},"number, number":function(e,t){return new n(e,t)},"BigNumber, BigNumber":function(e,t){return new n(e.toNumber(),t.toNumber())},Fraction:function(e){return new n(e.valueOf(),0)},Complex:function(e){return e.clone()},string:function(e){return n(e)},null:function(e){return n(0)},Object:function(e){if("re"in e&&"im"in e)return new n(e.re,e.im);if("r"in e&&"phi"in e||"abs"in e&&"arg"in e)return new n(e);throw new Error("Expected object with properties (re and im) or (r and phi) or (abs and arg)")},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4f="fraction",dependencies$4f=["typed","Fraction"],createFraction=factory(name$4f,dependencies$4f,(e=>{var{typed:t,Fraction:n}=e;return t("fraction",{number:function(e){if(!isFinite(e)||isNaN(e))throw new Error(e+" cannot be represented as a fraction");return new n(e)},string:function(e){return new n(e)},"number, number":function(e,t){return new n(e,t)},null:function(e){return new n(0)},BigNumber:function(e){return new n(e.toString())},Fraction:function(e){return e},Object:function(e){return new n(e)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4e="matrix",dependencies$4e=["typed","Matrix","DenseMatrix","SparseMatrix"],createMatrix=factory(name$4e,dependencies$4e,(e=>{var{typed:t,Matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$4e,{"":function(){return i([])},string:function(e){return i([],e)},"string, string":function(e,t){return i([],e,t)},Array:function(e){return i(e)},Matrix:function(e){return i(e,e.storage())},"Array | Matrix, string":i,"Array | Matrix, string, string":i});function i(e,t,n){if("dense"===t||"default"===t||void 0===t)return new r(e,n);if("sparse"===t)return new a(e,n);throw new TypeError("Unknown matrix type "+JSON.stringify(t)+".")}})),name$4d="matrixFromFunction",dependencies$4d=["typed","matrix","isZero"],createMatrixFromFunction=factory(name$4d,dependencies$4d,(e=>{var{typed:t,matrix:n,isZero:r}=e;return t(name$4d,{"Array | Matrix, function, string, string":function(e,t,n,r){return a(e,t,n,r)},"Array | Matrix, function, string":function(e,t,n){return a(e,t,n)},"Matrix, function":function(e,t){return a(e,t,"dense")},"Array, function":function(e,t){return a(e,t,"dense").toArray()},"Array | Matrix, string, function":function(e,t,n){return a(e,n,t)},"Array | Matrix, string, string, function":function(e,t,n,r){return a(e,r,t,n)}});function a(e,t,a,i){var s;return(s=void 0!==i?n(a,i):n(a)).resize(e),s.forEach((function(e,n){var a=t(n);r(a)||s.set(n,a)})),s}})),name$4c="matrixFromRows",dependencies$4c=["typed","matrix","flatten","size"],createMatrixFromRows=factory(name$4c,dependencies$4c,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4c,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one row is needed to construct a matrix.");var t=s(e[0]),n=[];for(var a of e){var i=s(a);if(i!==t)throw new TypeError("The vectors had different length: "+(0|t)+" ≠ "+(0|i));n.push(r(a))}return n}function s(e){var t=a(e);if(1===t.length)return t[0];if(2===t.length){if(1===t[0])return t[1];if(1===t[1])return t[0];throw new TypeError("At least one of the arguments is not a vector.")}throw new TypeError("Only one- or two-dimensional vectors are supported.")}})),name$4b="matrixFromColumns",dependencies$4b=["typed","matrix","flatten","size"],createMatrixFromColumns=factory(name$4b,dependencies$4b,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4b,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one column is needed to construct a matrix.");for(var t=s(e[0]),n=[],a=0;a{var{typed:t}=e;return t(name$4a,{"Unit, Array":function(e,t){return e.splitUnit(t)}})})),name$49="unaryMinus",dependencies$49=["typed"],createUnaryMinus=factory(name$49,dependencies$49,(e=>{var{typed:t}=e;return t(name$49,{number:unaryMinusNumber,Complex:function(e){return e.neg()},BigNumber:function(e){return e.neg()},Fraction:function(e){return e.neg()},Unit:function(e){var t=e.clone();return t.value=this(e.value),t},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$48="unaryPlus",dependencies$48=["typed","config","BigNumber"],createUnaryPlus=factory(name$48,dependencies$48,(e=>{var{typed:t,config:n,BigNumber:r}=e;return t(name$48,{number:unaryPlusNumber,Complex:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Unit:function(e){return e.clone()},"Array | Matrix":function(e){return deepMap(e,this)},"boolean | string":function(e){return"BigNumber"===n.number?new r(+e):+e}})})),name$47="abs",dependencies$47=["typed"],createAbs=factory(name$47,dependencies$47,(e=>{var{typed:t}=e;return t(name$47,{number:absNumber,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},Fraction:function(e){return e.abs()},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.abs()}})})),name$46="apply",dependencies$46=["typed","isInteger"],createApply=factory(name$46,dependencies$46,(e=>{var{typed:t,isInteger:n}=e;return t(name$46,{"Array | Matrix, number | BigNumber, function":function(e,t,r){if(!n(t))throw new TypeError("Integer number expected for dimension");var a=Array.isArray(e)?arraySize(e):e.size();if(t<0||t>=a.length)throw new IndexError(t,a.length);return isMatrix(e)?e.create(_apply(e.valueOf(),t,r)):_apply(e,t,r)}})}));function _apply(e,t,n){var r,a,i;if(t<=0){if(Array.isArray(e[0])){for(i=_switch(e),a=[],r=0;r{var{typed:t}=e;return t(name$45,{"number, number":addNumber,"Complex, Complex":function(e,t){return e.add(t)},"BigNumber, BigNumber":function(e,t){return e.plus(t)},"Fraction, Fraction":function(e,t){return e.add(t)},"Unit, Unit":function(e,t){if(null===e.value||void 0===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value||void 0===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n}})})),name$44="cbrt",dependencies$44=["config","typed","isNegative","unaryMinus","matrix","Complex","BigNumber","Fraction"],createCbrt=factory(name$44,dependencies$44,(e=>{var{config:t,typed:n,isNegative:r,unaryMinus:a,matrix:i,Complex:s,BigNumber:o,Fraction:l}=e;return n(name$44,{number:cbrtNumber,Complex:u,"Complex, boolean":u,BigNumber:function(e){return e.cbrt()},Unit:function(e){if(e.value&&isComplex(e.value)){var t=e.clone();return t.value=1,(t=t.pow(1/3)).value=u(e.value),t}var n,i=r(e.value);i&&(e.value=a(e.value)),n=isBigNumber(e.value)?new o(1).div(3):isFraction(e.value)?new l(1,3):1/3;var s=e.pow(n);return i&&(s.value=a(s.value)),s},"Array | Matrix":function(e){return deepMap(e,this)}});function u(e,n){var r=e.arg()/3,a=e.abs(),o=new s(cbrtNumber(a),0).mul(new s(0,r).exp());if(n){var l=[o,new s(cbrtNumber(a),0).mul(new s(0,r+2*Math.PI/3).exp()),new s(cbrtNumber(a),0).mul(new s(0,r-2*Math.PI/3).exp())];return"Array"===t.matrix?l:i(l)}return o}})),name$43="algorithm11",dependencies$43=["typed","equalScalar"],createAlgorithm11=factory(name$43,dependencies$43,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=n,f=0,y=a;"string"==typeof c&&(p=c,h=t.find(n,[p,p]),f=t.convert(0,p),r=t.convert(r,p),y=t.find(a,[p,p]));for(var g=[],b=[],v=[],N=0;N{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=a;"string"==typeof c&&(p=c,r=t.convert(r,p),h=t.find(a,[p,p]));for(var f=[],y=[],g=[],b=0;b{var{typed:t}=e;return function(e,r,a,i){var s,o=e._data,l=e._size,u=e._datatype,c=a;"string"==typeof u&&(s=u,r=t.convert(r,s),c=t.find(a,[s,s]));var p=l.length>0?n(c,0,l,l[0],o,r,i):[];return e.createDenseMatrix({data:p,size:clone$3(l),datatype:s})};function n(e,t,r,a,i,s,o){var l=[];if(t===r.length-1)for(var u=0;u{var{typed:t,config:n,round:r}=e;return t(name$40,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.ceil(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),s=Math.ceil(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(s,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createCeil=factory(name$40,dependencies$40,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:s,DenseMatrix:o}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:o}),c=createAlgorithm14({typed:t}),p=createCeilNumber({typed:t,config:n,round:r});return t("ceil",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.ceil()},"Complex, number":function(e,t){return e.ceil(t)},"Complex, BigNumber":function(e,t){return e.ceil(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.ceil()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_CEIL)},Fraction:function(e){return e.ceil()},"Fraction, number":function(e,t){return e.ceil(t)},"Fraction, BigNumber":function(e,t){return e.ceil(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?s(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3$="cube",dependencies$3$=["typed"],createCube=factory(name$3$,dependencies$3$,(e=>{var{typed:t}=e;return t(name$3$,{number:cubeNumber,Complex:function(e){return e.mul(e).mul(e)},BigNumber:function(e){return e.times(e).times(e)},Fraction:function(e){return e.pow(3)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(3)}})})),name$3_="exp",dependencies$3_=["typed"],createExp=factory(name$3_,dependencies$3_,(e=>{var{typed:t}=e;return t(name$3_,{number:expNumber,Complex:function(e){return e.exp()},BigNumber:function(e){return e.exp()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Z="expm1",dependencies$3Z=["typed","Complex"],createExpm1=factory(name$3Z,dependencies$3Z,(e=>{var{typed:t,Complex:n}=e;return t(name$3Z,{number:expm1Number,Complex:function(e){var t=Math.exp(e.re);return new n(t*Math.cos(e.im)-1,t*Math.sin(e.im))},BigNumber:function(e){return e.exp().minus(1)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Y="fix",dependencies$3Y=["typed","Complex","matrix","ceil","floor","equalScalar","zeros","DenseMatrix"],createFixNumber=factory(name$3Y,["typed","ceil","floor"],(e=>{var{typed:t,ceil:n,floor:r}=e;return t(name$3Y,{number:function(e){return e>0?r(e):n(e)},"number, number":function(e,t){return e>0?r(e,t):n(e,t)}})})),createFix=factory(name$3Y,dependencies$3Y,(e=>{var{typed:t,Complex:n,matrix:r,ceil:a,floor:i,equalScalar:s,zeros:o,DenseMatrix:l}=e,u=createAlgorithm12({typed:t,DenseMatrix:l}),c=createAlgorithm14({typed:t}),p=createFixNumber({typed:t,ceil:a,floor:i});return t("fix",{number:p.signatures.number,"number, number | BigNumber":p.signatures["number,number"],Complex:function(e){return new n(e.re>0?Math.floor(e.re):Math.ceil(e.re),e.im>0?Math.floor(e.im):Math.ceil(e.im))},"Complex, number":function(e,t){return new n(e.re>0?i(e.re,t):a(e.re,t),e.im>0?i(e.im,t):a(e.im,t))},"Complex, BigNumber":function(e,t){var r=t.toNumber();return new n(e.re>0?i(e.re,r):a(e.re,r),e.im>0?i(e.im,r):a(e.im,r))},BigNumber:function(e){return e.isNegative()?a(e):i(e)},"BigNumber, number | BigNumber":function(e,t){return e.isNegative()?a(e,t):i(e,t)},Fraction:function(e){return e.s<0?e.ceil():e.floor()},"Fraction, number | BigNumber":function(e,t){return e.s<0?a(e,t):i(e,t)},"Array | Matrix":function(e){return deepMap(e,this)},"Array | Matrix, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(r(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return s(e,0)?o(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3X="floor",dependencies$3X=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix"],createFloorNumber=factory(name$3X,["typed","config","round"],(e=>{var{typed:t,config:n,round:r}=e;return t(name$3X,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.floor(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),s=Math.floor(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(s,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createFloor=factory(name$3X,dependencies$3X,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:s,DenseMatrix:o}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:o}),c=createAlgorithm14({typed:t}),p=createFloorNumber({typed:t,config:n,round:r});return t("floor",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.floor()},"Complex, number":function(e,t){return e.floor(t)},"Complex, BigNumber":function(e,t){return e.floor(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.floor()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_FLOOR)},Fraction:function(e){return e.floor()},"Fraction, number":function(e,t){return e.floor(t)},"Fraction, BigNumber":function(e,t){return e.floor(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?s(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3W="algorithm01",dependencies$3W=["typed"],createAlgorithm01=factory(name$3W,dependencies$3W,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,s=e._size,o=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(s.length!==p.length)throw new DimensionError(s.length,p.length);if(s[0]!==p[0]||s[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,h,f=s[0],y=s[1],g="string"==typeof o&&o===d?o:void 0,b=g?t.find(r,[g,g]):r,v=[];for(m=0;m{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x,S=i&&c?[]:void 0,w=[],E=[],D=i&&c?[]:void 0,O=i&&c?[]:void 0,I=[],R=[];for(C=0;C{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=a;"string"==typeof c&&(p=c,r=t.convert(r,p),h=t.find(a,[p,p]));for(var f=[],y=[],g=[],b=0;b{var{typed:t}=e;return function(e,r,a){var i,s=e._data,o=e._size,l=e._datatype,u=r._data,c=r._size,p=r._datatype,d=[];if(o.length!==c.length)throw new DimensionError(o.length,c.length);for(var m=0;m0?n(h,0,d,d[0],s,u):[];return e.createDenseMatrix({data:f,size:d,datatype:i})};function n(e,t,r,a,i,s){var o=[];if(t===r.length-1)for(var l=0;l{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm04({typed:t,equalScalar:r}),l=createAlgorithm10({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$3S,{"number, number":gcdNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function gcd must be integer numbers");for(var n=new a(0);!t.isZero();){var r=e.mod(t);e=t,t=r}return e.lt(n)?e.neg():e},"Fraction, Fraction":function(e,t){return e.gcd(t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return l(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return c(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return c(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var s=e._data,o=e._size,l=e._datatype,u=r._values,c=r._index,p=r._ptr,d=r._size,m=r._datatype;if(o.length!==d.length)throw new DimensionError(o.length,d.length);if(o[0]!==d[0]||o[1]!==d[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+d+")");if(!u)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var h,f=o[0],y=o[1],g=n,b=0,v=a;"string"==typeof l&&l===m&&(h=l,g=t.find(n,[h,h]),b=t.convert(0,h),v=t.find(a,[h,h]));for(var N=[],T=[],C=[],A=0;A{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._size,o=e._datatype,l=r._values,u=r._size,c=r._datatype;if(s.length!==u.length)throw new DimensionError(s.length,u.length);if(s[0]!==u[0]||s[1]!==u[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+u+")");var p,d=s[0],m=s[1],h=n,f=0,y=a;"string"==typeof o&&o===c&&(p=o,h=t.find(n,[p,p]),f=t.convert(0,p),y=t.find(a,[p,p]));for(var g=i&&l?[]:void 0,b=[],v=[],N=g?[]:void 0,T=[],C=[],A=0;A{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),s=createAlgorithm11({typed:t,equalScalar:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3P,{"number, number":lcmNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function lcm must be integer numbers");if(e.isZero())return e;if(t.isZero())return t;for(var n=e.times(t);!t.isZero();){var r=t;t=e.mod(r),e=r}return n.div(e).abs()},"Fraction, Fraction":function(e,t){return e.lcm(t)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return s(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return s(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return l(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return l(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,config:n,Complex:r}=e;return t(name$3O,{number:function(e){return e>=0||n.predictable?log10Number(e):new r(e,0).log().div(Math.LN10)},Complex:function(e){return new r(e).log().div(Math.LN10)},BigNumber:function(e){return!e.isNegative()||n.predictable?e.log():new r(e.toNumber(),0).log().div(Math.LN10)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3N="log2",dependencies$3N=["typed","config","Complex"],createLog2=factory(name$3N,dependencies$3N,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$3N,{number:function(e){return e>=0||n.predictable?log2Number(e):a(new r(e,0))},Complex:a,BigNumber:function(e){return!e.isNegative()||n.predictable?e.log(2):a(new r(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)}});function a(e){var t=Math.sqrt(e.re*e.re+e.im*e.im);return new r(Math.log2?Math.log2(t):Math.log(t)/Math.LN2,Math.atan2(e.im,e.re)/Math.LN2)}})),name$3M="algorithm03",dependencies$3M=["typed"],createAlgorithm03=factory(name$3M,dependencies$3M,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,s=e._size,o=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(s.length!==p.length)throw new DimensionError(s.length,p.length);if(s[0]!==p[0]||s[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,h=s[0],f=s[1],y=0,g=r;"string"==typeof o&&o===d&&(m=o,y=t.convert(0,m),g=t.find(r,[m,m]));for(var b=[],v=0;v{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x=i&&c?[]:void 0,S=[],w=[],E=x?[]:void 0,D=x?[]:void 0,O=[],I=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm03({typed:t}),o=createAlgorithm05({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm12({typed:t,DenseMatrix:a}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$3K,{"number, number":modNumber,"BigNumber, BigNumber":function(e,t){if(t.isNeg())throw new Error("Cannot calculate mod for a negative divisor");return t.isZero()?e:e.mod(t)},"Fraction, Fraction":function(e,t){if(t.compare(0)<0)throw new Error("Cannot calculate mod for a negative divisor");return e.compare(0)>=0?e.mod(t):e.mod(t).add(t).mod(t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,this,!0).valueOf()}})})),name$3J="multiplyScalar",dependencies$3J=["typed"],createMultiplyScalar=factory(name$3J,dependencies$3J,(e=>{var{typed:t}=e;return t("multiplyScalar",{"number, number":multiplyNumber,"Complex, Complex":function(e,t){return e.mul(t)},"BigNumber, BigNumber":function(e,t){return e.times(t)},"Fraction, Fraction":function(e,t){return e.mul(t)},"number | Fraction | BigNumber | Complex, Unit":function(e,t){var n=t.clone();return n.value=null===n.value?n._normalize(e):this(n.value,e),n},"Unit, number | Fraction | BigNumber | Complex":function(e,t){var n=e.clone();return n.value=null===n.value?n._normalize(t):this(n.value,t),n},"Unit, Unit":function(e,t){return e.multiply(t)}})})),name$3I="multiply",dependencies$3I=["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],createMultiply=factory(name$3I,dependencies$3I,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,equalScalar:i,dot:s}=e,o=createAlgorithm11({typed:t,equalScalar:i}),l=createAlgorithm14({typed:t});function u(e,t){switch(e.length){case 1:switch(t.length){case 1:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+e[0]+") must match Matrix rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;case 2:switch(t.length){case 1:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+e[1]+") must match Vector length ("+t[0]+")");break;case 2:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+e[1]+") must match Matrix B rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+e.length+" dimensions)")}}function c(e,n){if("dense"!==n.storage())throw new Error("Support for SparseMatrix not implemented");return function(e,n){var i,s=e._data,o=e._size,l=e._datatype,u=n._data,c=n._size,p=n._datatype,d=o[0],m=c[1],h=r,f=a;l&&p&&l===p&&"string"==typeof l&&(i=l,h=t.find(r,[i,i]),f=t.find(a,[i,i]));for(var y=[],g=0;gS)for(var E=0,D=0;D{var{typed:t,matrix:n,equalScalar:r,BigNumber:a}=e,i=createAlgorithm01({typed:t}),s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t}),p="Complex number not supported in function nthRoot. Use nthRoots instead.";return t(name$3H,{number:nthRootNumber,"number, number":nthRootNumber,BigNumber:function(e){return d(e,new a(2))},Complex:function(e){throw new Error(p)},"Complex, number":function(e,t){throw new Error(p)},"BigNumber, BigNumber":d,"Array | Matrix":function(e){return this(e,2)},"SparseMatrix, SparseMatrix":function(e,t){if(1===t.density())return o(e,t,this);throw new Error("Root must be non-zero")},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){if(1===t.density())return i(e,t,this,!1);throw new Error("Root must be non-zero")},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){if(1===t.density())return l(t,e,this,!0);throw new Error("Root must be non-zero")},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}});function d(e,t){var n=a.precision,r=a.clone({precision:n+2}),i=new a(0),s=new r(1),o=t.isNegative();if(o&&(t=t.neg()),t.isZero())throw new Error("Root must be non-zero");if(e.isNegative()&&!t.abs().mod(2).equals(1))throw new Error("Root must be odd when a is negative.");if(e.isZero())return o?new r(1/0):0;if(!e.isFinite())return o?i:e;var l=e.abs().pow(s.div(t));return l=e.isNeg()?l.neg():l,new a((o?s.div(l):l).toPrecision(n))}})),name$3G="sign",dependencies$3G=["typed","BigNumber","Fraction","complex"],createSign=factory(name$3G,dependencies$3G,(e=>{var{typed:t,BigNumber:n,complex:r,Fraction:a}=e;return t(name$3G,{number:signNumber,Complex:function(e){return 0===e.im?r(signNumber(e.re)):e.sign()},BigNumber:function(e){return new n(e.cmp(0))},Fraction:function(e){return new a(e.s,1)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){if(!e._isDerived()&&0!==e.units[0].unit.offset)throw new TypeError("sign is ambiguous for units with offset");return this(e.value)}})})),name$3F="sqrt",dependencies$3F=["config","typed","Complex"],createSqrt=factory(name$3F,dependencies$3F,(e=>{var{config:t,typed:n,Complex:r}=e;return n("sqrt",{number:a,Complex:function(e){return e.sqrt()},BigNumber:function(e){return!e.isNegative()||t.predictable?e.sqrt():a(e.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(.5)}});function a(e){return isNaN(e)?NaN:e>=0||t.predictable?Math.sqrt(e):new r(e,0).sqrt()}})),name$3E="square",dependencies$3E=["typed"],createSquare=factory(name$3E,dependencies$3E,(e=>{var{typed:t}=e;return t(name$3E,{number:squareNumber,Complex:function(e){return e.mul(e)},BigNumber:function(e){return e.times(e)},Fraction:function(e){return e.mul(e)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(2)}})})),name$3D="subtract",dependencies$3D=["typed","matrix","equalScalar","addScalar","unaryMinus","DenseMatrix"],createSubtract=factory(name$3D,dependencies$3D,(e=>{var{typed:t,matrix:n,equalScalar:r,addScalar:a,unaryMinus:i,DenseMatrix:s}=e,o=createAlgorithm01({typed:t}),l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm10({typed:t,DenseMatrix:s}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$3D,{"number, number":function(e,t){return e-t},"Complex, Complex":function(e,t){return e.sub(t)},"BigNumber, BigNumber":function(e,t){return e.minus(t)},"Fraction, Fraction":function(e,t){return e.sub(t)},"Unit, Unit":function(e,t){if(null===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n},"SparseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return c(e,i(t),a)},"DenseMatrix, any":function(e,t){return d(e,t,this)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})}));function checkEqualDimensions(e,t){var n=e.size(),r=t.size();if(n.length!==r.length)throw new DimensionError(n.length,r.length)}var name$3C="xgcd",dependencies$3C=["typed","config","matrix","BigNumber"],createXgcd=factory(name$3C,dependencies$3C,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$3C,{"number, number":function(e,t){var a=xgcdNumber(e,t);return"Array"===n.matrix?a:r(a)},"BigNumber, BigNumber":function(e,t){var i,s,o,l,u=new a(0),c=new a(1),p=u,d=c,m=c,h=u;if(!e.isInt()||!t.isInt())throw new Error("Parameters in function xgcd must be integer numbers");for(;!t.isZero();)s=e.div(t).floor(),o=e.mod(t),i=p,p=d.minus(s.times(p)),d=i,i=m,m=h.minus(s.times(m)),h=i,e=t,t=o;return l=e.lt(u)?[e.neg(),d.neg(),h.neg()]:[e,e.isZero()?0:d,h],"Array"===n.matrix?l:r(l)}})})),name$3B="invmod",dependencies$3B=["typed","config","BigNumber","xgcd","equal","smaller","mod","add","isInteger"],createInvmod=factory(name$3B,dependencies$3B,(e=>{var{typed:t,config:n,BigNumber:r,xgcd:a,equal:i,smaller:s,mod:o,add:l,isInteger:u}=e;return t(name$3B,{"number, number":c,"BigNumber, BigNumber":c});function c(e,t){if(!u(e)||!u(t))throw new Error("Parameters in function invmod must be integer numbers");if(e=o(e,t),i(t,0))throw new Error("Divisor must be non zero");var n=a(e,t);n=n.valueOf();var[c,p]=n;return i(c,r(1))?(p=o(p,t),s(p,r(0))&&(p=l(p,t)),p):NaN}})),name$3A="algorithm09",dependencies$3A=["typed","equalScalar"],createAlgorithm09=factory(name$3A,dependencies$3A,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x,S=i&&c?[]:void 0,w=[],E=[],D=S?[]:void 0,O=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,multiplyScalar:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm09({typed:t,equalScalar:r}),o=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3z,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,a,!1)},"DenseMatrix, any":function(e,t){return u(e,t,a,!1)},"any, SparseMatrix":function(e,t){return o(t,e,a,!0)},"any, DenseMatrix":function(e,t){return u(t,e,a,!0)},"Array, any":function(e,t){return u(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,a,!0).valueOf()}})}));function bitAndBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitAnd");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero()||t.eq(-1)||e.eq(t))return e;if(t.isZero()||e.eq(-1))return t;if(!e.isFinite()||!t.isFinite()){if(!e.isFinite()&&!t.isFinite())return e.isNegative()===t.isNegative()?e:new n(0);if(!e.isFinite())return t.isNegative()?e:e.isNegative()?new n(0):t;if(!t.isFinite())return e.isNegative()?t:t.isNegative()?new n(0):e}return bitwise(e,t,(function(e,t){return e&t}))}function bitNotBigNumber(e){if(e.isFinite()&&!e.isInteger())throw new Error("Integer expected in function bitNot");var t=e.constructor,n=t.precision;t.config({precision:1e9});var r=e.plus(new t(1));return r.s=-r.s||null,t.config({precision:n}),r}function bitOrBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitOr");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);var r=new n(-1);return e.isZero()||t.eq(r)||e.eq(t)?t:t.isZero()||e.eq(r)?e:e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e|t})):!e.isFinite()&&!e.isNegative()&&t.isNegative()||e.isNegative()&&!t.isNegative()&&!t.isFinite()?r:e.isNegative()&&t.isNegative()?e.isFinite()?e:t:e.isFinite()?t:e}function bitwise(e,t,n){var r,a,i,s,o,l=e.constructor,u=+(e.s<0),c=+(t.s<0);if(u){r=decCoefficientToBinaryString(bitNotBigNumber(e));for(var p=0;p0;)n(i[--m],s[--h])===f&&(y=y.plus(g)),g=g.times(b);for(;h>0;)n(o,s[--h])===f&&(y=y.plus(g)),g=g.times(b);return l.config({precision:v}),0===f&&(y.s=-y.s),y}function decCoefficientToBinaryString(e){for(var t=e.d,n=t[0]+"",r=1;r0)if(++o>u)for(o-=u;o--;)l+="0";else o1&&(null!==c[m+1]&&void 0!==c[m+1]||(c[m+1]=0),c[m+1]+=c[m]>>1,c[m]&=1)}return c.reverse()}function bitXor$1(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitXor");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero())return t;if(t.isZero())return e;if(e.eq(t))return new n(0);var r=new n(-1);return e.eq(r)?bitNotBigNumber(t):t.eq(r)?bitNotBigNumber(e):e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e^t})):e.isFinite()||t.isFinite()?new n(e.isNegative()===t.isNegative()?1/0:-1/0):r}function leftShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function leftShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:e.isFinite()||t.isFinite()?t.lt(55)?e.times(Math.pow(2,t.toNumber())+""):e.times(new n(2).pow(t)):new n(NaN)}function rightArithShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function rightArithShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:t.isFinite()?t.lt(55)?e.div(Math.pow(2,t.toNumber())+"").floor():e.div(new n(2).pow(t)).floor():e.isNegative()?new n(-1):e.isFinite()?new n(0):new n(NaN)}var name$3y="bitAnd",dependencies$3y=["typed","matrix","equalScalar"],createBitAnd=factory(name$3y,dependencies$3y,(e=>{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),s=createAlgorithm11({typed:t,equalScalar:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3y,{"number, number":bitAndNumber,"BigNumber, BigNumber":bitAndBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3x="bitNot",dependencies$3x=["typed"],createBitNot=factory(name$3x,dependencies$3x,(e=>{var{typed:t}=e;return t(name$3x,{number:bitNotNumber,BigNumber:bitNotBigNumber,"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3w="bitOr",dependencies$3w=["typed","matrix","equalScalar","DenseMatrix"],createBitOr=factory(name$3w,dependencies$3w,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm01({typed:t}),s=createAlgorithm04({typed:t,equalScalar:r}),o=createAlgorithm10({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3w,{"number, number":bitOrNumber,"BigNumber, BigNumber":bitOrBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3v="algorithm07",dependencies$3v=["typed","DenseMatrix"],createAlgorithm07=factory(name$3v,dependencies$3v,(e=>{var{typed:t,DenseMatrix:n}=e;return function(e,a,i){var s=e._size,o=e._datatype,l=a._size,u=a._datatype;if(s.length!==l.length)throw new DimensionError(s.length,l.length);if(s[0]!==l[0]||s[1]!==l[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+l+")");var c,p,d,m=s[0],h=s[1],f=0,y=i;"string"==typeof o&&o===u&&(c=o,f=t.convert(0,c),y=t.find(i,[c,c]));var g=[];for(p=0;p{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),s=createAlgorithm12({typed:t,DenseMatrix:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3u,{"number, number":bitXorNumber,"BigNumber, BigNumber":bitXor$1,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3t="arg",dependencies$3t=["typed"],createArg=factory(name$3t,dependencies$3t,(e=>{var{typed:t}=e;return t(name$3t,{number:function(e){return Math.atan2(0,e)},BigNumber:function(e){return e.constructor.atan2(0,e)},Complex:function(e){return e.arg()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3s="conj",dependencies$3s=["typed"],createConj=factory(name$3s,dependencies$3s,(e=>{var{typed:t}=e;return t(name$3s,{number:function(e){return e},BigNumber:function(e){return e},Complex:function(e){return e.conjugate()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3r="im",dependencies$3r=["typed"],createIm=factory(name$3r,dependencies$3r,(e=>{var{typed:t}=e;return t(name$3r,{number:function(e){return 0},BigNumber:function(e){return e.mul(0)},Fraction:function(e){return e.mul(0)},Complex:function(e){return e.im},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3q="re",dependencies$3q=["typed"],createRe=factory(name$3q,dependencies$3q,(e=>{var{typed:t}=e;return t(name$3q,{number:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Complex:function(e){return e.re},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3p="not",dependencies$3p=["typed"],createNot=factory(name$3p,dependencies$3p,(e=>{var{typed:t}=e;return t(name$3p,{number:notNumber,Complex:function(e){return 0===e.re&&0===e.im},BigNumber:function(e){return e.isZero()||e.isNaN()},Unit:function(e){return null===e.value||this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3o="or",dependencies$3o=["typed","matrix","equalScalar","DenseMatrix"],createOr=factory(name$3o,dependencies$3o,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm05({typed:t,equalScalar:r}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3o,{"number, number":orNumber,"Complex, Complex":function(e,t){return 0!==e.re||0!==e.im||0!==t.re||0!==t.im},"BigNumber, BigNumber":function(e,t){return!e.isZero()&&!e.isNaN()||!t.isZero()&&!t.isNaN()},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3n="xor",dependencies$3n=["typed","matrix","DenseMatrix"],createXor=factory(name$3n,dependencies$3n,(e=>{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),s=createAlgorithm12({typed:t,DenseMatrix:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3n,{"number, number":xorNumber,"Complex, Complex":function(e,t){return(0!==e.re||0!==e.im)!=(0!==t.re||0!==t.im)},"BigNumber, BigNumber":function(e,t){return(!e.isZero()&&!e.isNaN())!=(!t.isZero()&&!t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3m="concat",dependencies$3m=["typed","matrix","isInteger"],createConcat=factory(name$3m,dependencies$3m,(e=>{var{typed:t,matrix:n,isInteger:r}=e;return t(name$3m,{"...Array | Matrix | number | BigNumber":function(e){var t,a,i=e.length,s=-1,o=!1,l=[];for(t=0;t0&&s>a)throw new IndexError(s,a+1)}else{var c=clone$3(u).valueOf(),p=arraySize(c);if(l[t]=c,a=s,s=p.length-1,t>0&&s!==a)throw new DimensionError(a+1,s+1)}}if(0===l.length)throw new SyntaxError("At least one matrix expected");for(var d=l.shift();l.length;)d=_concat(d,l.shift(),s,0);return o?n(d):d},"...string":function(e){return e.join("")}})}));function _concat(e,t,n,r){if(r{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$3l,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$3(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[1]);var r=a(0,e.size()[0]),i=new n(r,t);return e.subset(i)}})),name$3k="count",dependencies$3k=["typed","size","prod"],createCount=factory(name$3k,dependencies$3k,(e=>{var{typed:t,size:n,prod:r}=e;return t(name$3k,{string:function(e){return e.length},"Matrix | Array":function(e){return r(n(e))}})})),name$3j="cross",dependencies$3j=["typed","matrix","subtract","multiply"],createCross=factory(name$3j,dependencies$3j,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a}=e;return t(name$3j,{"Matrix, Matrix":function(e,t){return n(i(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(i(e.toArray(),t))},"Array, Matrix":function(e,t){return n(i(e,t.toArray()))},"Array, Array":i});function i(e,t){var n=Math.max(arraySize(e).length,arraySize(t).length);e=squeeze$1(e),t=squeeze$1(t);var i=arraySize(e),s=arraySize(t);if(1!==i.length||1!==s.length||3!==i[0]||3!==s[0])throw new RangeError("Vectors with length 3 expected (Size A = ["+i.join(", ")+"], B = ["+s.join(", ")+"])");var o=[r(a(e[1],t[2]),a(e[2],t[1])),r(a(e[2],t[0]),a(e[0],t[2])),r(a(e[0],t[1]),a(e[1],t[0]))];return n>1?[o]:o}})),name$3i="diag",dependencies$3i=["typed","matrix","DenseMatrix","SparseMatrix"],createDiag=factory(name$3i,dependencies$3i,(e=>{var{typed:t,matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$3i,{Array:function(e){return i(e,0,arraySize(e),null)},"Array, number":function(e,t){return i(e,t,arraySize(e),null)},"Array, BigNumber":function(e,t){return i(e,t.toNumber(),arraySize(e),null)},"Array, string":function(e,t){return i(e,0,arraySize(e),t)},"Array, number, string":function(e,t,n){return i(e,t,arraySize(e),n)},"Array, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),arraySize(e),n)},Matrix:function(e){return i(e,0,e.size(),e.storage())},"Matrix, number":function(e,t){return i(e,t,e.size(),e.storage())},"Matrix, BigNumber":function(e,t){return i(e,t.toNumber(),e.size(),e.storage())},"Matrix, string":function(e,t){return i(e,0,e.size(),t)},"Matrix, number, string":function(e,t,n){return i(e,t,e.size(),n)},"Matrix, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),e.size(),n)}});function i(e,t,i,s){if(!isInteger$1(t))throw new TypeError("Second parameter in function diag must be an integer");var o=t>0?t:0,l=t<0?-t:0;switch(i.length){case 1:return function(e,t,n,i,s,o){var l=[i+s,i+o];if(n&&"sparse"!==n&&"dense"!==n)throw new TypeError("Unknown matrix type ".concat(n,'"'));var u="sparse"===n?a.diagonal(l,e,t):r.diagonal(l,e,t);return null!==n?u:u.valueOf()}(e,t,s,i[0],l,o);case 2:return function(e,t,r,a,i,s){if(isMatrix(e)){var o=e.diagonal(t);return null!==r?r!==o.storage()?n(o,r):o:o.valueOf()}for(var l=Math.min(a[0]-i,a[1]-s),u=[],c=0;c1&&void 0!==arguments[1]?arguments[1]:{};return n=null==n?Number.POSITIVE_INFINITY:n,t=null==t?JSON.stringify:t,function r(){"object"!=typeof r.cache&&(r.cache={values:new Map,lru:lruQueue(n||Number.POSITIVE_INFINITY)});for(var a=[],i=0;i{var{typed:t}=e;return t("filter",{"Array, function":_filterCallback,"Matrix, function":function(e,t){return e.create(_filterCallback(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}})}));function _filterCallback(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r]):t(e,[r],a)}))}var name$3g="flatten",dependencies$3g=["typed","matrix"],createFlatten=factory(name$3g,dependencies$3g,(e=>{var{typed:t,matrix:n}=e;return t(name$3g,{Array:function(e){return flatten$4(clone$3(e))},Matrix:function(e){var t=flatten$4(clone$3(e.toArray()));return n(t)}})})),name$3f="forEach",dependencies$3f=["typed"],createForEach=factory(name$3f,dependencies$3f,(e=>{var{typed:t}=e;return t(name$3f,{"Array, function":_forEach,"Matrix, function":function(e,t){return e.forEach(t)}})}));function _forEach(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e,[])}var name$3e="getMatrixDataType",dependencies$3e=["typed"],createGetMatrixDataType=factory(name$3e,dependencies$3e,(e=>{var{typed:t}=e;return t(name$3e,{Array:function(e){return getArrayDataType(e,typeOf$1)},Matrix:function(e){return e.getDataType()}})})),name$3d="identity",dependencies$3d=["typed","config","matrix","BigNumber","DenseMatrix","SparseMatrix"],createIdentity=factory(name$3d,dependencies$3d,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a,DenseMatrix:i,SparseMatrix:s}=e;return t(name$3d,{"":function(){return"Matrix"===n.matrix?r([]):[]},string:function(e){return r(e)},"number | BigNumber":function(e){return l(e,e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, string":function(e,t){return l(e,e,t)},"number | BigNumber, number | BigNumber":function(e,t){return l(e,t,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, number | BigNumber, string":function(e,t,n){return l(e,t,n)},Array:function(e){return o(e)},"Array, string":function(e,t){return o(e,t)},Matrix:function(e){return o(e.valueOf(),e.storage())},"Matrix, string":function(e,t){return o(e.valueOf(),t)}});function o(e,t){switch(e.length){case 0:return t?r(t):[];case 1:return l(e[0],e[0],t);case 2:return l(e[0],e[1],t);default:throw new Error("Vector containing two values expected")}}function l(e,t,n){var r=isBigNumber(e)||isBigNumber(t)?a:null;if(isBigNumber(e)&&(e=e.toNumber()),isBigNumber(t)&&(t=t.toNumber()),!isInteger$1(e)||e<1)throw new Error("Parameters in function identity must be positive integers");if(!isInteger$1(t)||t<1)throw new Error("Parameters in function identity must be positive integers");var o=r?new a(1):1,l=r?new r(0):0,u=[e,t];if(n){if("sparse"===n)return s.diagonal(u,o,0,l);if("dense"===n)return i.diagonal(u,o,0,l);throw new TypeError('Unknown matrix type "'.concat(n,'"'))}for(var c=resize$1([],u,l),p=e{var{typed:t,matrix:n,multiplyScalar:r}=e;return t(name$3c,{"Matrix, Matrix":function(e,t){return n(a(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(a(e.toArray(),t))},"Array, Matrix":function(e,t){return n(a(e,t.toArray()))},"Array, Array":a});function a(e,t){if(1===arraySize(e).length&&(e=[e]),1===arraySize(t).length&&(t=[t]),arraySize(e).length>2||arraySize(t).length>2)throw new RangeError("Vectors with dimensions greater then 2 are not supported expected (Size x = "+JSON.stringify(e.length)+", y = "+JSON.stringify(t.length)+")");var n=[],a=[];return e.map((function(e){return t.map((function(t){return a=[],n.push(a),e.map((function(e){return t.map((function(t){return a.push(r(e,t))}))}))}))}))&&n}})),name$3b="map",dependencies$3b=["typed"],createMap=factory(name$3b,dependencies$3b,(e=>{var{typed:t}=e;return t(name$3b,{"Array, function":_map$1,"Matrix, function":function(e,t){return e.map(t)}})}));function _map$1(e,t){var n=maxArgumentCount(t);return function r(a,i){if(Array.isArray(a))return a.map((function(e,t){return r(e,i.concat(t))}));try{return 1===n?t(a):2===n?t(a,i):t(a,i,e)}catch(t){if(t instanceof TypeError&&"data"in t&&"wrongType"===t.data.category){var s="map attempted to call '".concat(t.data.fn,"(").concat(a),o=JSON.stringify(i);throw 2===n?s+=","+o:1!==n&&(s+=",".concat(o,",").concat(e)),s+=")' but argument ".concat(t.data.index+1," of type "),s+="".concat(t.data.actual," does not match expected type "),s+=t.data.expected.join(" or "),new TypeError(s)}throw t}}(e,[])}var name$3a="diff",dependencies$3a=["typed","matrix","subtract","number"],createDiff=factory(name$3a,dependencies$3a,(e=>{var{typed:t,matrix:n,subtract:r,number:a}=e;return t(name$3a,{"Array | Matrix":function(e){return isMatrix(e)?n(s(e.toArray())):s(e)},"Array | Matrix, number":function(e,t){if(!isInteger$1(t))throw new RangeError("Dimension must be a whole number");return isMatrix(e)?n(i(e.toArray(),t)):i(e,t)},"Array | Matrix, BigNumber":function(e,t){return this(e,a(t))}});function i(e,t){if(isMatrix(e)&&(e=e.toArray()),!Array.isArray(e))throw RangeError("Array/Matrix does not have that many dimensions");if(t>0){var n=[];return e.forEach((e=>{n.push(i(e,t-1))})),n}if(0===t)return s(e);throw RangeError("Cannot have negative dimension")}function s(e){var t=[],n=e.length;if(n<2)return e;for(var r=1;r{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t("ones",{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(1):1;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function ones must be positive integers")}))}(e),t){var s=r(t);return e.length>0?s.resize(e,i):s}var o=[];return e.length>0?resize$1(o,e,i):o}}));function noBignumber(){throw new Error('No "bignumber" implementation available')}function noFraction(){throw new Error('No "fraction" implementation available')}function noMatrix(){throw new Error('No "matrix" implementation available')}var name$38="range",dependencies$38=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRange=factory(name$38,dependencies$38,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l}=e;return t(name$38,{string:c,"string, boolean":c,"number, number":function(e,t){return u(p(e,t,1))},"number, number, number":function(e,t,n){return u(p(e,t,n))},"number, number, boolean":function(e,t,n){return u(n?d(e,t,1):p(e,t,1))},"number, number, number, boolean":function(e,t,n,r){return u(r?d(e,t,n):p(e,t,n))},"BigNumber, BigNumber":function(e,t){return u(m(e,t,new e.constructor(1)))},"BigNumber, BigNumber, BigNumber":function(e,t,n){return u(m(e,t,n))},"BigNumber, BigNumber, boolean":function(e,t,n){var r=e.constructor;return u(n?h(e,t,new r(1)):m(e,t,new r(1)))},"BigNumber, BigNumber, BigNumber, boolean":function(e,t,n,r){return u(r?h(e,t,n):m(e,t,n))}});function u(e){return"Matrix"===n.matrix?r?r(e):noMatrix():e}function c(e,t){var r=function(e){var t=e.split(":").map((function(e){return Number(e)}));if(t.some((function(e){return isNaN(e)})))return null;switch(t.length){case 2:return{start:t[0],end:t[1],step:1};case 3:return{start:t[0],end:t[2],step:t[1]};default:return null}}(e);if(!r)throw new SyntaxError('String "'+e+'" is no valid range');return"BigNumber"===n.number?(void 0===a&&noBignumber(),u((t?h:m)(a(r.start),a(r.end),a(r.step)))):u((t?d:p)(r.start,r.end,r.step))}function p(e,t,n){var r=[],a=e;if(n>0)for(;i(a,t);)r.push(a),a+=n;else if(n<0)for(;o(a,t);)r.push(a),a+=n;return r}function d(e,t,n){var r=[],a=e;if(n>0)for(;s(a,t);)r.push(a),a+=n;else if(n<0)for(;l(a,t);)r.push(a),a+=n;return r}function m(e,t,n){var r=a(0),s=[],l=e;if(n.gt(r))for(;i(l,t);)s.push(l),l=l.plus(n);else if(n.lt(r))for(;o(l,t);)s.push(l),l=l.plus(n);return s}function h(e,t,n){var r=a(0),i=[],o=e;if(n.gt(r))for(;s(o,t);)i.push(o),o=o.plus(n);else if(n.lt(r))for(;l(o,t);)i.push(o),o=o.plus(n);return i}})),name$37="reshape",dependencies$37=["typed","isInteger","matrix"],createReshape=factory(name$37,dependencies$37,(e=>{var{typed:t,isInteger:n}=e;return t(name$37,{"Matrix, Array":function(e,t){return e.reshape(t)},"Array, Array":function(e,t){return t.forEach((function(e){if(!n(e))throw new TypeError("Invalid size for dimension: "+e)})),reshape$1(e,t)}})}));function ArgumentsError(e,t,n,r){if(!(this instanceof ArgumentsError))throw new SyntaxError("Constructor must be called with the new operator");this.fn=e,this.count=t,this.min=n,this.max=r,this.message="Wrong number of arguments in function "+e+" ("+t+" provided, "+n+(null!=r?"-"+r:"")+" expected)",this.stack=(new Error).stack}ArgumentsError.prototype=new Error,ArgumentsError.prototype.constructor=Error,ArgumentsError.prototype.name="ArgumentsError",ArgumentsError.prototype.isArgumentsError=!0;var name$36="resize",dependencies$36=["config","matrix"],createResize=factory(name$36,dependencies$36,(e=>{var{config:t,matrix:n}=e;return function(e,r,a){if(2!==arguments.length&&3!==arguments.length)throw new ArgumentsError("resize",arguments.length,2,3);if(isMatrix(r)&&(r=r.valueOf()),isBigNumber(r[0])&&(r=r.map((function(e){return isBigNumber(e)?e.toNumber():e}))),isMatrix(e))return e.resize(r,a,!0);if("string"==typeof e)return function(e,t,n){if(void 0!==n){if("string"!=typeof n||1!==n.length)throw new TypeError("Single character expected as defaultValue")}else n=" ";if(1!==t.length)throw new DimensionError(t.length,1);var r=t[0];if("number"!=typeof r||!isInteger$1(r))throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(t)+")");if(e.length>r)return e.substring(0,r);if(e.length{var{typed:t,multiply:n,rotationMatrix:r}=e;return t(name$35,{"Array , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e).toArray()},"Matrix , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e)},"Array, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)},"Matrix, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)}});function a(e,t){var n=Array.isArray(e)?arraySize(e):e.size();if(n.length>2)throw new RangeError("Vector must be of dimensions 1x".concat(t));if(2===n.length&&1!==n[1])throw new RangeError("Vector must be of dimensions 1x".concat(t));if(n[0]!==t)throw new RangeError("Vector must be of dimensions 1x".concat(t))}})),name$34="rotationMatrix",dependencies$34=["typed","config","multiplyScalar","addScalar","unaryMinus","norm","matrix","BigNumber","DenseMatrix","SparseMatrix","cos","sin"],createRotationMatrix=factory(name$34,dependencies$34,(e=>{var{typed:t,config:n,multiplyScalar:r,addScalar:a,unaryMinus:i,norm:s,BigNumber:o,matrix:l,DenseMatrix:u,SparseMatrix:c,cos:p,sin:d}=e;return t(name$34,{"":function(){return"Matrix"===n.matrix?l([]):[]},string:function(e){return l(e)},"number | BigNumber | Complex | Unit":function(e){return m(e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber | Complex | Unit, string":function(e,t){return m(e,t)},"number | BigNumber | Complex | Unit, Array":function(e,t){var n=l(t);return h(n),g(e,n,void 0)},"number | BigNumber | Complex | Unit, Matrix":function(e,t){h(t);var r=t.storage()||("Matrix"===n.matrix?"dense":void 0);return g(e,t,r)},"number | BigNumber | Complex | Unit, Array, string":function(e,t,n){var r=l(t);return h(r),g(e,r,n)},"number | BigNumber | Complex | Unit, Matrix, string":function(e,t,n){return h(t),g(e,t,n)}});function m(e,t){var n=isBigNumber(e)?new o(-1):-1,a=p(e),i=d(e);return y([[a,r(n,i)],[i,a]],t)}function h(e){var t=e.size();if(t.length<1||3!==t[0])throw new RangeError("Vector must be of dimensions 1x3")}function f(e){return e.reduce(((e,t)=>r(e,t)))}function y(e,t){if(t){if("sparse"===t)return new c(e);if("dense"===t)return new u(e);throw new TypeError('Unknown matrix type "'.concat(t,'"'))}return e}function g(e,t,n){var r=s(t);if(0===r)throw new RangeError("Rotation around zero vector");var l=isBigNumber(e)?o:null,u=l?new l(1):1,c=l?new l(-1):-1,m=l?new l(t.get([0])/r):t.get([0])/r,h=l?new l(t.get([1])/r):t.get([1])/r,g=l?new l(t.get([2])/r):t.get([2])/r,b=p(e),v=a(u,i(b)),N=d(e);return y([[a(b,f([m,m,v])),a(f([m,h,v]),f([c,g,N])),a(f([m,g,v]),f([h,N]))],[a(f([m,h,v]),f([g,N])),a(b,f([h,h,v])),a(f([h,g,v]),f([c,m,N]))],[a(f([m,g,v]),f([c,h,N])),a(f([h,g,v]),f([m,N])),a(b,f([g,g,v]))]],n)}})),name$33="row",dependencies$33=["typed","Index","matrix","range"],createRow=factory(name$33,dependencies$33,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$33,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$3(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[0]);var r=a(0,e.size()[1]),i=new n(t,r);return e.subset(i)}})),name$32="size",dependencies$32=["typed","config","?matrix"],createSize=factory(name$32,dependencies$32,(e=>{var{typed:t,config:n,matrix:r}=e;return t(name$32,{Matrix:function(e){return e.create(e.size())},Array:arraySize,string:function(e){return"Array"===n.matrix?[e.length]:r([e.length])},"number | Complex | BigNumber | Unit | boolean | null":function(e){return"Array"===n.matrix?[]:r?r([]):noMatrix()}})})),name$31="squeeze",dependencies$31=["typed","matrix"],createSqueeze=factory(name$31,dependencies$31,(e=>{var{typed:t,matrix:n}=e;return t(name$31,{Array:function(e){return squeeze$1(clone$3(e))},Matrix:function(e){var t=squeeze$1(e.toArray());return Array.isArray(t)?n(t):t},any:function(e){return clone$3(e)}})})),name$30="subset",dependencies$30=["typed","matrix"],createSubset=factory(name$30,dependencies$30,(e=>{var{typed:t,matrix:n}=e;return t(name$30,{"Array, Index":function(e,t){var r=n(e).subset(t);return t.isScalar()?r:r.valueOf()},"Matrix, Index":function(e,t){return e.subset(t)},"Object, Index":_getObjectProperty,"string, Index":_getSubstring,"Array, Index, any":function(e,t,r){return n(clone$3(e)).subset(t,r,void 0).valueOf()},"Array, Index, any, any":function(e,t,r,a){return n(clone$3(e)).subset(t,r,a).valueOf()},"Matrix, Index, any":function(e,t,n){return e.clone().subset(t,n)},"Matrix, Index, any, any":function(e,t,n,r){return e.clone().subset(t,n,r)},"string, Index, string":_setSubstring,"string, Index, string, string":_setSubstring,"Object, Index, any":_setObjectProperty})}));function _getSubstring(e,t){if(!isIndex(t))throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);var n=e.length;validateIndex(t.min()[0],n),validateIndex(t.max()[0],n);var r=t.dimension(0),a="";return r.forEach((function(t){a+=e.charAt(t)})),a}function _setSubstring(e,t,n,r){if(!t||!0!==t.isIndex)throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);if(void 0!==r){if("string"!=typeof r||1!==r.length)throw new TypeError("Single character expected as defaultValue")}else r=" ";var a=t.dimension(0);if(a.size()[0]!==n.length)throw new DimensionError(a.size()[0],n.length);var i=e.length;validateIndex(t.min()[0]),validateIndex(t.max()[0]);for(var s=[],o=0;oi)for(var l=i-1,u=s.length;l{var{typed:t,matrix:n}=e;return t("transpose",{Array:function(e){return this(n(e)).valueOf()},Matrix:function(e){var t,n=e.size();switch(n.length){case 1:t=e.clone();break;case 2:var r=n[0],a=n[1];if(0===a)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+format$1(n)+")");switch(e.storage()){case"dense":t=function(e,t,n){for(var r,a=e._data,i=[],s=0;s{var{typed:t,transpose:n,conj:r}=e;return t(name$2_,{any:function(e){return r(n(e))}})})),name$2Z="zeros",dependencies$2Z=["typed","config","matrix","BigNumber"],createZeros=factory(name$2Z,dependencies$2Z,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$2Z,{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(0):0;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function zeros must be positive integers")}))}(e),t){var s=r(t);return e.length>0?s.resize(e,i):s}var o=[];return e.length>0?resize$1(o,e,i):o}})),name$2Y="fft",dependencies$2Y=["typed","matrix","addScalar","multiplyScalar","divideScalar","exp","tau","i"],createFft=factory(name$2Y,dependencies$2Y,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,divideScalar:i,exp:s,tau:o,i:l}=e;return t(name$2Y,{Array:u,Matrix:function(e){return e.create(u(e.toArray()))}});function u(e){var t=arraySize(e);return 1===t.length?p(e,t[0]):c(e.map((e=>u(e,t.slice(1)))),0)}function c(e,t){var n=arraySize(e);if(0!==t)return new Array(n[0]).fill(0).map(((n,r)=>c(e[r],t-1)));if(1===n.length)return p(e);function r(e){var t=arraySize(e);return new Array(t[1]).fill(0).map(((n,r)=>new Array(t[0]).fill(0).map(((t,n)=>e[n][r]))))}return r(c(r(e),1))}function p(e){var t=e.length;if(1===t)return[e[0]];if(t%2==0){for(var n=[...p(e.filter(((e,t)=>t%2==0))),...p(e.filter(((e,t)=>t%2==1)))],u=0;u{var{typed:t,fft:n,dotDivide:r,conj:a}=e;return t(name$2X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);return r(a(n(a(e))),t.reduce(((e,t)=>e*t),1))}})})),name$2W="erf",dependencies$2W=["typed"],createErf=factory(name$2W,dependencies$2W,(e=>{var{typed:t}=e;return t("name",{number:function(e){var t=Math.abs(e);return t>=MAX_NUM?sign$3(e):t<=THRESH?sign$3(e)*function(e){var t,n=e*e,r=P[0][4]*n,a=n;for(t=0;t<3;t+=1)r=(r+P[0][t])*n,a=(a+Q[0][t])*n;return e*(r+P[0][3])/(a+Q[0][3])}(t):t<=4?sign$3(e)*(1-function(e){var t,n=P[1][8]*e,r=e;for(t=0;t<7;t+=1)n=(n+P[1][t])*e,r=(r+Q[1][t])*e;var a=(n+P[1][7])/(r+Q[1][7]),i=parseInt(16*e)/16,s=(e-i)*(e+i);return Math.exp(-i*i)*Math.exp(-s)*a}(t)):sign$3(e)*(1-function(e){var t,n=1/(e*e),r=P[2][5]*n,a=n;for(t=0;t<4;t+=1)r=(r+P[2][t])*n,a=(a+Q[2][t])*n;var i=n*(r+P[2][4])/(a+Q[2][4]);i=(SQRPI-i)/e;var s=(e-(n=parseInt(16*e)/16))*(e+n);return Math.exp(-n*n)*Math.exp(-s)*i}(t))},"Array | Matrix":function(e){return deepMap(e,this)}})})),THRESH=.46875,SQRPI=.5641895835477563,P=[[3.1611237438705655,113.86415415105016,377.485237685302,3209.3775891384694,.18577770618460315],[.5641884969886701,8.883149794388377,66.11919063714163,298.6351381974001,881.952221241769,1712.0476126340707,2051.0783778260716,1230.3393547979972,2.1531153547440383e-8],[.30532663496123236,.36034489994980445,.12578172611122926,.016083785148742275,.0006587491615298378,.016315387137302097]],Q=[[23.601290952344122,244.02463793444417,1282.6165260773723,2844.236833439171],[15.744926110709835,117.6939508913125,537.1811018620099,1621.3895745666903,3290.7992357334597,4362.619090143247,3439.3676741437216,1230.3393548037495],[2.568520192289822,1.8729528499234604,.5279051029514285,.06051834131244132,.0023352049762686918]],MAX_NUM=Math.pow(2,53),name$2V="mode",dependencies$2V=["typed","isNaN","isNumeric"],createMode=factory(name$2V,dependencies$2V,(e=>{var{typed:t,isNaN:n,isNumeric:r}=e;return t(name$2V,{"Array | Matrix":a,"...":function(e){return a(e)}});function a(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate mode of an empty array");for(var t={},a=[],i=0,s=0;si&&(i=t[o],a=[o])}return a}}));function improveErrorMessage(e,t,n){var r;return-1!==String(e).indexOf("Unexpected type")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":" (type: "+e.data.actual+")",new TypeError("Cannot calculate "+t+", unexpected type of argument"+r)):-1!==String(e).indexOf("complex numbers")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":"",new TypeError("Cannot calculate "+t+", no ordering relation is defined for complex numbers"+r)):e}var name$2U="prod",dependencies$2U=["typed","config","multiplyScalar","numeric"],createProd=factory(name$2U,dependencies$2U,(e=>{var{typed:t,config:n,multiplyScalar:r,numeric:a}=e;return t(name$2U,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("prod(A, dim) is not yet supported")},"...":function(e){return i(e)}});function i(e){var t;if(deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"prod",e)}})),"string"==typeof t&&(t=a(t,n.number)),void 0===t)throw new Error("Cannot calculate prod of an empty array");return t}})),name$2T="format",dependencies$2T=["typed"],createFormat=factory(name$2T,dependencies$2T,(e=>{var{typed:t}=e;return t(name$2T,{any:format$1,"any, Object | function | number":format$1})})),name$2S="bin",dependencies$2S=["typed","format"],createBin=factory(name$2S,dependencies$2S,(e=>{var{typed:t,format:n}=e;return t(name$2S,{"number | BigNumber":function(e){return n(e,{notation:"bin"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"bin",wordSize:t})}})})),name$2R="oct",dependencies$2R=["typed","format"],createOct=factory(name$2R,dependencies$2R,(e=>{var{typed:t,format:n}=e;return t(name$2R,{"number | BigNumber":function(e){return n(e,{notation:"oct"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"oct",wordSize:t})}})})),name$2Q="hex",dependencies$2Q=["typed","format"],createHex=factory(name$2Q,dependencies$2Q,(e=>{var{typed:t,format:n}=e;return t(name$2Q,{"number | BigNumber":function(e){return n(e,{notation:"hex"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"hex",wordSize:t})}})})),name$2P="print",dependencies$2P=["typed"],createPrint=factory(name$2P,dependencies$2P,(e=>{var{typed:t}=e;return t(name$2P,{"string, Object | Array":_print,"string, Object | Array, number | Object":_print})}));function _print(e,t,n){return e.replace(/\$([\w.]+)/g,(function(e,r){for(var a=r.split("."),i=t[a.shift()];a.length&&void 0!==i;){var s=a.shift();i=s?i[s]:i+"."}return void 0!==i?isString$1(i)?i:format$1(i,n):e}))}var name$2O="to",dependencies$2O=["typed","matrix"],createTo=factory(name$2O,dependencies$2O,(e=>{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2O,{"Unit, Unit | string":function(e,t){return e.to(t)},"Matrix, Matrix":function(e,t){return r(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"Matrix, any":function(e,t){return a(e,t,this,!1)},"any, Matrix":function(e,t){return a(t,e,this,!0)},"Array, any":function(e,t){return a(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,this,!0).valueOf()}})})),name$2N="isPrime",dependencies$2N=["typed"],createIsPrime=factory(name$2N,dependencies$2N,(e=>{var{typed:t}=e;return t(name$2N,{number:function(e){if(0*e!=0)return!1;if(e<=3)return e>1;if(e%2==0||e%3==0)return!1;for(var t=5;t*t<=e;t+=6)if(e%t==0||e%(t+2)==0)return!1;return!0},BigNumber:function(e){if(0*e.toNumber()!=0)return!1;if(e.lte(3))return e.gt(1);if(e.mod(2).eq(0)||e.mod(3).eq(0))return!1;if(e.lt(Math.pow(2,32))){for(var t=e.toNumber(),n=5;n*n<=t;n+=6)if(t%n==0||t%(n+2)==0)return!1;return!0}function r(e,t,n){for(var r=1;!t.eq(0);)t.mod(2).eq(0)?(t=t.div(2),e=e.mul(e).mod(n)):(t=t.sub(1),r=e.mul(r).mod(n));return r}for(var a=e.constructor.clone({precision:2*e.toFixed(0).length}),i=0,s=(e=new a(e)).sub(1);s.mod(2).eq(0);)s=s.div(2),i+=1;var o=null;if(e.lt("3317044064679887385961981"))o=[2,3,5,7,11,13,17,19,23,29,31,37,41].filter((t=>t{var{number:t,bignumber:n,fraction:r}=e,a={string:!0,number:!0,BigNumber:!0,Fraction:!0},i={number:e=>t(e),BigNumber:n?e=>n(e):noBignumber,Fraction:r?e=>r(e):noFraction};return function(e,t){var n=typeOf$1(e);if(!(n in a))throw new TypeError("Cannot convert "+e+' of type "'+n+'"; valid input types are '+Object.keys(a).join(", "));if(!(t in i))throw new TypeError("Cannot convert "+e+' to type "'+t+'"; valid output types are '+Object.keys(i).join(", "));return t===n?e:i[t](e)}})),name$2L="divideScalar",dependencies$2L=["typed","numeric"],createDivideScalar=factory(name$2L,dependencies$2L,(e=>{var{typed:t,numeric:n}=e;return t(name$2L,{"number, number":function(e,t){return e/t},"Complex, Complex":function(e,t){return e.div(t)},"BigNumber, BigNumber":function(e,t){return e.div(t)},"Fraction, Fraction":function(e,t){return e.div(t)},"Unit, number | Fraction | BigNumber":function(e,t){var r=e.clone(),a=n(1,typeOf$1(t));return r.value=this(null===r.value?r._normalize(a):r.value,t),r},"number | Fraction | BigNumber, Unit":function(e,t){var r=t.clone();r=r.pow(-1);var a=n(1,typeOf$1(e));return r.value=this(e,null===t.value?t._normalize(a):t.value),r},"Unit, Unit":function(e,t){return e.divide(t)}})})),name$2K="pow",dependencies$2K=["typed","config","identity","multiply","matrix","inv","fraction","number","Complex"],createPow=factory(name$2K,dependencies$2K,(e=>{var{typed:t,config:n,identity:r,multiply:a,matrix:i,inv:s,number:o,fraction:l,Complex:u}=e;return t(name$2K,{"number, number":c,"Complex, Complex":function(e,t){return e.pow(t)},"BigNumber, BigNumber":function(e,t){return t.isInteger()||e>=0||n.predictable?e.pow(t):new u(e.toNumber(),0).pow(t.toNumber(),0)},"Fraction, Fraction":function(e,t){var r=e.pow(t);if(null!=r)return r;if(n.predictable)throw new Error("Result of pow is non-rational and cannot be expressed as a fraction");return c(e.valueOf(),t.valueOf())},"Array, number":p,"Array, BigNumber":function(e,t){return p(e,t.toNumber())},"Matrix, number":d,"Matrix, BigNumber":function(e,t){return d(e,t.toNumber())},"Unit, number | BigNumber":function(e,t){return e.pow(t)}});function c(e,t){if(n.predictable&&!isInteger$1(t)&&e<0)try{var r=l(t),a=o(r);if((t===a||Math.abs((t-a)/t)<1e-14)&&r.d%2==1)return(r.n%2==0?1:-1)*Math.pow(-e,t)}catch(e){}return n.predictable&&(e<-1&&t===1/0||e>-1&&e<0&&t===-1/0)?NaN:isInteger$1(t)||e>=0||n.predictable?powNumber(e,t):e*e<1&&t===1/0||e*e>1&&t===-1/0?0:new u(e,0).pow(t,0)}function p(e,t){if(!isInteger$1(t))throw new TypeError("For A^b, b must be an integer (value is "+t+")");var n=arraySize(e);if(2!==n.length)throw new Error("For A^b, A must be 2 dimensional (A has "+n.length+" dimensions)");if(n[0]!==n[1])throw new Error("For A^b, A must be square (size is "+n[0]+"x"+n[1]+")");if(t<0)try{return p(s(e),-t)}catch(e){if("Cannot calculate inverse, determinant is zero"===e.message)throw new TypeError("For A^b, when A is not invertible, b must be a positive integer (value is "+t+")");throw e}for(var i=r(n[0]).valueOf(),o=e;t>=1;)1==(1&t)&&(i=a(o,i)),t>>=1,o=a(o,o);return i}function d(e,t){return i(p(e.valueOf(),t))}})),NO_INT="Number of decimals in function round must be an integer",name$2J="round",dependencies$2J=["typed","matrix","equalScalar","zeros","BigNumber","DenseMatrix"],createRound=factory(name$2J,dependencies$2J,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,BigNumber:i,DenseMatrix:s}=e,o=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm12({typed:t,DenseMatrix:s}),u=createAlgorithm14({typed:t});return t(name$2J,{number:roundNumber,"number, number":roundNumber,"number, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return new i(e).toDecimalPlaces(t.toNumber())},Complex:function(e){return e.round()},"Complex, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Complex, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);var n=t.toNumber();return e.round(n)},BigNumber:function(e){return e.toDecimalPlaces(0)},"BigNumber, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.toDecimalPlaces(t.toNumber())},Fraction:function(e){return e.round()},"Fraction, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Fraction, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.round(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"SparseMatrix, number | BigNumber":function(e,t){return o(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"Array, number | BigNumber":function(e,t){return u(n(e),t,this,!1).valueOf()},"number | Complex | BigNumber | Fraction, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):l(t,e,this,!0)},"number | Complex | BigNumber | Fraction, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | Complex | BigNumber | Fraction, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$2I="log",dependencies$2I=["config","typed","divideScalar","Complex"],createLog=factory(name$2I,dependencies$2I,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e;return t(name$2I,{number:function(e){return e>=0||n.predictable?logNumber(e):new a(e,0).log()},Complex:function(e){return e.log()},BigNumber:function(e){return!e.isNegative()||n.predictable?e.ln():new a(e.toNumber(),0).log()},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),this(t))}})})),name$2H="log1p",dependencies$2H=["typed","config","divideScalar","log","Complex"],createLog1p=factory(name$2H,dependencies$2H,(e=>{var{typed:t,config:n,divideScalar:r,log:a,Complex:i}=e;return t(name$2H,{number:function(e){return e>=-1||n.predictable?log1p$1(e):s(new i(e,0))},Complex:s,BigNumber:function(e){var t=e.plus(1);return!t.isNegative()||n.predictable?t.ln():s(new i(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),a(t))}});function s(e){var t=e.re+1;return new i(Math.log(Math.sqrt(t*t+e.im*e.im)),Math.atan2(e.im,t))}})),name$2G="nthRoots",dependencies$2G=["config","typed","divideScalar","Complex"],createNthRoots=factory(name$2G,dependencies$2G,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e,i=[function(e){return new a(e,0)},function(e){return new a(0,e)},function(e){return new a(-e,0)},function(e){return new a(0,-e)}];function s(e,t){if(t<0)throw new Error("Root must be greater than zero");if(0===t)throw new Error("Root must be non-zero");if(t%1!=0)throw new Error("Root must be an integer");if(0===e||0===e.abs())return[new a(0,0)];var n,r="number"==typeof e;(r||0===e.re||0===e.im)&&(n=r?2*+(e<0):0===e.im?2*+(e.re<0):2*+(e.im<0)+1);for(var s=e.arg(),o=e.abs(),l=[],u=Math.pow(o,1/t),c=0;c{var{typed:t,equalScalar:n,matrix:r,pow:a,DenseMatrix:i}=e,s=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm11({typed:t,equalScalar:n}),u=createAlgorithm12({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$2F,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,a)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(r(t),e,this,!0).valueOf()}})})),name$2E="dotDivide",dependencies$2E=["typed","matrix","equalScalar","divideScalar","DenseMatrix"],createDotDivide=factory(name$2E,dependencies$2E,(e=>{var{typed:t,matrix:n,equalScalar:r,divideScalar:a,DenseMatrix:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm03({typed:t}),l=createAlgorithm07({typed:t,DenseMatrix:i}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2E,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return u(e,t,a,!1)},"DenseMatrix, any":function(e,t){return d(e,t,a,!1)},"any, SparseMatrix":function(e,t){return c(t,e,a,!0)},"any, DenseMatrix":function(e,t){return d(t,e,a,!0)},"Array, any":function(e,t){return d(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,a,!0).valueOf()}})}));function createSolveValidation(e){var{DenseMatrix:t}=e;return function(e,n,r){var a=e.size();if(2!==a.length)throw new RangeError("Matrix must be two dimensional (size: "+format$1(a)+")");var i=a[0];if(i!==a[1])throw new RangeError("Matrix must be square (size: "+format$1(a)+")");var s=[];if(isMatrix(n)){var o=n.size(),l=n._data;if(1===o.length){if(o[0]!==i)throw new RangeError("Dimension mismatch. Matrix columns must match vector length.");for(var u=0;u{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2D,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=[],f=0;ff&&(b.push(p[C]),v.push(A))}if(s(g,0))throw new Error("Linear system cannot be solved since matrix is singular");for(var V=r(y,g),x=0,S=v.length;x{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2C,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=[],f=c-1;f>=0;f--){var y=n[f][0]||0;if(s(y,0))h[f]=[0];else{for(var g=0,b=[],v=[],N=m[f],T=m[f+1]-1;T>=N;T--){var C=d[T];C===f?g=p[T]:C=0;m--){var h=n[m][0]||0,f=void 0;if(s(h,0))f=0;else{var y=d[m][m];if(s(y,0))throw new Error("Linear system cannot be solved since matrix is singular");f=r(h,y);for(var g=m-1;g>=0;g--)n[g]=[i(n[g][0]||0,a(f,d[g][m]))]}p[m]=[f]}return new o({data:p,size:[u,1]})}})),name$2B="lsolveAll",dependencies$2B=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createLsolveAll=factory(name$2B,dependencies$2B,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2B,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=0;hh&&(b.push(p[A]),v.push(V))}if(s(C,0))if(s(g[h],0)){if(0===y){var x=[...g];x[h]=1;for(var S=0,w=v.length;Snew o({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1],d=0;dnew o({data:e.map((e=>[e])),size:[c,1]})))}})),name$2A="usolveAll",dependencies$2A=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createUsolveAll=factory(name$2A,dependencies$2A,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2A,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=c-1;h>=0;h--)for(var f=n.length,y=0;y=N;C--){var A=d[C];A===h?T=p[C]:Anew o({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1]-1;p>=0;p--)for(var d=n.length,m=0;m=0;y--)f[y]=i(f[y],u[y][p]);n.push(f)}}else{if(0===m)return[];n.splice(m,1),m-=1,d-=1}else{h[p]=r(h[p],u[p][p]);for(var g=p-1;g>=0;g--)h[g]=i(h[g],a(h[p],u[g][p]))}}return n.map((e=>new o({data:e.map((e=>[e])),size:[c,1]})))}})),name$2z="algorithm08",dependencies$2z=["typed","equalScalar"],createAlgorithm08=factory(name$2z,dependencies$2z,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");if(!i||!c)throw new Error("Cannot perform operation on Pattern Sparse Matrices");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));for(var T,C,A,V,x=[],S=[],w=[],E=[],D=[],O=0;O{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2y,{"number, number":leftShiftNumber,"BigNumber, BigNumber":leftShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2x="rightArithShift",dependencies$2x=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightArithShift=factory(name$2x,dependencies$2x,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2x,{"number, number":rightArithShiftNumber,"BigNumber, BigNumber":rightArithShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2w="rightLogShift",dependencies$2w=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightLogShift=factory(name$2w,dependencies$2w,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2w,{"number, number":rightLogShiftNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2v="and",dependencies$2v=["typed","matrix","equalScalar","zeros","not"],createAnd=factory(name$2v,dependencies$2v,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,not:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$2v,{"number, number":andNumber,"Complex, Complex":function(e,t){return!(0===e.re&&0===e.im||0===t.re&&0===t.im)},"BigNumber, BigNumber":function(e,t){return!(e.isZero()||t.isZero()||e.isNaN()||t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):c(e,t,this,!1)},"any, SparseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):l(t,e,this,!0)},"any, DenseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):c(t,e,this,!0)},"Array, any":function(e,t){return this(n(e),t).valueOf()},"any, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2u="compare",dependencies$2u=["typed","config","matrix","equalScalar","BigNumber","Fraction","DenseMatrix"],createCompare=factory(name$2u,dependencies$2u,(e=>{var{typed:t,config:n,equalScalar:r,matrix:a,BigNumber:i,Fraction:s,DenseMatrix:o}=e,l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:o}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2u,{"boolean, boolean":function(e,t){return e===t?0:e>t?1:-1},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)?0:e>t?1:-1},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,t,n.epsilon)?new i(0):new i(e.cmp(t))},"Fraction, Fraction":function(e,t){return new s(e.compare(t))},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return c(e,t,this,!1)},"DenseMatrix, any":function(e,t){return d(e,t,this,!1)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(a(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(a(t),e,this,!0).valueOf()}})})),naturalSort=function e(t,n){var r,a,i=/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,s=/(^[ ]*|[ ]*$)/g,o=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,l=/^0x[0-9a-f]+$/i,u=/^0/,c=function(t){return e.insensitive&&(""+t).toLowerCase()||""+t},p=c(t).replace(s,"")||"",d=c(n).replace(s,"")||"",m=p.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),h=d.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),f=parseInt(p.match(l),16)||1!==m.length&&p.match(o)&&Date.parse(p),y=parseInt(d.match(l),16)||f&&d.match(o)&&Date.parse(d)||null;if(y){if(fy)return 1}for(var g=0,b=Math.max(m.length,h.length);ga)return 1}return 0},name$2t="compareNatural",dependencies$2t=["typed","compare"],createCompareNatural=factory(name$2t,dependencies$2t,(e=>{var{typed:t,compare:n}=e,r=n.signatures["boolean,boolean"];return t(name$2t,{"any, any":function(e,t){var s,o=typeOf$1(e),l=typeOf$1(t);if(!("number"!==o&&"BigNumber"!==o&&"Fraction"!==o||"number"!==l&&"BigNumber"!==l&&"Fraction"!==l))return"0"!==(s=n(e,t)).toString()?s>0?1:-1:naturalSort(o,l);if("Array"===o||"Matrix"===o||"Array"===l||"Matrix"===l)return 0!==(s=a(this,e,t))?s:naturalSort(o,l);if(o!==l)return naturalSort(o,l);if("Complex"===o)return compareComplexNumbers(e,t);if("Unit"===o)return e.equalBase(t)?this(e.value,t.value):i(this,e.formatUnits(),t.formatUnits());if("boolean"===o)return r(e,t);if("string"===o)return naturalSort(e,t);if("Object"===o)return function(e,t,n){var r=Object.keys(t),a=Object.keys(n);r.sort(naturalSort),a.sort(naturalSort);var s=i(e,r,a);if(0!==s)return s;for(var o=0;on.length?1:t.lengtht.re?1:e.ret.im?1:e.im{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2s,{"any, any":compareText$1,"DenseMatrix, DenseMatrix":function(e,t){return r(e,t,compareText$1)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return a(e,t,compareText$1,!1)},"any, DenseMatrix":function(e,t){return a(t,e,compareText$1,!0)},"Array, any":function(e,t){return a(n(e),t,compareText$1,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,compareText$1,!0).valueOf()}})})),name$2r="equal",dependencies$2r=["typed","matrix","equalScalar","DenseMatrix"],createEqual=factory(name$2r,dependencies$2r,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:r(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,r)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,r,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,r,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,r,!1)},"DenseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, SparseMatrix":function(e,t){return o(t,e,r,!0)},"any, DenseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return u(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,r,!0).valueOf()}})}));factory(name$2r,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:n(e,t)}})}));var name$2q="equalText",dependencies$2q=["typed","compareText","isZero"],createEqualText=factory(name$2q,dependencies$2q,(e=>{var{typed:t,compareText:n,isZero:r}=e;return t(name$2q,{"any, any":function(e,t){return r(n(e,t))}})})),name$2p="smaller",dependencies$2p=["typed","config","matrix","DenseMatrix"],createSmaller=factory(name$2p,dependencies$2p,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2p,{"boolean, boolean":function(e,t){return e{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2o,{"boolean, boolean":function(e,t){return e<=t},"number, number":function(e,t){return e<=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.lte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2n="larger",dependencies$2n=["typed","config","matrix","DenseMatrix"],createLarger=factory(name$2n,dependencies$2n,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2n,{"boolean, boolean":function(e,t){return e>t},"number, number":function(e,t){return e>t&&!nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gt(t)&&!nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1===e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2m="largerEq",dependencies$2m=["typed","config","matrix","DenseMatrix"],createLargerEq=factory(name$2m,dependencies$2m,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2m,{"boolean, boolean":function(e,t){return e>=t},"number, number":function(e,t){return e>=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return-1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2l="deepEqual",dependencies$2l=["typed","equal"],createDeepEqual=factory(name$2l,dependencies$2l,(e=>{var{typed:t,equal:n}=e;return t(name$2l,{"any, any":function(e,t){return r(e.valueOf(),t.valueOf())}});function r(e,t){if(Array.isArray(e)){if(Array.isArray(t)){var a=e.length;if(a!==t.length)return!1;for(var i=0;i{var{typed:t,config:n,equalScalar:r,matrix:a,DenseMatrix:i}=e,s=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm12({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t("unequal",{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:p(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,p)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,p,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,p,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,p)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return l(e,t,p,!1)},"DenseMatrix, any":function(e,t){return c(e,t,p,!1)},"any, SparseMatrix":function(e,t){return l(t,e,p,!0)},"any, DenseMatrix":function(e,t){return c(t,e,p,!0)},"Array, any":function(e,t){return c(a(e),t,p,!1).valueOf()},"any, Array":function(e,t){return c(a(t),e,p,!0).valueOf()}});function p(e,t){return!r(e,t)}}));factory(name$2k,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2k,{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:!n(e,t)}})}));var name$2j="partitionSelect",dependencies$2j=["typed","isNumeric","isNaN","compare"],createPartitionSelect=factory(name$2j,dependencies$2j,(e=>{var{typed:t,isNumeric:n,isNaN:r,compare:a}=e,i=a,s=(e,t)=>-a(e,t);return t(name$2j,{"Array | Matrix, number":function(e,t){return o(e,t,i)},"Array | Matrix, number, string":function(e,t,n){if("asc"===n)return o(e,t,i);if("desc"===n)return o(e,t,s);throw new Error('Compare string must be "asc" or "desc"')},"Array | Matrix, number, function":o});function o(e,t,n){if(!isInteger$1(t)||t<0)throw new Error("k must be a non-negative integer");if(isMatrix(e)){if(e.size().length>1)throw new Error("Only one dimensional matrices supported");return l(e.valueOf(),t,n)}if(Array.isArray(e))return l(e,t,n)}function l(e,t,a){if(t>=e.length)throw new Error("k out of bounds");for(var i=0;i=0){var p=e[u];e[u]=e[l],e[l]=p,--u}else++l;a(e[l],c)>0&&--l,t<=l?o=l:s=l+1}return e[t]}})),name$2i="sort",dependencies$2i=["typed","matrix","compare","compareNatural"],createSort=factory(name$2i,dependencies$2i,(e=>{var{typed:t,matrix:n,compare:r,compareNatural:a}=e,i=r,s=(e,t)=>-r(e,t);return t(name$2i,{Array:function(e){return l(e),e.sort(i)},Matrix:function(e){return u(e),n(e.toArray().sort(i),e.storage())},"Array, function":function(e,t){return l(e),e.sort(t)},"Matrix, function":function(e,t){return u(e),n(e.toArray().sort(t),e.storage())},"Array, string":function(e,t){return l(e),e.sort(o(t))},"Matrix, string":function(e,t){return u(e),n(e.toArray().sort(o(t)),e.storage())}});function o(e){if("asc"===e)return i;if("desc"===e)return s;if("natural"===e)return a;throw new Error('String "asc", "desc", or "natural" expected')}function l(e){if(1!==arraySize(e).length)throw new Error("One dimensional array expected")}function u(e){if(1!==e.size().length)throw new Error("One dimensional matrix expected")}})),name$2h="max",dependencies$2h=["typed","config","numeric","larger"],createMax=factory(name$2h,dependencies$2h,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e;return t(name$2h,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function max");return s(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"max",t)}}function s(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"max",e)}})),void 0===t)throw new Error("Cannot calculate max of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2g="min",dependencies$2g=["typed","config","numeric","smaller"],createMin=factory(name$2g,dependencies$2g,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e;return t(name$2g,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function min");return s(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"min",t)}}function s(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"min",e)}})),void 0===t)throw new Error("Cannot calculate min of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2f="ImmutableDenseMatrix",dependencies$2f=["smaller","DenseMatrix"],createImmutableDenseMatrixClass=factory(name$2f,dependencies$2f,(e=>{var{smaller:t,DenseMatrix:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e)||isArray$1(e)){var a=new n(e,t);this._data=a._data,this._size=a._size,this._datatype=a._datatype,this._min=null,this._max=null}else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,this._datatype=e.datatype,this._min=void 0!==e.min?e.min:null,this._max=void 0!==e.max?e.max:null;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t,this._min=null,this._max=null}}return r.prototype=new n,r.prototype.type="ImmutableDenseMatrix",r.prototype.isImmutableDenseMatrix=!0,r.prototype.subset=function(e){switch(arguments.length){case 1:var t=n.prototype.subset.call(this,e);return isMatrix(t)?new r({data:t._data,size:t._size,datatype:t._datatype}):t;case 2:case 3:throw new Error("Cannot invoke set subset on an Immutable Matrix instance");default:throw new SyntaxError("Wrong number of arguments")}},r.prototype.set=function(){throw new Error("Cannot invoke set on an Immutable Matrix instance")},r.prototype.resize=function(){throw new Error("Cannot invoke resize on an Immutable Matrix instance")},r.prototype.reshape=function(){throw new Error("Cannot invoke reshape on an Immutable Matrix instance")},r.prototype.clone=function(){return new r({data:clone$3(this._data),size:clone$3(this._size),datatype:this._datatype})},r.prototype.toJSON=function(){return{mathjs:"ImmutableDenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},r.fromJSON=function(e){return new r(e)},r.prototype.swapRows=function(){throw new Error("Cannot invoke swapRows on an Immutable Matrix instance")},r.prototype.min=function(){if(null===this._min){var e=null;this.forEach((function(n){(null===e||t(n,e))&&(e=n)})),this._min=null!==e?e:void 0}return this._min},r.prototype.max=function(){if(null===this._max){var e=null;this.forEach((function(n){(null===e||t(e,n))&&(e=n)})),this._max=null!==e?e:void 0}return this._max},r}),{isClass:!0}),name$2e="Index",dependencies$2e=["ImmutableDenseMatrix"],createIndexClass=factory(name$2e,dependencies$2e,(e=>{var{ImmutableDenseMatrix:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this._dimensions=[],this._isScalar=!0;for(var t=0,a=arguments.length;t{var{smaller:t,larger:n}=e,r=1/Math.log((1+Math.sqrt(5))/2);function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._minimum=null,this._size=0}function i(e,t,n){t.left.right=t.right,t.right.left=t.left,n.degree--,n.child===t&&(n.child=t.right),0===n.degree&&(n.child=null),t.left=e,t.right=e.right,e.right=t,t.right.left=t,t.parent=null,t.mark=!1}function s(e,t){var n=t.parent;n&&(t.mark?(i(e,t,n),s(n)):t.mark=!0)}a.prototype.type="FibonacciHeap",a.prototype.isFibonacciHeap=!0,a.prototype.insert=function(e,n){var r={key:e,value:n,degree:0};if(this._minimum){var a=this._minimum;r.left=a,r.right=a.right,a.right=r,r.right.left=r,t(e,a.key)&&(this._minimum=r)}else r.left=r,r.right=r,this._minimum=r;return this._size++,r},a.prototype.size=function(){return this._size},a.prototype.clear=function(){this._minimum=null,this._size=0},a.prototype.isEmpty=function(){return 0===this._size},a.prototype.extractMinimum=function(){var e=this._minimum;if(null===e)return e;for(var a=this._minimum,i=e.degree,s=e.child;i>0;){var l=s.right;s.left.right=s.right,s.right.left=s.left,s.left=a,s.right=a.right,a.right=s,s.right.left=s,s.parent=null,s=l,i--}return e.left.right=e.right,e.right.left=e.left,a=e===e.right?null:function(e,a){var i,s=Math.floor(Math.log(a)*r)+1,l=new Array(s),u=0,c=e;if(c)for(u++,c=c.right;c!==e;)u++,c=c.right;for(;u>0;){for(var p=c.degree,d=c.right;i=l[p];){if(n(c.key,i.key)){var m=i;i=c,c=m}o(i,c),l[p]=null,p++}l[p]=c,c=d,u--}e=null;for(var h=0;h{var{addScalar:t,equalScalar:n,FibonacciHeap:r}=e;function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._values=[],this._heap=new r}return a.prototype.type="Spa",a.prototype.isSpa=!0,a.prototype.set=function(e,t){if(this._values[e])this._values[e].value=t;else{var n=this._heap.insert(e,t);this._values[e]=n}},a.prototype.get=function(e){var t=this._values[e];return t?t.value:0},a.prototype.accumulate=function(e,n){var r=this._values[e];r?r.value=t(r.value,n):(r=this._heap.insert(e,n),this._values[e]=r)},a.prototype.forEach=function(e,t,r){var a=this._heap,i=this._values,s=[],o=a.extractMinimum();for(o&&s.push(o);o&&o.key<=t;)o.key>=e&&(n(o.value,0)||r(o.key,o.value,this)),(o=a.extractMinimum())&&s.push(o);for(var l=0;l{var t,n,r,{on:a,config:i,addScalar:s,subtract:o,multiplyScalar:l,divideScalar:u,pow:c,abs:p,fix:d,round:m,equal:h,isNumeric:f,format:y,number:g,Complex:b,BigNumber:v,Fraction:N}=e,T=g;function C(e,t){if(!(this instanceof C))throw new Error("Constructor must be called with the new operator");if(null!=e&&!f(e)&&!isComplex(e))throw new TypeError("First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined");if(void 0!==t&&("string"!=typeof t||""===t))throw new TypeError("Second parameter in Unit constructor must be a string");if(void 0!==t){var n=C.parse(t);this.units=n.units,this.dimensions=n.dimensions}else{this.units=[{unit:F,prefix:R.NONE,power:0}],this.dimensions=[];for(var r=0;r<_.length;r++)this.dimensions[r]=0}this.value=null!=e?this._normalize(e):null,this.fixPrefix=!1,this.skipAutomaticSimplification=!0}function A(){for(;" "===r||"\t"===r;)x()}function V(e){return e>="0"&&e<="9"}function x(){n++,r=t.charAt(n)}function S(e){n=e,r=t.charAt(n)}function w(){var e="",t=n;if("+"===r?x():"-"===r&&(e+=r,x()),!function(e){return e>="0"&&e<="9"||"."===e}(r))return S(t),null;if("."===r){if(e+=r,x(),!V(r))return S(t),null}else{for(;V(r);)e+=r,x();"."===r&&(e+=r,x())}for(;V(r);)e+=r,x();if("E"===r||"e"===r){var a="",i=n;if(a+=r,x(),"+"!==r&&"-"!==r||(a+=r,x()),!V(r))return S(i),e;for(e+=a;V(r);)e+=r,x()}return e}function E(){for(var e="";V(r)||C.isValidAlpha(r);)e+=r,x();var t=e.charAt(0);return C.isValidAlpha(t)?e:null}function D(e){return r===e?(x(),e):null}C.prototype.type="Unit",C.prototype.isUnit=!0,C.parse=function(e,a){if(a=a||{},n=-1,r="","string"!=typeof(t=e))throw new TypeError("Invalid argument in Unit.parse, string expected");var s=new C;s.units=[];var o=1,l=!1;x(),A();var u=w(),c=null;if(u){if("BigNumber"===i.number)c=new v(u);else if("Fraction"===i.number)try{c=new N(u)}catch(e){c=parseFloat(u)}else c=parseFloat(u);A(),D("*")?(o=1,l=!0):D("/")&&(o=-1,l=!0)}for(var p=[],d=1;;){for(A();"("===r;)p.push(o),d*=o,o=1,x(),A();var m;if(!r)break;var h=r;if(null===(m=E()))throw new SyntaxError('Unexpected "'+h+'" in "'+t+'" at index '+n.toString());var f=O(m);if(null===f)throw new SyntaxError('Unit "'+m+'" not found.');var y=o*d;if(A(),D("^")){A();var g=w();if(null===g)throw new SyntaxError('In "'+e+'", "^" must be followed by a floating-point number');y*=g}s.units.push({unit:f.unit,prefix:f.prefix,power:y});for(var b=0;b<_.length;b++)s.dimensions[b]+=(f.unit.dimensions[b]||0)*y;for(A();")"===r;){if(0===p.length)throw new SyntaxError('Unmatched ")" in "'+t+'" at index '+n.toString());d/=p.pop(),x(),A()}if(l=!1,D("*")?(o=1,l=!0):D("/")?(o=-1,l=!0):o=1,f.unit.base){var T=f.unit.base.key;L.auto[T]={unit:f.unit,prefix:f.prefix}}}if(A(),r)throw new SyntaxError('Could not parse: "'+e+'"');if(l)throw new SyntaxError('Trailing characters: "'+e+'"');if(0!==p.length)throw new SyntaxError('Unmatched "(" in "'+t+'"');if(0===s.units.length&&!a.allowNoUnits)throw new SyntaxError('"'+e+'" contains no units');return s.value=void 0!==c?s._normalize(c):null,s},C.prototype.clone=function(){var e=new C;e.fixPrefix=this.fixPrefix,e.skipAutomaticSimplification=this.skipAutomaticSimplification,e.value=clone$3(this.value),e.dimensions=this.dimensions.slice(0),e.units=[];for(var t=0;t1||Math.abs(this.units[0].power-1)>1e-15)},C.prototype._normalize=function(e){if(null==e||0===this.units.length)return e;for(var t=e,n=C._getNumberConverter(typeOf$1(e)),r=0;r{if(hasOwnProperty$2(k,e)){var t=k[e];return{unit:t,prefix:t.prefixes[""]}}for(var n in k)if(hasOwnProperty$2(k,n)&&endsWith(e,n)){var r=k[n],a=e.length-n.length,i=e.substring(0,a),s=hasOwnProperty$2(r.prefixes,i)?r.prefixes[i]:void 0;if(void 0!==s)return{unit:r,prefix:s}}return null}),{hasher:e=>e[0],limit:100});function I(e){return e.equalBase(M.NONE)&&null!==e.value&&!i.predictable?e.value:e}C.isValuelessUnit=function(e){return null!==O(e)},C.prototype.hasBase=function(e){if("string"==typeof e&&(e=M[e]),!e)return!1;for(var t=0;t<_.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},C.prototype.equalBase=function(e){for(var t=0;t<_.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},C.prototype.equals=function(e){return this.equalBase(e)&&h(this.value,e.value)},C.prototype.multiply=function(e){for(var t=this.clone(),n=0;n<_.length;n++)t.dimensions[n]=(this.dimensions[n]||0)+(e.dimensions[n]||0);for(var r=0;r1e-12&&(hasOwnProperty$2(z,o)?r.push({unit:z[o].unit,prefix:z[o].prefix,power:n.dimensions[s]||0}):i=!0)}r.length1e-12){if(!hasOwnProperty$2(L.si,r))throw new Error("Cannot express custom unit "+r+" in SI units");t.push({unit:L.si[r].unit,prefix:L.si[r].prefix,power:e.dimensions[n]||0})}}return e.units=t,e.fixPrefix=!0,e.skipAutomaticSimplification=!0,e},C.prototype.formatUnits=function(){for(var e="",t="",n=0,r=0,a=0;a0?(n++,e+=" "+this.units[a].prefix.name+this.units[a].unit.name,Math.abs(this.units[a].power-1)>1e-15&&(e+="^"+this.units[a].power)):this.units[a].power<0&&r++;if(r>0)for(var i=0;i0?(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,Math.abs(this.units[i].power+1)>1e-15&&(t+="^"+-this.units[i].power)):(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,t+="^"+this.units[i].power));e=e.substr(1),t=t.substr(1),n>1&&r>0&&(e="("+e+")"),r>1&&n>0&&(t="("+t+")");var s=e;return n>0&&r>0&&(s+=" / "),s+t},C.prototype.format=function(e){var t=this.skipAutomaticSimplification||null===this.value?this.clone():this.simplify(),n=!1;for(var r in void 0!==t.value&&null!==t.value&&isComplex(t.value)&&(n=Math.abs(t.value.re)<1e-14),t.units)hasOwnProperty$2(t.units,r)&&t.units[r].unit&&("VA"===t.units[r].unit.name&&n?t.units[r].unit=k.VAR:"VAR"!==t.units[r].unit.name||n||(t.units[r].unit=k.VA));1!==t.units.length||t.fixPrefix||Math.abs(t.units[0].power-Math.round(t.units[0].power))<1e-14&&(t.units[0].prefix=t._bestPrefix());var a=t._denormalize(t.value),i=null!==t.value?y(a,e||{}):"",s=t.formatUnits();return t.value&&isComplex(t.value)&&(i="("+i+")"),s.length>0&&i.length>0&&(i+=" "),i+s},C.prototype._bestPrefix=function(){if(1!==this.units.length)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");if(Math.abs(this.units[0].power-Math.round(this.units[0].power))>=1e-14)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");var e=null!==this.value?p(this.value):0,t=p(this.units[0].unit.value),n=this.units[0].prefix;if(0===e)return n;var r=this.units[0].power,a=Math.log(e/Math.pow(n.value*t,r))/Math.LN10-1.2;if(a>-2.200001&&a<1.800001)return n;a=Math.abs(a);var i=this.units[0].unit.prefixes;for(var s in i)if(hasOwnProperty$2(i,s)){var o=i[s];if(o.scientific){var l=Math.abs(Math.log(e/Math.pow(o.value*t,r))/Math.LN10-1.2);(l0))},k={meter:{name:"meter",base:M.LENGTH,prefixes:R.LONG,value:1,offset:0},inch:{name:"inch",base:M.LENGTH,prefixes:R.NONE,value:.0254,offset:0},foot:{name:"foot",base:M.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yard:{name:"yard",base:M.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mile:{name:"mile",base:M.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},link:{name:"link",base:M.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rod:{name:"rod",base:M.LENGTH,prefixes:R.NONE,value:5.0292,offset:0},chain:{name:"chain",base:M.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},angstrom:{name:"angstrom",base:M.LENGTH,prefixes:R.NONE,value:1e-10,offset:0},m:{name:"m",base:M.LENGTH,prefixes:R.SHORT,value:1,offset:0},in:{name:"in",base:M.LENGTH,prefixes:R.NONE,value:.0254,offset:0},ft:{name:"ft",base:M.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yd:{name:"yd",base:M.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mi:{name:"mi",base:M.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},li:{name:"li",base:M.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rd:{name:"rd",base:M.LENGTH,prefixes:R.NONE,value:5.02921,offset:0},ch:{name:"ch",base:M.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},mil:{name:"mil",base:M.LENGTH,prefixes:R.NONE,value:254e-7,offset:0},m2:{name:"m2",base:M.SURFACE,prefixes:R.SQUARED,value:1,offset:0},sqin:{name:"sqin",base:M.SURFACE,prefixes:R.NONE,value:64516e-8,offset:0},sqft:{name:"sqft",base:M.SURFACE,prefixes:R.NONE,value:.09290304,offset:0},sqyd:{name:"sqyd",base:M.SURFACE,prefixes:R.NONE,value:.83612736,offset:0},sqmi:{name:"sqmi",base:M.SURFACE,prefixes:R.NONE,value:2589988.110336,offset:0},sqrd:{name:"sqrd",base:M.SURFACE,prefixes:R.NONE,value:25.29295,offset:0},sqch:{name:"sqch",base:M.SURFACE,prefixes:R.NONE,value:404.6873,offset:0},sqmil:{name:"sqmil",base:M.SURFACE,prefixes:R.NONE,value:6.4516e-10,offset:0},acre:{name:"acre",base:M.SURFACE,prefixes:R.NONE,value:4046.86,offset:0},hectare:{name:"hectare",base:M.SURFACE,prefixes:R.NONE,value:1e4,offset:0},m3:{name:"m3",base:M.VOLUME,prefixes:R.CUBIC,value:1,offset:0},L:{name:"L",base:M.VOLUME,prefixes:R.SHORT,value:.001,offset:0},l:{name:"l",base:M.VOLUME,prefixes:R.SHORT,value:.001,offset:0},litre:{name:"litre",base:M.VOLUME,prefixes:R.LONG,value:.001,offset:0},cuin:{name:"cuin",base:M.VOLUME,prefixes:R.NONE,value:16387064e-12,offset:0},cuft:{name:"cuft",base:M.VOLUME,prefixes:R.NONE,value:.028316846592,offset:0},cuyd:{name:"cuyd",base:M.VOLUME,prefixes:R.NONE,value:.764554857984,offset:0},teaspoon:{name:"teaspoon",base:M.VOLUME,prefixes:R.NONE,value:5e-6,offset:0},tablespoon:{name:"tablespoon",base:M.VOLUME,prefixes:R.NONE,value:15e-6,offset:0},drop:{name:"drop",base:M.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},gtt:{name:"gtt",base:M.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},minim:{name:"minim",base:M.VOLUME,prefixes:R.NONE,value:6.161152e-8,offset:0},fluiddram:{name:"fluiddram",base:M.VOLUME,prefixes:R.NONE,value:36966911e-13,offset:0},fluidounce:{name:"fluidounce",base:M.VOLUME,prefixes:R.NONE,value:2957353e-11,offset:0},gill:{name:"gill",base:M.VOLUME,prefixes:R.NONE,value:.0001182941,offset:0},cc:{name:"cc",base:M.VOLUME,prefixes:R.NONE,value:1e-6,offset:0},cup:{name:"cup",base:M.VOLUME,prefixes:R.NONE,value:.0002365882,offset:0},pint:{name:"pint",base:M.VOLUME,prefixes:R.NONE,value:.0004731765,offset:0},quart:{name:"quart",base:M.VOLUME,prefixes:R.NONE,value:.0009463529,offset:0},gallon:{name:"gallon",base:M.VOLUME,prefixes:R.NONE,value:.003785412,offset:0},beerbarrel:{name:"beerbarrel",base:M.VOLUME,prefixes:R.NONE,value:.1173478,offset:0},oilbarrel:{name:"oilbarrel",base:M.VOLUME,prefixes:R.NONE,value:.1589873,offset:0},hogshead:{name:"hogshead",base:M.VOLUME,prefixes:R.NONE,value:.238481,offset:0},fldr:{name:"fldr",base:M.VOLUME,prefixes:R.NONE,value:36966911e-13,offset:0},floz:{name:"floz",base:M.VOLUME,prefixes:R.NONE,value:2957353e-11,offset:0},gi:{name:"gi",base:M.VOLUME,prefixes:R.NONE,value:.0001182941,offset:0},cp:{name:"cp",base:M.VOLUME,prefixes:R.NONE,value:.0002365882,offset:0},pt:{name:"pt",base:M.VOLUME,prefixes:R.NONE,value:.0004731765,offset:0},qt:{name:"qt",base:M.VOLUME,prefixes:R.NONE,value:.0009463529,offset:0},gal:{name:"gal",base:M.VOLUME,prefixes:R.NONE,value:.003785412,offset:0},bbl:{name:"bbl",base:M.VOLUME,prefixes:R.NONE,value:.1173478,offset:0},obl:{name:"obl",base:M.VOLUME,prefixes:R.NONE,value:.1589873,offset:0},g:{name:"g",base:M.MASS,prefixes:R.SHORT,value:.001,offset:0},gram:{name:"gram",base:M.MASS,prefixes:R.LONG,value:.001,offset:0},ton:{name:"ton",base:M.MASS,prefixes:R.SHORT,value:907.18474,offset:0},t:{name:"t",base:M.MASS,prefixes:R.SHORT,value:1e3,offset:0},tonne:{name:"tonne",base:M.MASS,prefixes:R.LONG,value:1e3,offset:0},grain:{name:"grain",base:M.MASS,prefixes:R.NONE,value:6479891e-11,offset:0},dram:{name:"dram",base:M.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},ounce:{name:"ounce",base:M.MASS,prefixes:R.NONE,value:.028349523125,offset:0},poundmass:{name:"poundmass",base:M.MASS,prefixes:R.NONE,value:.45359237,offset:0},hundredweight:{name:"hundredweight",base:M.MASS,prefixes:R.NONE,value:45.359237,offset:0},stick:{name:"stick",base:M.MASS,prefixes:R.NONE,value:.115,offset:0},stone:{name:"stone",base:M.MASS,prefixes:R.NONE,value:6.35029318,offset:0},gr:{name:"gr",base:M.MASS,prefixes:R.NONE,value:6479891e-11,offset:0},dr:{name:"dr",base:M.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},oz:{name:"oz",base:M.MASS,prefixes:R.NONE,value:.028349523125,offset:0},lbm:{name:"lbm",base:M.MASS,prefixes:R.NONE,value:.45359237,offset:0},cwt:{name:"cwt",base:M.MASS,prefixes:R.NONE,value:45.359237,offset:0},s:{name:"s",base:M.TIME,prefixes:R.SHORT,value:1,offset:0},min:{name:"min",base:M.TIME,prefixes:R.NONE,value:60,offset:0},h:{name:"h",base:M.TIME,prefixes:R.NONE,value:3600,offset:0},second:{name:"second",base:M.TIME,prefixes:R.LONG,value:1,offset:0},sec:{name:"sec",base:M.TIME,prefixes:R.LONG,value:1,offset:0},minute:{name:"minute",base:M.TIME,prefixes:R.NONE,value:60,offset:0},hour:{name:"hour",base:M.TIME,prefixes:R.NONE,value:3600,offset:0},day:{name:"day",base:M.TIME,prefixes:R.NONE,value:86400,offset:0},week:{name:"week",base:M.TIME,prefixes:R.NONE,value:604800,offset:0},month:{name:"month",base:M.TIME,prefixes:R.NONE,value:2629800,offset:0},year:{name:"year",base:M.TIME,prefixes:R.NONE,value:31557600,offset:0},decade:{name:"decade",base:M.TIME,prefixes:R.NONE,value:315576e3,offset:0},century:{name:"century",base:M.TIME,prefixes:R.NONE,value:315576e4,offset:0},millennium:{name:"millennium",base:M.TIME,prefixes:R.NONE,value:315576e5,offset:0},hertz:{name:"Hertz",base:M.FREQUENCY,prefixes:R.LONG,value:1,offset:0,reciprocal:!0},Hz:{name:"Hz",base:M.FREQUENCY,prefixes:R.SHORT,value:1,offset:0,reciprocal:!0},rad:{name:"rad",base:M.ANGLE,prefixes:R.SHORT,value:1,offset:0},radian:{name:"radian",base:M.ANGLE,prefixes:R.LONG,value:1,offset:0},deg:{name:"deg",base:M.ANGLE,prefixes:R.SHORT,value:null,offset:0},degree:{name:"degree",base:M.ANGLE,prefixes:R.LONG,value:null,offset:0},grad:{name:"grad",base:M.ANGLE,prefixes:R.SHORT,value:null,offset:0},gradian:{name:"gradian",base:M.ANGLE,prefixes:R.LONG,value:null,offset:0},cycle:{name:"cycle",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},arcsec:{name:"arcsec",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},arcmin:{name:"arcmin",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},A:{name:"A",base:M.CURRENT,prefixes:R.SHORT,value:1,offset:0},ampere:{name:"ampere",base:M.CURRENT,prefixes:R.LONG,value:1,offset:0},K:{name:"K",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:0},degC:{name:"degC",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:273.15},degF:{name:"degF",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:459.67},degR:{name:"degR",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:0},kelvin:{name:"kelvin",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:0},celsius:{name:"celsius",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:273.15},fahrenheit:{name:"fahrenheit",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:459.67},rankine:{name:"rankine",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:0},mol:{name:"mol",base:M.AMOUNT_OF_SUBSTANCE,prefixes:R.SHORT,value:1,offset:0},mole:{name:"mole",base:M.AMOUNT_OF_SUBSTANCE,prefixes:R.LONG,value:1,offset:0},cd:{name:"cd",base:M.LUMINOUS_INTENSITY,prefixes:R.SHORT,value:1,offset:0},candela:{name:"candela",base:M.LUMINOUS_INTENSITY,prefixes:R.LONG,value:1,offset:0},N:{name:"N",base:M.FORCE,prefixes:R.SHORT,value:1,offset:0},newton:{name:"newton",base:M.FORCE,prefixes:R.LONG,value:1,offset:0},dyn:{name:"dyn",base:M.FORCE,prefixes:R.SHORT,value:1e-5,offset:0},dyne:{name:"dyne",base:M.FORCE,prefixes:R.LONG,value:1e-5,offset:0},lbf:{name:"lbf",base:M.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},poundforce:{name:"poundforce",base:M.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},kip:{name:"kip",base:M.FORCE,prefixes:R.LONG,value:4448.2216,offset:0},kilogramforce:{name:"kilogramforce",base:M.FORCE,prefixes:R.NONE,value:9.80665,offset:0},J:{name:"J",base:M.ENERGY,prefixes:R.SHORT,value:1,offset:0},joule:{name:"joule",base:M.ENERGY,prefixes:R.SHORT,value:1,offset:0},erg:{name:"erg",base:M.ENERGY,prefixes:R.NONE,value:1e-7,offset:0},Wh:{name:"Wh",base:M.ENERGY,prefixes:R.SHORT,value:3600,offset:0},BTU:{name:"BTU",base:M.ENERGY,prefixes:R.BTU,value:1055.05585262,offset:0},eV:{name:"eV",base:M.ENERGY,prefixes:R.SHORT,value:1602176565e-28,offset:0},electronvolt:{name:"electronvolt",base:M.ENERGY,prefixes:R.LONG,value:1602176565e-28,offset:0},W:{name:"W",base:M.POWER,prefixes:R.SHORT,value:1,offset:0},watt:{name:"watt",base:M.POWER,prefixes:R.LONG,value:1,offset:0},hp:{name:"hp",base:M.POWER,prefixes:R.NONE,value:745.6998715386,offset:0},VAR:{name:"VAR",base:M.POWER,prefixes:R.SHORT,value:b.I,offset:0},VA:{name:"VA",base:M.POWER,prefixes:R.SHORT,value:1,offset:0},Pa:{name:"Pa",base:M.PRESSURE,prefixes:R.SHORT,value:1,offset:0},psi:{name:"psi",base:M.PRESSURE,prefixes:R.NONE,value:6894.75729276459,offset:0},atm:{name:"atm",base:M.PRESSURE,prefixes:R.NONE,value:101325,offset:0},bar:{name:"bar",base:M.PRESSURE,prefixes:R.SHORTLONG,value:1e5,offset:0},torr:{name:"torr",base:M.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmHg:{name:"mmHg",base:M.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmH2O:{name:"mmH2O",base:M.PRESSURE,prefixes:R.NONE,value:9.80665,offset:0},cmH2O:{name:"cmH2O",base:M.PRESSURE,prefixes:R.NONE,value:98.0665,offset:0},coulomb:{name:"coulomb",base:M.ELECTRIC_CHARGE,prefixes:R.LONG,value:1,offset:0},C:{name:"C",base:M.ELECTRIC_CHARGE,prefixes:R.SHORT,value:1,offset:0},farad:{name:"farad",base:M.ELECTRIC_CAPACITANCE,prefixes:R.LONG,value:1,offset:0},F:{name:"F",base:M.ELECTRIC_CAPACITANCE,prefixes:R.SHORT,value:1,offset:0},volt:{name:"volt",base:M.ELECTRIC_POTENTIAL,prefixes:R.LONG,value:1,offset:0},V:{name:"V",base:M.ELECTRIC_POTENTIAL,prefixes:R.SHORT,value:1,offset:0},ohm:{name:"ohm",base:M.ELECTRIC_RESISTANCE,prefixes:R.SHORTLONG,value:1,offset:0},henry:{name:"henry",base:M.ELECTRIC_INDUCTANCE,prefixes:R.LONG,value:1,offset:0},H:{name:"H",base:M.ELECTRIC_INDUCTANCE,prefixes:R.SHORT,value:1,offset:0},siemens:{name:"siemens",base:M.ELECTRIC_CONDUCTANCE,prefixes:R.LONG,value:1,offset:0},S:{name:"S",base:M.ELECTRIC_CONDUCTANCE,prefixes:R.SHORT,value:1,offset:0},weber:{name:"weber",base:M.MAGNETIC_FLUX,prefixes:R.LONG,value:1,offset:0},Wb:{name:"Wb",base:M.MAGNETIC_FLUX,prefixes:R.SHORT,value:1,offset:0},tesla:{name:"tesla",base:M.MAGNETIC_FLUX_DENSITY,prefixes:R.LONG,value:1,offset:0},T:{name:"T",base:M.MAGNETIC_FLUX_DENSITY,prefixes:R.SHORT,value:1,offset:0},b:{name:"b",base:M.BIT,prefixes:R.BINARY_SHORT,value:1,offset:0},bits:{name:"bits",base:M.BIT,prefixes:R.BINARY_LONG,value:1,offset:0},B:{name:"B",base:M.BIT,prefixes:R.BINARY_SHORT,value:8,offset:0},bytes:{name:"bytes",base:M.BIT,prefixes:R.BINARY_LONG,value:8,offset:0}},$={meters:"meter",inches:"inch",feet:"foot",yards:"yard",miles:"mile",links:"link",rods:"rod",chains:"chain",angstroms:"angstrom",lt:"l",litres:"litre",liter:"litre",liters:"litre",teaspoons:"teaspoon",tablespoons:"tablespoon",minims:"minim",fluiddrams:"fluiddram",fluidounces:"fluidounce",gills:"gill",cups:"cup",pints:"pint",quarts:"quart",gallons:"gallon",beerbarrels:"beerbarrel",oilbarrels:"oilbarrel",hogsheads:"hogshead",gtts:"gtt",grams:"gram",tons:"ton",tonnes:"tonne",grains:"grain",drams:"dram",ounces:"ounce",poundmasses:"poundmass",hundredweights:"hundredweight",sticks:"stick",lb:"lbm",lbs:"lbm",kips:"kip",kgf:"kilogramforce",acres:"acre",hectares:"hectare",sqfeet:"sqft",sqyard:"sqyd",sqmile:"sqmi",sqmiles:"sqmi",mmhg:"mmHg",mmh2o:"mmH2O",cmh2o:"cmH2O",seconds:"second",secs:"second",minutes:"minute",mins:"minute",hours:"hour",hr:"hour",hrs:"hour",days:"day",weeks:"week",months:"month",years:"year",decades:"decade",centuries:"century",millennia:"millennium",hertz:"hertz",radians:"radian",degrees:"degree",gradians:"gradian",cycles:"cycle",arcsecond:"arcsec",arcseconds:"arcsec",arcminute:"arcmin",arcminutes:"arcmin",BTUs:"BTU",watts:"watt",joules:"joule",amperes:"ampere",coulombs:"coulomb",volts:"volt",ohms:"ohm",farads:"farad",webers:"weber",teslas:"tesla",electronvolts:"electronvolt",moles:"mole",bit:"bits",byte:"bytes"};function B(e){if("BigNumber"===e.number){var t=createBigNumberPi(v);k.rad.value=new v(1),k.deg.value=t.div(180),k.grad.value=t.div(200),k.cycle.value=t.times(2),k.arcsec.value=t.div(648e3),k.arcmin.value=t.div(10800)}else k.rad.value=1,k.deg.value=Math.PI/180,k.grad.value=Math.PI/200,k.cycle.value=2*Math.PI,k.arcsec.value=Math.PI/648e3,k.arcmin.value=Math.PI/10800;k.radian.value=k.rad.value,k.degree.value=k.deg.value,k.gradian.value=k.grad.value}B(i),a&&a("config",(function(e,t){e.number!==t.number&&B(e)}));var L={si:{NONE:{unit:F,prefix:R.NONE[""]},LENGTH:{unit:k.m,prefix:R.SHORT[""]},MASS:{unit:k.g,prefix:R.SHORT.k},TIME:{unit:k.s,prefix:R.SHORT[""]},CURRENT:{unit:k.A,prefix:R.SHORT[""]},TEMPERATURE:{unit:k.K,prefix:R.SHORT[""]},LUMINOUS_INTENSITY:{unit:k.cd,prefix:R.SHORT[""]},AMOUNT_OF_SUBSTANCE:{unit:k.mol,prefix:R.SHORT[""]},ANGLE:{unit:k.rad,prefix:R.SHORT[""]},BIT:{unit:k.bits,prefix:R.SHORT[""]},FORCE:{unit:k.N,prefix:R.SHORT[""]},ENERGY:{unit:k.J,prefix:R.SHORT[""]},POWER:{unit:k.W,prefix:R.SHORT[""]},PRESSURE:{unit:k.Pa,prefix:R.SHORT[""]},ELECTRIC_CHARGE:{unit:k.C,prefix:R.SHORT[""]},ELECTRIC_CAPACITANCE:{unit:k.F,prefix:R.SHORT[""]},ELECTRIC_POTENTIAL:{unit:k.V,prefix:R.SHORT[""]},ELECTRIC_RESISTANCE:{unit:k.ohm,prefix:R.SHORT[""]},ELECTRIC_INDUCTANCE:{unit:k.H,prefix:R.SHORT[""]},ELECTRIC_CONDUCTANCE:{unit:k.S,prefix:R.SHORT[""]},MAGNETIC_FLUX:{unit:k.Wb,prefix:R.SHORT[""]},MAGNETIC_FLUX_DENSITY:{unit:k.T,prefix:R.SHORT[""]},FREQUENCY:{unit:k.Hz,prefix:R.SHORT[""]}}};L.cgs=JSON.parse(JSON.stringify(L.si)),L.cgs.LENGTH={unit:k.m,prefix:R.SHORT.c},L.cgs.MASS={unit:k.g,prefix:R.SHORT[""]},L.cgs.FORCE={unit:k.dyn,prefix:R.SHORT[""]},L.cgs.ENERGY={unit:k.erg,prefix:R.NONE[""]},L.us=JSON.parse(JSON.stringify(L.si)),L.us.LENGTH={unit:k.ft,prefix:R.NONE[""]},L.us.MASS={unit:k.lbm,prefix:R.NONE[""]},L.us.TEMPERATURE={unit:k.degF,prefix:R.NONE[""]},L.us.FORCE={unit:k.lbf,prefix:R.NONE[""]},L.us.ENERGY={unit:k.BTU,prefix:R.BTU[""]},L.us.POWER={unit:k.hp,prefix:R.NONE[""]},L.us.PRESSURE={unit:k.psi,prefix:R.NONE[""]},L.auto=JSON.parse(JSON.stringify(L.si));var z=L.auto;for(var U in C.setUnitSystem=function(e){if(!hasOwnProperty$2(L,e))throw new Error("Unit system "+e+" does not exist. Choices are: "+Object.keys(L).join(", "));z=L[e]},C.getUnitSystem=function(){for(var e in L)if(hasOwnProperty$2(L,e)&&L[e]===z)return e},C.typeConverters={BigNumber:function(e){return new v(e+"")},Fraction:function(e){return new N(e)},Complex:function(e){return e},number:function(e){return e}},C._getNumberConverter=function(e){if(!C.typeConverters[e])throw new TypeError('Unsupported type "'+e+'"');return C.typeConverters[e]},k)if(hasOwnProperty$2(k,U)){var j=k[U];j.dimensions=j.base.dimensions}for(var q in $)if(hasOwnProperty$2($,q)){var G=k[$[q]],H={};for(var W in G)hasOwnProperty$2(G,W)&&(H[W]=G[W]);H.name=q,k[q]=H}return C.isValidAlpha=function(e){return/^[a-zA-Z]$/.test(e)},C.createUnit=function(e,t){if("object"!=typeof e)throw new TypeError("createUnit expects first parameter to be of type 'Object'");if(t&&t.override)for(var n in e)if(hasOwnProperty$2(e,n)&&C.deleteUnit(n),e[n].aliases)for(var r=0;r0&&!C.isValidAlpha(r)&&!V(r))throw new Error('Invalid unit name (only alphanumeric characters are allowed): "'+e+'"')}}(e);var a,i,s,o=null,l=[],u=0;if(t&&"Unit"===t.type)o=t.clone();else if("string"==typeof t)""!==t&&(a=t);else{if("object"!=typeof t)throw new TypeError('Cannot create unit "'+e+'" from "'+t.toString()+'": expecting "string" or "Unit" or "Object"');a=t.definition,i=t.prefixes,u=t.offset,s=t.baseName,t.aliases&&(l=t.aliases.valueOf())}if(l)for(var c=0;c1e-12){h=!1;break}if(h){d=!0,p.base=M[m];break}}if(!d){s=s||e+"_STUFF";var y={dimensions:o.dimensions.slice(0)};y.key=s,M[s]=y,z[s]={unit:p,prefix:R.NONE[""]},p.base=M[s]}}else{if(s=s||e+"_STUFF",_.indexOf(s)>=0)throw new Error('Cannot create new base unit "'+e+'": a base unit with that name already exists (and cannot be overridden)');for(var g in _.push(s),M)hasOwnProperty$2(M,g)&&(M[g].dimensions[_.length-1]=0);for(var b={dimensions:[]},v=0;v<_.length;v++)b.dimensions[v]=0;b.dimensions[_.length-1]=1,b.key=s,M[s]=b,p={name:e,value:1,dimensions:M[s].dimensions.slice(0),prefixes:i,offset:u,base:M[s]},z[s]={unit:p,prefix:R.NONE[""]}}C.UNITS[e]=p;for(var N=0;N{var{typed:t,Unit:n}=e;return t(name$2a,{Unit:function(e){return e.clone()},string:function(e){return n.isValuelessUnit(e)?new n(null,e):n.parse(e,{allowNoUnits:!0})},"number | BigNumber | Fraction | Complex, string":function(e,t){return new n(e,t)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$29="sparse",dependencies$29=["typed","SparseMatrix"],createSparse=factory(name$29,dependencies$29,(e=>{var{typed:t,SparseMatrix:n}=e;return t(name$29,{"":function(){return new n([])},string:function(e){return new n([],e)},"Array | Matrix":function(e){return new n(e)},"Array | Matrix, string":function(e,t){return new n(e,t)}})})),name$28="createUnit",dependencies$28=["typed","Unit"],createCreateUnit=factory(name$28,dependencies$28,(e=>{var{typed:t,Unit:n}=e;return t(name$28,{"Object, Object":function(e,t){return n.createUnit(e,t)},Object:function(e){return n.createUnit(e,{})},"string, Unit | string | Object, Object":function(e,t,r){var a={};return a[e]=t,n.createUnit(a,r)},"string, Unit | string | Object":function(e,t){var r={};return r[e]=t,n.createUnit(r,{})},string:function(e){var t={};return t[e]={},n.createUnit(t,{})}})})),name$27="acos",dependencies$27=["typed","config","Complex"],createAcos=factory(name$27,dependencies$27,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$27,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.acos(e):new r(e,0).acos()},Complex:function(e){return e.acos()},BigNumber:function(e){return e.acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$26="acosh",dependencies$26=["typed","config","Complex"],createAcosh=factory(name$26,dependencies$26,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$26,{number:function(e){return e>=1||n.predictable?acoshNumber(e):e<=-1?new r(Math.log(Math.sqrt(e*e-1)-e),Math.PI):new r(e,0).acosh()},Complex:function(e){return e.acosh()},BigNumber:function(e){return e.acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$25="acot",dependencies$25=["typed","BigNumber"],createAcot=factory(name$25,dependencies$25,(e=>{var{typed:t,BigNumber:n}=e;return t(name$25,{number:acotNumber,Complex:function(e){return e.acot()},BigNumber:function(e){return new n(1).div(e).atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$24="acoth",dependencies$24=["typed","config","Complex","BigNumber"],createAcoth=factory(name$24,dependencies$24,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$24,{number:function(e){return e>=1||e<=-1||n.predictable?acothNumber(e):new r(e,0).acoth()},Complex:function(e){return e.acoth()},BigNumber:function(e){return new a(1).div(e).atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$23="acsc",dependencies$23=["typed","config","Complex","BigNumber"],createAcsc=factory(name$23,dependencies$23,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$23,{number:function(e){return e<=-1||e>=1||n.predictable?acscNumber(e):new r(e,0).acsc()},Complex:function(e){return e.acsc()},BigNumber:function(e){return new a(1).div(e).asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$22="acsch",dependencies$22=["typed","BigNumber"],createAcsch=factory(name$22,dependencies$22,(e=>{var{typed:t,BigNumber:n}=e;return t(name$22,{number:acschNumber,Complex:function(e){return e.acsch()},BigNumber:function(e){return new n(1).div(e).asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$21="asec",dependencies$21=["typed","config","Complex","BigNumber"],createAsec=factory(name$21,dependencies$21,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$21,{number:function(e){return e<=-1||e>=1||n.predictable?asecNumber(e):new r(e,0).asec()},Complex:function(e){return e.asec()},BigNumber:function(e){return new a(1).div(e).acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$20="asech",dependencies$20=["typed","config","Complex","BigNumber"],createAsech=factory(name$20,dependencies$20,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$20,{number:function(e){if(e<=1&&e>=-1||n.predictable){var t=1/e;if(t>0||n.predictable)return asechNumber(e);var a=Math.sqrt(t*t-1);return new r(Math.log(a-t),Math.PI)}return new r(e,0).asech()},Complex:function(e){return e.asech()},BigNumber:function(e){return new a(1).div(e).acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1$="asin",dependencies$1$=["typed","config","Complex"],createAsin=factory(name$1$,dependencies$1$,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1$,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.asin(e):new r(e,0).asin()},Complex:function(e){return e.asin()},BigNumber:function(e){return e.asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1_="asinh",dependencies$1_=["typed"],createAsinh=factory(name$1_,dependencies$1_,(e=>{var{typed:t}=e;return t("asinh",{number:asinhNumber,Complex:function(e){return e.asinh()},BigNumber:function(e){return e.asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Z="atan",dependencies$1Z=["typed"],createAtan=factory(name$1Z,dependencies$1Z,(e=>{var{typed:t}=e;return t("atan",{number:function(e){return Math.atan(e)},Complex:function(e){return e.atan()},BigNumber:function(e){return e.atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Y="atan2",dependencies$1Y=["typed","matrix","equalScalar","BigNumber","DenseMatrix"],createAtan2=factory(name$1Y,dependencies$1Y,(e=>{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm03({typed:t}),l=createAlgorithm09({typed:t,equalScalar:r}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$1Y,{"number, number":Math.atan2,"BigNumber, BigNumber":function(e,t){return a.atan2(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return c(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return d(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})})),name$1X="atanh",dependencies$1X=["typed","config","Complex"],createAtanh=factory(name$1X,dependencies$1X,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1X,{number:function(e){return e<=1&&e>=-1||n.predictable?atanhNumber(e):new r(e,0).atanh()},Complex:function(e){return e.atanh()},BigNumber:function(e){return e.atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1W="cos",dependencies$1W=["typed"],createCos=factory(name$1W,dependencies$1W,(e=>{var{typed:t}=e;return t(name$1W,{number:Math.cos,Complex:function(e){return e.cos()},BigNumber:function(e){return e.cos()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cos is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1V="cosh",dependencies$1V=["typed"],createCosh=factory(name$1V,dependencies$1V,(e=>{var{typed:t}=e;return t(name$1V,{number:cosh$3,Complex:function(e){return e.cosh()},BigNumber:function(e){return e.cosh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cosh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1U="cot",dependencies$1U=["typed","BigNumber"],createCot=factory(name$1U,dependencies$1U,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1U,{number:cotNumber,Complex:function(e){return e.cot()},BigNumber:function(e){return new n(1).div(e.tan())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cot is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1T="coth",dependencies$1T=["typed","BigNumber"],createCoth=factory(name$1T,dependencies$1T,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1T,{number:cothNumber,Complex:function(e){return e.coth()},BigNumber:function(e){return new n(1).div(e.tanh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function coth is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1S="csc",dependencies$1S=["typed","BigNumber"],createCsc=factory(name$1S,dependencies$1S,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1S,{number:cscNumber,Complex:function(e){return e.csc()},BigNumber:function(e){return new n(1).div(e.sin())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csc is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1R="csch",dependencies$1R=["typed","BigNumber"],createCsch=factory(name$1R,dependencies$1R,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1R,{number:cschNumber,Complex:function(e){return e.csch()},BigNumber:function(e){return new n(1).div(e.sinh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csch is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Q="sec",dependencies$1Q=["typed","BigNumber"],createSec=factory(name$1Q,dependencies$1Q,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1Q,{number:secNumber,Complex:function(e){return e.sec()},BigNumber:function(e){return new n(1).div(e.cos())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sec is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1P="sech",dependencies$1P=["typed","BigNumber"],createSech=factory(name$1P,dependencies$1P,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1P,{number:sechNumber,Complex:function(e){return e.sech()},BigNumber:function(e){return new n(1).div(e.cosh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sech is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1O="sin",dependencies$1O=["typed"],createSin=factory(name$1O,dependencies$1O,(e=>{var{typed:t}=e;return t(name$1O,{number:Math.sin,Complex:function(e){return e.sin()},BigNumber:function(e){return e.sin()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sin is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1N="sinh",dependencies$1N=["typed"],createSinh=factory(name$1N,dependencies$1N,(e=>{var{typed:t}=e;return t(name$1N,{number:sinhNumber,Complex:function(e){return e.sinh()},BigNumber:function(e){return e.sinh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sinh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1M="tan",dependencies$1M=["typed"],createTan=factory(name$1M,dependencies$1M,(e=>{var{typed:t}=e;return t(name$1M,{number:Math.tan,Complex:function(e){return e.tan()},BigNumber:function(e){return e.tan()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tan is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1L="tanh",dependencies$1L=["typed"],createTanh=factory(name$1L,dependencies$1L,(e=>{var{typed:t}=e;return t("tanh",{number:tanh$3,Complex:function(e){return e.tanh()},BigNumber:function(e){return e.tanh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tanh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1K="setCartesian",dependencies$1K=["typed","size","subset","compareNatural","Index","DenseMatrix"],createSetCartesian=factory(name$1K,dependencies$1K,(e=>{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1K,{"Array | Matrix, Array | Matrix":function(e,t){var o=[];if(0!==r(n(e),new i(0))&&0!==r(n(t),new i(0))){var l=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),u=flatten$4(Array.isArray(t)?t:t.toArray()).sort(a);o=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1J,{"Array | Matrix, Array | Matrix":function(e,t){var o;if(0===r(n(e),new i(0)))o=[];else{if(0===r(n(t),new i(0)))return flatten$4(e.toArray());var l,u=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),c=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));o=[];for(var p=0;p{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1I,{"Array | Matrix":function(e){var t;if(0===r(n(e),new i(0)))t=[];else{var o=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a);(t=[]).push(o[0]);for(var l=1;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1H,{"Array | Matrix, Array | Matrix":function(e,t){var o;if(0===r(n(e),new i(0))||0===r(n(t),new i(0)))o=[];else{var l=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),u=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));o=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1G,{"Array | Matrix, Array | Matrix":function(e,t){if(0===r(n(e),new i(0)))return!0;if(0===r(n(t),new i(0)))return!1;for(var s,o=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),l=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a)),u=0;u{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1F,{"number | BigNumber | Fraction | Complex, Array | Matrix":function(e,t){if(0===r(n(t),new i(0)))return 0;for(var s=flatten$4(Array.isArray(t)?t:t.toArray()),o=0,l=0;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1E,{"Array | Matrix":function(e){if(0===r(n(e),new i(0)))return[];for(var t=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),o=[],l=0;l.toString(2).length<=t.length;)o.push(s(t,l.toString(2).split("").reverse())),l++;return function(e){for(var t=[],n=e.length-1;n>0;n--)for(var r=0;re[r+1].length&&(t=e[r],e[r]=e[r+1],e[r+1]=t);return e}(o)}});function s(e,t){for(var n=[],r=0;r{var{typed:t,compareNatural:n}=e;return t(name$1D,{"Array | Matrix":function(e){return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length},"Array | Matrix, boolean":function(e,t){if(!1===t||0===e.length)return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length;for(var r=flatten$4(Array.isArray(e)?e:e.toArray()).sort(n),a=1,i=1;i{var{typed:t,size:n,concat:r,subset:a,setDifference:i,Index:s}=e;return t(name$1C,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new s(0)))return flatten$4(t);if(0===a(n(t),new s(0)))return flatten$4(e);var o=flatten$4(e),l=flatten$4(t);return r(i(o,l),i(l,o))}})})),name$1B="setUnion",dependencies$1B=["typed","size","concat","subset","setIntersect","setSymDifference","Index"],createSetUnion=factory(name$1B,dependencies$1B,(e=>{var{typed:t,size:n,concat:r,subset:a,setIntersect:i,setSymDifference:s,Index:o}=e;return t(name$1B,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new o(0)))return flatten$4(t);if(0===a(n(t),new o(0)))return flatten$4(e);var l=flatten$4(e),u=flatten$4(t);return r(s(l,u),i(l,u))}})})),name$1A="add",dependencies$1A=["typed","matrix","addScalar","equalScalar","DenseMatrix","SparseMatrix"],createAdd=factory(name$1A,dependencies$1A,(e=>{var{typed:t,matrix:n,addScalar:r,equalScalar:a,DenseMatrix:i,SparseMatrix:s}=e,o=createAlgorithm01({typed:t}),l=createAlgorithm04({typed:t,equalScalar:a}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$1A,extend$2({"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,r)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,r,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,r,!0)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return p(e,t,r,!1)},"SparseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, DenseMatrix":function(e,t){return p(t,e,r,!0)},"any, SparseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return p(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,r,!0).valueOf()},"any, any":r,"any, any, ...any":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,abs:n,addScalar:r,divideScalar:a,multiplyScalar:i,sqrt:s,smaller:o,isPositive:l}=e;return t(name$1z,{"... number | BigNumber":function(e){for(var t=0,u=0,c=0;c{var{typed:t,abs:n,add:r,pow:a,conj:i,sqrt:s,multiply:o,equalScalar:l,larger:u,smaller:c,matrix:p,ctranspose:d,eigs:m}=e;return t(name$1y,{number:Math.abs,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},boolean:function(e){return Math.abs(e)},Array:function(e){return y(p(e),2)},Matrix:function(e){return y(e,2)},"number | Complex | BigNumber | boolean, number | BigNumber | string":function(e){return this(e)},"Array, number | BigNumber | string":function(e,t){return y(p(e),t)},"Matrix, number | BigNumber | string":function(e,t){return y(e,t)}});function h(e,t){if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=0;return e.forEach((function(e){var r=n(e);u(r,t)&&(t=r)}),!0),t}(e);if(t===Number.NEGATIVE_INFINITY||"-inf"===t)return function(e){var t;return e.forEach((function(e){var r=n(e);t&&!c(r,t)||(t=r)}),!0),t||0}(e);if("fro"===t)return y(e,2);if("number"==typeof t&&!isNaN(t)){if(!l(t,0)){var i=0;return e.forEach((function(e){i=r(a(n(e),t),i)}),!0),a(i,1/t)}return Number.POSITIVE_INFINITY}throw new Error("Unsupported parameter value")}function f(e,t){if(1===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var s=i[1],o=r(t[s]||0,n(e));u(o,a)&&(a=o),t[s]=o}),!0),a}(e);if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var s=i[0],o=r(t[s]||0,n(e));u(o,a)&&(a=o),t[s]=o}),!0),a}(e);if("fro"===t)return function(e){var t=0;return e.forEach((function(e,n){t=r(t,o(e,i(e)))})),n(s(t))}(e);if(2===t)return function(e){var t=e.size();if(t[0]!==t[1])throw new RangeError("Invalid matrix dimensions");var r=d(e),a=o(r,e),i=m(a).values.toArray(),l=i[i.length-1];return n(s(l))}(e);throw new Error("Unsupported parameter value "+t)}function y(e,t){var n=e.size();if(1===n.length)return h(e,t);if(2===n.length){if(n[0]&&n[1])return f(e,t);throw new RangeError("Invalid matrix dimensions")}}})),name$1x="dot",dependencies$1x=["typed","addScalar","multiplyScalar","conj","size"],createDot=factory(name$1x,dependencies$1x,(e=>{var{typed:t,addScalar:n,multiplyScalar:r,conj:a,size:i}=e;return t(name$1x,{"Array | DenseMatrix, Array | DenseMatrix":function(e,i){var l=s(e,i),u=isMatrix(e)?e._data:e,c=isMatrix(e)?e._datatype:void 0,p=isMatrix(i)?i._data:i,d=isMatrix(i)?i._datatype:void 0,m=2===o(e).length,h=2===o(i).length,f=n,y=r;if(c&&d&&c===d&&"string"==typeof c){var g=c;f=t.find(n,[g,g]),y=t.find(r,[g,g])}if(!m&&!h){for(var b=y(a(u[0]),p[0]),v=1;vf?m++:h===f&&(u=c(u,p(i[d],l[m])),d++,m++)}return u}});function s(e,t){var n,r,a=o(e),i=o(t);if(1===a.length)n=a[0];else{if(2!==a.length||1!==a[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+a.join(", ")+")");n=a[0]}if(1===i.length)r=i[0];else{if(2!==i.length||1!==i[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+i.join(", ")+")");r=i[0]}if(n!==r)throw new RangeError("Vectors must have equal length ("+n+" != "+r+")");if(0===n)throw new RangeError("Cannot calculate the dot product of empty vectors");return n}function o(e){return isMatrix(e)?e.size():i(e)}})),name$1w="trace",dependencies$1w=["typed","matrix","add"],createTrace=factory(name$1w,dependencies$1w,(e=>{var{typed:t,matrix:n,add:r}=e;return t("trace",{Array:function(e){return a(n(e))},SparseMatrix:function(e){var t=e._values,n=e._index,a=e._ptr,i=e._size,s=i[0],o=i[1];if(s===o){var l=0;if(t.length>0)for(var u=0;uu)break}return l}throw new RangeError("Matrix must be square (size: "+format$1(i)+")")},DenseMatrix:a,any:clone$3});function a(e){var t=e._size,n=e._data;switch(t.length){case 1:if(1===t[0])return clone$3(n[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0];if(a===t[1]){for(var i=0,s=0;s{var{typed:t,Index:n}=e;return t(name$1v,{"...number | string | BigNumber | Range | Array | Matrix":function(e){var t=e.map((function(e){return isBigNumber(e)?e.toNumber():Array.isArray(e)||isMatrix(e)?e.map((function(e){return isBigNumber(e)?e.toNumber():e})):e})),r=new n;return n.apply(r,t),r}})})),keywords=new Set(["end"]),name$1u="Node",dependencies$1u=["mathWithTransform"],createNode=factory(name$1u,dependencies$1u,(e=>{var{mathWithTransform:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator")}return n.prototype.evaluate=function(e){return this.compile().evaluate(e)},n.prototype.type="Node",n.prototype.isNode=!0,n.prototype.comment="",n.prototype.compile=function(){var e=this._compile(t,{}),n={};return{evaluate:function(t){var r=createMap$1(t);return function(e){for(var t of[...keywords])if(e.has(t))throw new Error('Scope contains an illegal symbol, "'+t+'" is a reserved keyword')}(r),e(r,n,null)}}},n.prototype._compile=function(e,t){throw new Error("Method _compile should be implemented by type "+this.type)},n.prototype.forEach=function(e){throw new Error("Cannot run forEach on a Node interface")},n.prototype.map=function(e){throw new Error("Cannot run map on a Node interface")},n.prototype._ifNode=function(e){if(!isNode(e))throw new TypeError("Callback function must return a Node");return e},n.prototype.traverse=function(e){e(this,null,null),function e(t,n){t.forEach((function(t,r,a){n(t,r,a),e(t,n)}))}(this,e)},n.prototype.transform=function(e){return function t(n,r,a){var i=e(n,r,a);return i!==n?i:n.map(t)}(this,null,null)},n.prototype.filter=function(e){var t=[];return this.traverse((function(n,r,a){e(n,r,a)&&t.push(n)})),t},n.prototype.clone=function(){throw new Error("Cannot clone a Node interface")},n.prototype.cloneDeep=function(){return this.map((function(e){return e.cloneDeep()}))},n.prototype.equals=function(e){return!!e&&deepStrictEqual(this,e)},n.prototype.toString=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toString(e)},n.prototype.toJSON=function(){throw new Error("Cannot serialize object: toJSON not implemented by "+this.type)},n.prototype.toHTML=function(e){var t=this._getCustomString(e);return void 0!==t?t:this.toHTML(e)},n.prototype._toString=function(){throw new Error("_toString not implemented for "+this.type)},n.prototype.toTex=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toTex(e)},n.prototype._toTex=function(e){throw new Error("_toTex not implemented for "+this.type)},n.prototype._getCustomString=function(e){if(e&&"object"==typeof e)switch(typeof e.handler){case"object":case"undefined":return;case"function":return e.handler(this,e);default:throw new TypeError("Object or function expected as callback")}},n.prototype.getIdentifier=function(){return this.type},n.prototype.getContent=function(){return this},n}),{isClass:!0,isNode:!0});function errorTransform(e){return e&&e.isIndexError?new IndexError(e.index+1,e.min+1,void 0!==e.max?e.max+1:void 0):e}function accessFactory(e){var{subset:t}=e;return function(e,n){try{if(Array.isArray(e))return t(e,n);if(e&&"function"==typeof e.subset)return e.subset(n);if("string"==typeof e)return t(e,n);if("object"==typeof e){if(!n.isObjectProperty())throw new TypeError("Cannot apply a numeric index as object property");return getSafeProperty(e,n.getObjectProperty())}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var name$1t="AccessorNode",dependencies$1t=["subset","Node"],createAccessorNode=factory(name$1t,dependencies$1t,(e=>{var{subset:t,Node:n}=e,r=accessFactory({subset:t});function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "object"');if(!isIndexNode(t))throw new TypeError('IndexNode expected for parameter "index"');this.object=e||null,this.index=t,Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function i(e){return!(isAccessorNode(e)||isArrayNode(e)||isConstantNode(e)||isFunctionNode(e)||isObjectNode(e)||isParenthesisNode(e)||isSymbolNode(e))}return a.prototype=new n,a.prototype.type="AccessorNode",a.prototype.isAccessorNode=!0,a.prototype._compile=function(e,t){var n=this.object._compile(e,t),a=this.index._compile(e,t);if(this.index.isObjectProperty()){var i=this.index.getObjectProperty();return function(e,t,r){return getSafeProperty(n(e,t,r),i)}}return function(e,t,i){var s=n(e,t,i),o=a(e,t,s);return r(s,o)}},a.prototype.forEach=function(e){e(this.object,"object",this),e(this.index,"index",this)},a.prototype.map=function(e){return new a(this._ifNode(e(this.object,"object",this)),this._ifNode(e(this.index,"index",this)))},a.prototype.clone=function(){return new a(this.object,this.index)},a.prototype._toString=function(e){var t=this.object.toString(e);return i(this.object)&&(t="("+t+")"),t+this.index.toString(e)},a.prototype.toHTML=function(e){var t=this.object.toHTML(e);return i(this.object)&&(t='('+t+')'),t+this.index.toHTML(e)},a.prototype._toTex=function(e){var t=this.object.toTex(e);return i(this.object)&&(t="\\left(' + object + '\\right)"),t+this.index.toTex(e)},a.prototype.toJSON=function(){return{mathjs:"AccessorNode",object:this.object,index:this.index}},a.fromJSON=function(e){return new a(e.object,e.index)},a}),{isClass:!0,isNode:!0}),name$1s="ArrayNode",dependencies$1s=["Node"],createArrayNode=factory(name$1s,dependencies$1s,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.items=e||[],!Array.isArray(this.items)||!this.items.every(isNode))throw new TypeError("Array containing Nodes expected")}return n.prototype=new t,n.prototype.type="ArrayNode",n.prototype.isArrayNode=!0,n.prototype._compile=function(e,t){var n=map$2(this.items,(function(n){return n._compile(e,t)}));if("Array"!==e.config.matrix){var r=e.matrix;return function(e,t,a){return r(map$2(n,(function(n){return n(e,t,a)})))}}return function(e,t,r){return map$2(n,(function(n){return n(e,t,r)}))}},n.prototype.forEach=function(e){for(var t=0;t['+this.items.map((function(t){return t.toHTML(e)})).join(',')+']'},n.prototype._toTex=function(e){return function t(n,r){var a=n.some(isArrayNode)&&!n.every(isArrayNode),i=r||a,s=i?"&":"\\\\",o=n.map((function(n){return n.items?t(n.items,!r):n.toTex(e)})).join(s);return a||!i||i&&!r?"\\begin{bmatrix}"+o+"\\end{bmatrix}":o}(this.items,!1)},n}),{isClass:!0,isNode:!0});function assignFactory(e){var{subset:t,matrix:n}=e;return function(e,r,a){try{if(Array.isArray(e))return n(e).subset(r,a).valueOf();if(e&&"function"==typeof e.subset)return e.subset(r,a);if("string"==typeof e)return t(e,r,a);if("object"==typeof e){if(!r.isObjectProperty())throw TypeError("Cannot apply a numeric index as object property");return setSafeProperty(e,r.getObjectProperty(),a),e}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var properties=[{AssignmentNode:{},FunctionAssignmentNode:{}},{ConditionalNode:{latexLeftParens:!1,latexRightParens:!1,latexParens:!1}},{"OperatorNode:or":{associativity:"left",associativeWith:[]}},{"OperatorNode:xor":{associativity:"left",associativeWith:[]}},{"OperatorNode:and":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitOr":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitXor":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitAnd":{associativity:"left",associativeWith:[]}},{"OperatorNode:equal":{associativity:"left",associativeWith:[]},"OperatorNode:unequal":{associativity:"left",associativeWith:[]},"OperatorNode:smaller":{associativity:"left",associativeWith:[]},"OperatorNode:larger":{associativity:"left",associativeWith:[]},"OperatorNode:smallerEq":{associativity:"left",associativeWith:[]},"OperatorNode:largerEq":{associativity:"left",associativeWith:[]},RelationalNode:{associativity:"left",associativeWith:[]}},{"OperatorNode:leftShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightArithShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightLogShift":{associativity:"left",associativeWith:[]}},{"OperatorNode:to":{associativity:"left",associativeWith:[]}},{RangeNode:{}},{"OperatorNode:add":{associativity:"left",associativeWith:["OperatorNode:add","OperatorNode:subtract"]},"OperatorNode:subtract":{associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]},"OperatorNode:divide":{associativity:"left",associativeWith:[],latexLeftParens:!1,latexRightParens:!1,latexParens:!1},"OperatorNode:dotMultiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","OperatorNode:dotMultiply","OperatorNode:doDivide"]},"OperatorNode:dotDivide":{associativity:"left",associativeWith:[]},"OperatorNode:mod":{associativity:"left",associativeWith:[]}},{"OperatorNode:unaryPlus":{associativity:"right"},"OperatorNode:unaryMinus":{associativity:"right"},"OperatorNode:bitNot":{associativity:"right"},"OperatorNode:not":{associativity:"right"}},{"OperatorNode:pow":{associativity:"right",associativeWith:[],latexRightParens:!1},"OperatorNode:dotPow":{associativity:"right",associativeWith:[]}},{"OperatorNode:factorial":{associativity:"left"}},{"OperatorNode:transpose":{associativity:"left"}}];function getPrecedence(e,t){var n=e;"keep"!==t&&(n=e.getContent());for(var r=n.getIdentifier(),a=0;a{var{subset:t,matrix:n,Node:r}=e,a=accessFactory({subset:t}),i=assignFactory({subset:t,matrix:n});function s(e,t,n){if(!(this instanceof s))throw new SyntaxError("Constructor must be called with the new operator");if(this.object=e,this.index=n?t:null,this.value=n||t,!isSymbolNode(e)&&!isAccessorNode(e))throw new TypeError('SymbolNode or AccessorNode expected as "object"');if(isSymbolNode(e)&&"end"===e.name)throw new Error('Cannot assign to symbol "end"');if(this.index&&!isIndexNode(this.index))throw new TypeError('IndexNode expected as "index"');if(!isNode(this.value))throw new TypeError('Node expected as "value"');Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function o(e,t){t||(t="keep");var n=getPrecedence(e,t),r=getPrecedence(e.value,t);return"all"===t||null!==r&&r<=n}return s.prototype=new r,s.prototype.type="AssignmentNode",s.prototype.isAssignmentNode=!0,s.prototype._compile=function(e,t){var n=this.object._compile(e,t),r=this.index?this.index._compile(e,t):null,s=this.value._compile(e,t),o=this.object.name;if(this.index){if(this.index.isObjectProperty()){var l=this.index.getObjectProperty();return function(e,t,r){var a=n(e,t,r),i=s(e,t,r);return setSafeProperty(a,l,i),i}}if(isSymbolNode(this.object))return function(e,t,a){var l=n(e,t,a),u=s(e,t,a),c=r(e,t,l);return e.set(o,i(l,c,u)),u};var u=this.object.object._compile(e,t);if(this.object.index.isObjectProperty()){var c=this.object.index.getObjectProperty();return function(e,t,n){var a=u(e,t,n),o=getSafeProperty(a,c),l=r(e,t,o),p=s(e,t,n);return setSafeProperty(a,c,i(o,l,p)),p}}var p=this.object.index._compile(e,t);return function(e,t,n){var o=u(e,t,n),l=p(e,t,o),c=a(o,l),d=r(e,t,c),m=s(e,t,n);return i(o,l,i(c,d,m)),m}}if(!isSymbolNode(this.object))throw new TypeError("SymbolNode expected as object");return function(e,t,n){var r=s(e,t,n);return e.set(o,r),r}},s.prototype.forEach=function(e){e(this.object,"object",this),this.index&&e(this.index,"index",this),e(this.value,"value",this)},s.prototype.map=function(e){return new s(this._ifNode(e(this.object,"object",this)),this.index?this._ifNode(e(this.index,"index",this)):null,this._ifNode(e(this.value,"value",this)))},s.prototype.clone=function(){return new s(this.object,this.index,this.value)},s.prototype._toString=function(e){var t=this.object.toString(e),n=this.index?this.index.toString(e):"",r=this.value.toString(e);return o(this,e&&e.parenthesis)&&(r="("+r+")"),t+n+" = "+r},s.prototype.toJSON=function(){return{mathjs:"AssignmentNode",object:this.object,index:this.index,value:this.value}},s.fromJSON=function(e){return new s(e.object,e.index,e.value)},s.prototype.toHTML=function(e){var t=this.object.toHTML(e),n=this.index?this.index.toHTML(e):"",r=this.value.toHTML(e);return o(this,e&&e.parenthesis)&&(r='('+r+')'),t+n+'='+r},s.prototype._toTex=function(e){var t=this.object.toTex(e),n=this.index?this.index.toTex(e):"",r=this.value.toTex(e);return o(this,e&&e.parenthesis)&&(r="\\left(".concat(r,"\\right)")),t+n+":="+r},s}),{isClass:!0,isNode:!0}),name$1q="BlockNode",dependencies$1q=["ResultSet","Node"],createBlockNode=factory(name$1q,dependencies$1q,(e=>{var{ResultSet:t,Node:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new Error("Array expected");this.blocks=e.map((function(e){var t=e&&e.node,n=!e||void 0===e.visible||e.visible;if(!isNode(t))throw new TypeError('Property "node" must be a Node');if("boolean"!=typeof n)throw new TypeError('Property "visible" must be a boolean');return{node:t,visible:n}}))}return r.prototype=new n,r.prototype.type="BlockNode",r.prototype.isBlockNode=!0,r.prototype._compile=function(e,n){var r=map$2(this.blocks,(function(t){return{evaluate:t.node._compile(e,n),visible:t.visible}}));return function(e,n,a){var i=[];return forEach$1(r,(function(t){var r=t.evaluate(e,n,a);t.visible&&i.push(r)})),new t(i)}},r.prototype.forEach=function(e){for(var t=0;t;')})).join('
')},r.prototype._toTex=function(e){return this.blocks.map((function(t){return t.node.toTex(e)+(t.visible?"":";")})).join("\\;\\;\n")},r}),{isClass:!0,isNode:!0}),name$1p="ConditionalNode",dependencies$1p=["Node"],createConditionalNode=factory(name$1p,dependencies$1p,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Parameter condition must be a Node");if(!isNode(t))throw new TypeError("Parameter trueExpr must be a Node");if(!isNode(r))throw new TypeError("Parameter falseExpr must be a Node");this.condition=e,this.trueExpr=t,this.falseExpr=r}return n.prototype=new t,n.prototype.type="ConditionalNode",n.prototype.isConditionalNode=!0,n.prototype._compile=function(e,t){var n=this.condition._compile(e,t),r=this.trueExpr._compile(e,t),a=this.falseExpr._compile(e,t);return function(e,t,i){return function(e){if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return!!e;if(e){if(isBigNumber(e))return!e.isZero();if(isComplex(e))return!(!e.re&&!e.im);if(isUnit(e))return!!e.value}if(null==e)return!1;throw new TypeError('Unsupported type of condition "'+typeOf$1(e)+'"')}(n(e,t,i))?r(e,t,i):a(e,t,i)}},n.prototype.forEach=function(e){e(this.condition,"condition",this),e(this.trueExpr,"trueExpr",this),e(this.falseExpr,"falseExpr",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.condition,"condition",this)),this._ifNode(e(this.trueExpr,"trueExpr",this)),this._ifNode(e(this.falseExpr,"falseExpr",this)))},n.prototype.clone=function(){return new n(this.condition,this.trueExpr,this.falseExpr)},n.prototype._toString=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toString(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r="("+r+")");var i=this.trueExpr.toString(e),s=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==s&&s<=n)&&(i="("+i+")");var o=this.falseExpr.toString(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(o="("+o+")"),r+" ? "+i+" : "+o},n.prototype.toJSON=function(){return{mathjs:"ConditionalNode",condition:this.condition,trueExpr:this.trueExpr,falseExpr:this.falseExpr}},n.fromJSON=function(e){return new n(e.condition,e.trueExpr,e.falseExpr)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toHTML(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r='('+r+')');var i=this.trueExpr.toHTML(e),s=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==s&&s<=n)&&(i='('+i+')');var o=this.falseExpr.toHTML(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(o='('+o+')'),r+'?'+i+':'+o},n.prototype._toTex=function(e){return"\\begin{cases} {"+this.trueExpr.toTex(e)+"}, &\\quad{\\text{if }\\;"+this.condition.toTex(e)+"}\\\\{"+this.falseExpr.toTex(e)+"}, &\\quad{\\text{otherwise}}\\end{cases}"},n}),{isClass:!0,isNode:!0}),_extends=Object.assign||function(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},n=t.preserveFormatting,r=void 0!==n&&n,a=t.escapeMapFn,i=void 0===a?defaultEscapeMapFn:a,s=String(e),o="",l=i(_extends({},defaultEscapes),r?_extends({},formatEscapes):{}),u=Object.keys(l),c=function(){var e=!1;u.forEach((function(t,n){e||s.length>=t.length&&s.slice(0,t.length)===t&&(o+=l[u[n]],s=s.slice(t.length,s.length),e=!0)})),e||(o+=s.slice(0,1),s=s.slice(1,s.length))};s;)c();return o},latexSymbols={Alpha:"A",alpha:"\\alpha",Beta:"B",beta:"\\beta",Gamma:"\\Gamma",gamma:"\\gamma",Delta:"\\Delta",delta:"\\delta",Epsilon:"E",epsilon:"\\epsilon",varepsilon:"\\varepsilon",Zeta:"Z",zeta:"\\zeta",Eta:"H",eta:"\\eta",Theta:"\\Theta",theta:"\\theta",vartheta:"\\vartheta",Iota:"I",iota:"\\iota",Kappa:"K",kappa:"\\kappa",varkappa:"\\varkappa",Lambda:"\\Lambda",lambda:"\\lambda",Mu:"M",mu:"\\mu",Nu:"N",nu:"\\nu",Xi:"\\Xi",xi:"\\xi",Omicron:"O",omicron:"o",Pi:"\\Pi",pi:"\\pi",varpi:"\\varpi",Rho:"P",rho:"\\rho",varrho:"\\varrho",Sigma:"\\Sigma",sigma:"\\sigma",varsigma:"\\varsigma",Tau:"T",tau:"\\tau",Upsilon:"\\Upsilon",upsilon:"\\upsilon",Phi:"\\Phi",phi:"\\phi",varphi:"\\varphi",Chi:"X",chi:"\\chi",Psi:"\\Psi",psi:"\\psi",Omega:"\\Omega",omega:"\\omega",true:"\\mathrm{True}",false:"\\mathrm{False}",i:"i",inf:"\\infty",Inf:"\\infty",infinity:"\\infty",Infinity:"\\infty",oo:"\\infty",lim:"\\lim",undefined:"\\mathbf{?}"},latexOperators={transpose:"^\\top",ctranspose:"^H",factorial:"!",pow:"^",dotPow:".^\\wedge",unaryPlus:"+",unaryMinus:"-",bitNot:"\\~",not:"\\neg",multiply:"\\cdot",divide:"\\frac",dotMultiply:".\\cdot",dotDivide:".:",mod:"\\mod",add:"+",subtract:"-",to:"\\rightarrow",leftShift:"<<",rightArithShift:">>",rightLogShift:">>>",equal:"=",unequal:"\\neq",smaller:"<",larger:">",smallerEq:"\\leq",largerEq:"\\geq",bitAnd:"\\&",bitXor:"\\underline{|}",bitOr:"|",and:"\\wedge",xor:"\\veebar",or:"\\vee"},latexFunctions={abs:{1:"\\left|${args[0]}\\right|"},add:{2:"\\left(${args[0]}".concat(latexOperators.add,"${args[1]}\\right)")},cbrt:{1:"\\sqrt[3]{${args[0]}}"},ceil:{1:"\\left\\lceil${args[0]}\\right\\rceil"},cube:{1:"\\left(${args[0]}\\right)^3"},divide:{2:"\\frac{${args[0]}}{${args[1]}}"},dotDivide:{2:"\\left(${args[0]}".concat(latexOperators.dotDivide,"${args[1]}\\right)")},dotMultiply:{2:"\\left(${args[0]}".concat(latexOperators.dotMultiply,"${args[1]}\\right)")},dotPow:{2:"\\left(${args[0]}".concat(latexOperators.dotPow,"${args[1]}\\right)")},exp:{1:"\\exp\\left(${args[0]}\\right)"},expm1:"\\left(e".concat(latexOperators.pow,"{${args[0]}}-1\\right)"),fix:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},floor:{1:"\\left\\lfloor${args[0]}\\right\\rfloor"},gcd:"\\gcd\\left(${args}\\right)",hypot:"\\hypot\\left(${args}\\right)",log:{1:"\\ln\\left(${args[0]}\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}\\right)"},log10:{1:"\\log_{10}\\left(${args[0]}\\right)"},log1p:{1:"\\ln\\left(${args[0]}+1\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}+1\\right)"},log2:"\\log_{2}\\left(${args[0]}\\right)",mod:{2:"\\left(${args[0]}".concat(latexOperators.mod,"${args[1]}\\right)")},multiply:{2:"\\left(${args[0]}".concat(latexOperators.multiply,"${args[1]}\\right)")},norm:{1:"\\left\\|${args[0]}\\right\\|",2:void 0},nthRoot:{2:"\\sqrt[${args[1]}]{${args[0]}}"},nthRoots:{2:"\\{y : $y^{args[1]} = {${args[0]}}\\}"},pow:{2:"\\left(${args[0]}\\right)".concat(latexOperators.pow,"{${args[1]}}")},round:{1:"\\left\\lfloor${args[0]}\\right\\rceil",2:void 0},sign:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},sqrt:{1:"\\sqrt{${args[0]}}"},square:{1:"\\left(${args[0]}\\right)^2"},subtract:{2:"\\left(${args[0]}".concat(latexOperators.subtract,"${args[1]}\\right)")},unaryMinus:{1:"".concat(latexOperators.unaryMinus,"\\left(${args[0]}\\right)")},unaryPlus:{1:"".concat(latexOperators.unaryPlus,"\\left(${args[0]}\\right)")},bitAnd:{2:"\\left(${args[0]}".concat(latexOperators.bitAnd,"${args[1]}\\right)")},bitNot:{1:latexOperators.bitNot+"\\left(${args[0]}\\right)"},bitOr:{2:"\\left(${args[0]}".concat(latexOperators.bitOr,"${args[1]}\\right)")},bitXor:{2:"\\left(${args[0]}".concat(latexOperators.bitXor,"${args[1]}\\right)")},leftShift:{2:"\\left(${args[0]}".concat(latexOperators.leftShift,"${args[1]}\\right)")},rightArithShift:{2:"\\left(${args[0]}".concat(latexOperators.rightArithShift,"${args[1]}\\right)")},rightLogShift:{2:"\\left(${args[0]}".concat(latexOperators.rightLogShift,"${args[1]}\\right)")},bellNumbers:{1:"\\mathrm{B}_{${args[0]}}"},catalan:{1:"\\mathrm{C}_{${args[0]}}"},stirlingS2:{2:"\\mathrm{S}\\left(${args}\\right)"},arg:{1:"\\arg\\left(${args[0]}\\right)"},conj:{1:"\\left(${args[0]}\\right)^*"},im:{1:"\\Im\\left\\lbrace${args[0]}\\right\\rbrace"},re:{1:"\\Re\\left\\lbrace${args[0]}\\right\\rbrace"},and:{2:"\\left(${args[0]}".concat(latexOperators.and,"${args[1]}\\right)")},not:{1:latexOperators.not+"\\left(${args[0]}\\right)"},or:{2:"\\left(${args[0]}".concat(latexOperators.or,"${args[1]}\\right)")},xor:{2:"\\left(${args[0]}".concat(latexOperators.xor,"${args[1]}\\right)")},cross:{2:"\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)"},ctranspose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.ctranspose)},det:{1:"\\det\\left(${args[0]}\\right)"},dot:{2:"\\left(${args[0]}\\cdot${args[1]}\\right)"},expm:{1:"\\exp\\left(${args[0]}\\right)"},inv:{1:"\\left(${args[0]}\\right)^{-1}"},pinv:{1:"\\left(${args[0]}\\right)^{+}"},sqrtm:{1:"{${args[0]}}".concat(latexOperators.pow,"{\\frac{1}{2}}")},trace:{1:"\\mathrm{tr}\\left(${args[0]}\\right)"},transpose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.transpose)},combinations:{2:"\\binom{${args[0]}}{${args[1]}}"},combinationsWithRep:{2:"\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)"},factorial:{1:"\\left(${args[0]}\\right)".concat(latexOperators.factorial)},gamma:{1:"\\Gamma\\left(${args[0]}\\right)"},lgamma:{1:"\\ln\\Gamma\\left(${args[0]}\\right)"},equal:{2:"\\left(${args[0]}".concat(latexOperators.equal,"${args[1]}\\right)")},larger:{2:"\\left(${args[0]}".concat(latexOperators.larger,"${args[1]}\\right)")},largerEq:{2:"\\left(${args[0]}".concat(latexOperators.largerEq,"${args[1]}\\right)")},smaller:{2:"\\left(${args[0]}".concat(latexOperators.smaller,"${args[1]}\\right)")},smallerEq:{2:"\\left(${args[0]}".concat(latexOperators.smallerEq,"${args[1]}\\right)")},unequal:{2:"\\left(${args[0]}".concat(latexOperators.unequal,"${args[1]}\\right)")},erf:{1:"erf\\left(${args[0]}\\right)"},max:"\\max\\left(${args}\\right)",min:"\\min\\left(${args}\\right)",variance:"\\mathrm{Var}\\left(${args}\\right)",acos:{1:"\\cos^{-1}\\left(${args[0]}\\right)"},acosh:{1:"\\cosh^{-1}\\left(${args[0]}\\right)"},acot:{1:"\\cot^{-1}\\left(${args[0]}\\right)"},acoth:{1:"\\coth^{-1}\\left(${args[0]}\\right)"},acsc:{1:"\\csc^{-1}\\left(${args[0]}\\right)"},acsch:{1:"\\mathrm{csch}^{-1}\\left(${args[0]}\\right)"},asec:{1:"\\sec^{-1}\\left(${args[0]}\\right)"},asech:{1:"\\mathrm{sech}^{-1}\\left(${args[0]}\\right)"},asin:{1:"\\sin^{-1}\\left(${args[0]}\\right)"},asinh:{1:"\\sinh^{-1}\\left(${args[0]}\\right)"},atan:{1:"\\tan^{-1}\\left(${args[0]}\\right)"},atan2:{2:"\\mathrm{atan2}\\left(${args}\\right)"},atanh:{1:"\\tanh^{-1}\\left(${args[0]}\\right)"},cos:{1:"\\cos\\left(${args[0]}\\right)"},cosh:{1:"\\cosh\\left(${args[0]}\\right)"},cot:{1:"\\cot\\left(${args[0]}\\right)"},coth:{1:"\\coth\\left(${args[0]}\\right)"},csc:{1:"\\csc\\left(${args[0]}\\right)"},csch:{1:"\\mathrm{csch}\\left(${args[0]}\\right)"},sec:{1:"\\sec\\left(${args[0]}\\right)"},sech:{1:"\\mathrm{sech}\\left(${args[0]}\\right)"},sin:{1:"\\sin\\left(${args[0]}\\right)"},sinh:{1:"\\sinh\\left(${args[0]}\\right)"},tan:{1:"\\tan\\left(${args[0]}\\right)"},tanh:{1:"\\tanh\\left(${args[0]}\\right)"},to:{2:"\\left(${args[0]}".concat(latexOperators.to,"${args[1]}\\right)")},numeric:function(e,t){return e.args[0].toTex()},number:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"},string:{0:'\\mathtt{""}',1:"\\mathrm{string}\\left(${args[0]}\\right)"},bignumber:{0:"0",1:"\\left(${args[0]}\\right)"},complex:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i,"\\cdot\\left(${args[1]}\\right)\\right)")},matrix:{0:"\\begin{bmatrix}\\end{bmatrix}",1:"\\left(${args[0]}\\right)",2:"\\left(${args[0]}\\right)"},sparse:{0:"\\begin{bsparse}\\end{bsparse}",1:"\\left(${args[0]}\\right)"},unit:{1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"}},defaultTemplate="\\mathrm{${name}}\\left(${args}\\right)",latexUnits={deg:"^\\circ"};function escapeLatex(e){return dist(e,{preserveFormatting:!0})}function toSymbol(e,t){return(t=void 0!==t&&t)?hasOwnProperty$2(latexUnits,e)?latexUnits[e]:"\\mathrm{"+escapeLatex(e)+"}":hasOwnProperty$2(latexSymbols,e)?latexSymbols[e]:escapeLatex(e)}var name$1o="ConstantNode",dependencies$1o=["Node"],createConstantNode=factory(name$1o,dependencies$1o,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this.value=e}return n.prototype=new t,n.prototype.type="ConstantNode",n.prototype.isConstantNode=!0,n.prototype._compile=function(e,t){var n=this.value;return function(){return n}},n.prototype.forEach=function(e){},n.prototype.map=function(e){return this.clone()},n.prototype.clone=function(){return new n(this.value)},n.prototype._toString=function(e){return format$1(this.value,e)},n.prototype.toHTML=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"number":case"BigNumber":case"Fraction":return''+t+"";case"string":return''+t+"";case"boolean":return''+t+"";case"null":return''+t+"";case"undefined":return''+t+"";default:return''+t+""}},n.prototype.toJSON=function(){return{mathjs:"ConstantNode",value:this.value}},n.fromJSON=function(e){return new n(e.value)},n.prototype._toTex=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"string":return"\\mathtt{"+escapeLatex(t)+"}";case"number":case"BigNumber":if(!isFinite(this.value))return this.value.valueOf()<0?"-\\infty":"\\infty";var n=t.toLowerCase().indexOf("e");return-1!==n?t.substring(0,n)+"\\cdot10^{"+t.substring(n+1)+"}":t;case"Fraction":return this.value.toLatex();default:return t}},n}),{isClass:!0,isNode:!0}),name$1n="FunctionAssignmentNode",dependencies$1n=["typed","Node"],createFunctionAssignmentNode=factory(name$1n,dependencies$1n,(e=>{var{typed:t,Node:n}=e;function r(e,t,n){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');if(!Array.isArray(t))throw new TypeError('Array containing strings or objects expected for parameter "params"');if(!isNode(n))throw new TypeError('Node expected for parameter "expr"');if(keywords.has(e))throw new Error('Illegal function name, "'+e+'" is a reserved keyword');this.name=e,this.params=t.map((function(e){return e&&e.name||e})),this.types=t.map((function(e){return e&&e.type||"any"})),this.expr=n}function a(e,t){var n=getPrecedence(e,t),r=getPrecedence(e.expr,t);return"all"===t||null!==r&&r<=n}return r.prototype=new n,r.prototype.type="FunctionAssignmentNode",r.prototype.isFunctionAssignmentNode=!0,r.prototype._compile=function(e,n){var r=Object.create(n);forEach$1(this.params,(function(e){r[e]=!0}));var a=this.expr._compile(e,r),i=this.name,s=this.params,o=join(this.types,","),l=i+"("+join(this.params,", ")+")";return function(e,n,r){var u={};u[o]=function(){for(var t=Object.create(n),i=0;i'+escape$1(this.params[r])+"");var i=this.expr.toHTML(e);return a(this,t)&&(i='('+i+')'),''+escape$1(this.name)+'('+n.join(',')+')='+i},r.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=this.expr.toTex(e);return a(this,t)&&(n="\\left(".concat(n,"\\right)")),"\\mathrm{"+this.name+"}\\left("+this.params.map(toSymbol).join(",")+"\\right):="+n},r}),{isClass:!0,isNode:!0}),name$1m="IndexNode",dependencies$1m=["Node","size"],createIndexNode=factory(name$1m,dependencies$1m,(e=>{var{Node:t,size:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(this.dimensions=e,this.dotNotation=t||!1,!Array.isArray(e)||!e.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "dimensions"');if(this.dotNotation&&!this.isObjectProperty())throw new Error("dotNotation only applicable for object properties")}return r.prototype=new t,r.prototype.type="IndexNode",r.prototype.isIndexNode=!0,r.prototype._compile=function(e,t){var r=map$2(this.dimensions,(function(r,a){if(r.filter((e=>e.isSymbolNode&&"end"===e.name)).length>0){var i=Object.create(t);i.end=!0;var s=r._compile(e,i);return function(e,t,r){if(!isMatrix(r)&&!isArray$1(r)&&!isString$1(r))throw new TypeError('Cannot resolve "end": context must be a Matrix, Array, or string but is '+typeOf$1(r));var i=n(r).valueOf(),o=Object.create(t);return o.end=i[a],s(e,o,r)}}return r._compile(e,t)})),a=getSafeProperty(e,"index");return function(e,t,n){var i=map$2(r,(function(r){return r(e,t,n)}));return a(...i)}},r.prototype.forEach=function(e){for(var t=0;t.'+escape$1(this.getObjectProperty())+"":'['+t.join(',')+']'},r.prototype._toTex=function(e){var t=this.dimensions.map((function(t){return t.toTex(e)}));return this.dotNotation?"."+this.getObjectProperty():"_{"+t.join(",")+"}"},r}),{isClass:!0,isNode:!0}),name$1l="ObjectNode",dependencies$1l=["Node"],createObjectNode=factory(name$1l,dependencies$1l,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.properties=e||{},e&&("object"!=typeof e||!Object.keys(e).every((function(t){return isNode(e[t])}))))throw new TypeError("Object containing Nodes expected")}return n.prototype=new t,n.prototype.type="ObjectNode",n.prototype.isObjectNode=!0,n.prototype._compile=function(e,t){var n={};for(var r in this.properties)if(hasOwnProperty$2(this.properties,r)){var a=stringify(r),i=JSON.parse(a);if(!isSafeProperty(this.properties,i))throw new Error('No access to property "'+i+'"');n[i]=this.properties[r]._compile(e,t)}return function(e,t,r){var a={};for(var i in n)hasOwnProperty$2(n,i)&&(a[i]=n[i](e,t,r));return a}},n.prototype.forEach=function(e){for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&e(this.properties[t],"properties["+stringify(t)+"]",this)},n.prototype.map=function(e){var t={};for(var r in this.properties)hasOwnProperty$2(this.properties,r)&&(t[r]=this._ifNode(e(this.properties[r],"properties["+stringify(r)+"]",this)));return new n(t)},n.prototype.clone=function(){var e={};for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&(e[t]=this.properties[t]);return new n(e)},n.prototype._toString=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(stringify(n)+": "+this.properties[n].toString(e));return"{"+t.join(", ")+"}"},n.prototype.toJSON=function(){return{mathjs:"ObjectNode",properties:this.properties}},n.fromJSON=function(e){return new n(e.properties)},n.prototype.toHTML=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(''+escape$1(n)+':'+this.properties[n].toHTML(e));return'{'+t.join(',')+'}'},n.prototype._toTex=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push("\\mathbf{"+n+":} & "+this.properties[n].toTex(e)+"\\\\");return"\\left\\{\\begin{array}{ll}".concat(t.join("\n"),"\\end{array}\\right\\}")},n}),{isClass:!0,isNode:!0}),name$1k="OperatorNode",dependencies$1k=["Node"],createOperatorNode=factory(name$1k,dependencies$1k,(e=>{var{Node:t}=e;function n(e,t,r,a,i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('string expected for parameter "op"');if("string"!=typeof t)throw new TypeError('string expected for parameter "fn"');if(!Array.isArray(r)||!r.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.implicit=!0===a,this.isPercentage=!0===i,this.op=e,this.fn=t,this.args=r||[]}function r(e,t,n,r,a){var i,s=getPrecedence(e,t),o=getAssociativity(e,t);if("all"===t||r.length>2&&"OperatorNode:add"!==e.getIdentifier()&&"OperatorNode:multiply"!==e.getIdentifier())return r.map((function(e){switch(e.getContent().type){case"ArrayNode":case"ConstantNode":case"SymbolNode":case"ParenthesisNode":return!1;default:return!0}}));switch(r.length){case 0:i=[];break;case 1:var l=getPrecedence(r[0],t);if(a&&null!==l){var u,c;if("keep"===t?(u=r[0].getIdentifier(),c=e.getIdentifier()):(u=r[0].getContent().getIdentifier(),c=e.getContent().getIdentifier()),!1===properties[s][c].latexLeftParens){i=[!1];break}if(!1===properties[l][u].latexParens){i=[!1];break}}if(null===l){i=[!1];break}if(l<=s){i=[!0];break}i=[!1];break;case 2:var p,d,m=getPrecedence(r[0],t),h=isAssociativeWith(e,r[0],t);p=null!==m&&(m===s&&"right"===o&&!h||m=2&&"OperatorNode:multiply"===e.getIdentifier()&&e.implicit&&"auto"===t&&"hide"===n&&(i=r.map((function(e,t){var n="ParenthesisNode"===e.getIdentifier();return!(!i[t]&&!n)}))),i}return n.prototype=new t,n.prototype.type="OperatorNode",n.prototype.isOperatorNode=!0,n.prototype._compile=function(e,t){if("string"!=typeof this.fn||!isSafeMethod(e,this.fn))throw e[this.fn]?new Error('No access to function "'+this.fn+'"'):new Error("Function "+this.fn+' missing in provided namespace "math"');var n=getSafeProperty(e,this.fn),r=map$2(this.args,(function(n){return n._compile(e,t)}));if(1===r.length){var a=r[0];return function(e,t,r){return n(a(e,t,r))}}if(2===r.length){var i=r[0],s=r[1];return function(e,t,r){return n(i(e,t,r),s(e,t,r))}}return function(e,t,a){return n.apply(null,map$2(r,(function(n){return n(e,t,a)})))}},n.prototype.forEach=function(e){for(var t=0;t2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var p=a.map((function(t,n){return t=t.toString(e),i[n]&&(t="("+t+")"),t}));return this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?p.join(" "):p.join(" "+this.op+" ")}return this.fn+"("+this.args.join(", ")+")"},n.prototype.toJSON=function(){return{mathjs:"OperatorNode",op:this.op,fn:this.fn,args:this.args,implicit:this.implicit,isPercentage:this.isPercentage}},n.fromJSON=function(e){return new n(e.op,e.fn,e.args,e.implicit,e.isPercentage)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!1);if(1===a.length){var s=getAssociativity(this,t),o=a[0].toHTML(e);return i[0]&&(o='('+o+')'),"right"===s?''+escape$1(this.op)+""+o:o+''+escape$1(this.op)+""}if(2===a.length){var l=a[0].toHTML(e),u=a[1].toHTML(e);return i[0]&&(l='('+l+')'),i[1]&&(u='('+u+')'),this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?l+''+u:l+''+escape$1(this.op)+""+u}var c=a.map((function(t,n){return t=t.toHTML(e),i[n]&&(t='('+t+')'),t}));return a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())?this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?c.join(''):c.join(''+escape$1(this.op)+""):''+escape$1(this.fn)+'('+c.join(',')+')'},n.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!0),s=latexOperators[this.fn];if(s=void 0===s?this.op:s,1===a.length){var o=getAssociativity(this,t),l=a[0].toTex(e);return i[0]&&(l="\\left(".concat(l,"\\right)")),"right"===o?s+l:l+s}if(2===a.length){var u=a[0],c=u.toTex(e);i[0]&&(c="\\left(".concat(c,"\\right)"));var p,d=a[1].toTex(e);switch(i[1]&&(d="\\left(".concat(d,"\\right)")),p="keep"===t?u.getIdentifier():u.getContent().getIdentifier(),this.getIdentifier()){case"OperatorNode:divide":return s+"{"+c+"}{"+d+"}";case"OperatorNode:pow":switch(c="{"+c+"}",d="{"+d+"}",p){case"ConditionalNode":case"OperatorNode:divide":c="\\left(".concat(c,"\\right)")}break;case"OperatorNode:multiply":if(this.implicit&&"hide"===n)return c+"~"+d}return c+s+d}if(a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var m=a.map((function(t,n){return t=t.toTex(e),i[n]&&(t="\\left(".concat(t,"\\right)")),t}));return"OperatorNode:multiply"===this.getIdentifier()&&this.implicit?m.join("~"):m.join(s)}return"\\mathrm{"+this.fn+"}\\left("+a.map((function(t){return t.toTex(e)})).join(",")+"\\right)"},n.prototype.getIdentifier=function(){return this.type+":"+this.fn},n}),{isClass:!0,isNode:!0}),name$1j="ParenthesisNode",dependencies$1j=["Node"],createParenthesisNode=factory(name$1j,dependencies$1j,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "content"');this.content=e}return n.prototype=new t,n.prototype.type="ParenthesisNode",n.prototype.isParenthesisNode=!0,n.prototype._compile=function(e,t){return this.content._compile(e,t)},n.prototype.getContent=function(){return this.content.getContent()},n.prototype.forEach=function(e){e(this.content,"content",this)},n.prototype.map=function(e){return new n(e(this.content,"content",this))},n.prototype.clone=function(){return new n(this.content)},n.prototype._toString=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"("+this.content.toString(e)+")":this.content.toString(e)},n.prototype.toJSON=function(){return{mathjs:"ParenthesisNode",content:this.content}},n.fromJSON=function(e){return new n(e.content)},n.prototype.toHTML=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?'('+this.content.toHTML(e)+')':this.content.toHTML(e)},n.prototype._toTex=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"\\left(".concat(this.content.toTex(e),"\\right)"):this.content.toTex(e)},n}),{isClass:!0,isNode:!0}),name$1i="RangeNode",dependencies$1i=["Node"],createRangeNode=factory(name$1i,dependencies$1i,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Node expected");if(!isNode(t))throw new TypeError("Node expected");if(r&&!isNode(r))throw new TypeError("Node expected");if(arguments.length>3)throw new Error("Too many arguments");this.start=e,this.end=t,this.step=r||null}function r(e,t){var n=getPrecedence(e,t),r={},a=getPrecedence(e.start,t);if(r.start=null!==a&&a<=n||"all"===t,e.step){var i=getPrecedence(e.step,t);r.step=null!==i&&i<=n||"all"===t}var s=getPrecedence(e.end,t);return r.end=null!==s&&s<=n||"all"===t,r}return n.prototype=new t,n.prototype.type="RangeNode",n.prototype.isRangeNode=!0,n.prototype.needsEnd=function(){return this.filter((function(e){return isSymbolNode(e)&&"end"===e.name})).length>0},n.prototype._compile=function(e,t){var n=e.range,r=this.start._compile(e,t),a=this.end._compile(e,t);if(this.step){var i=this.step._compile(e,t);return function(e,t,s){return n(r(e,t,s),a(e,t,s),i(e,t,s))}}return function(e,t,i){return n(r(e,t,i),a(e,t,i))}},n.prototype.forEach=function(e){e(this.start,"start",this),e(this.end,"end",this),this.step&&e(this.step,"step",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.start,"start",this)),this._ifNode(e(this.end,"end",this)),this.step&&this._ifNode(e(this.step,"step",this)))},n.prototype.clone=function(){return new n(this.start,this.end,this.step&&this.step)},n.prototype._toString=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toString(e);if(n.start&&(a="("+a+")"),t=a,this.step){var i=this.step.toString(e);n.step&&(i="("+i+")"),t+=":"+i}var s=this.end.toString(e);return n.end&&(s="("+s+")"),t+":"+s},n.prototype.toJSON=function(){return{mathjs:"RangeNode",start:this.start,end:this.end,step:this.step}},n.fromJSON=function(e){return new n(e.start,e.end,e.step)},n.prototype.toHTML=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toHTML(e);if(n.start&&(a='('+a+')'),t=a,this.step){var i=this.step.toHTML(e);n.step&&(i='('+i+')'),t+=':'+i}var s=this.end.toHTML(e);return n.end&&(s='('+s+')'),t+':'+s},n.prototype._toTex=function(e){var t=r(this,e&&e.parenthesis?e.parenthesis:"keep"),n=this.start.toTex(e);if(t.start&&(n="\\left(".concat(n,"\\right)")),this.step){var a=this.step.toTex(e);t.step&&(a="\\left(".concat(a,"\\right)")),n+=":"+a}var i=this.end.toTex(e);return t.end&&(i="\\left(".concat(i,"\\right)")),n+":"+i},n}),{isClass:!0,isNode:!0}),name$1h="RelationalNode",dependencies$1h=["Node"],createRelationalNode=factory(name$1h,dependencies$1h,(e=>{var{Node:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new TypeError("Parameter conditionals must be an array");if(!Array.isArray(t))throw new TypeError("Parameter params must be an array");if(e.length!==t.length-1)throw new TypeError("Parameter params must contain exactly one more element than parameter conditionals");this.conditionals=e,this.params=t}return n.prototype=new t,n.prototype.type="RelationalNode",n.prototype.isRelationalNode=!0,n.prototype._compile=function(e,t){var n=this,r=this.params.map((n=>n._compile(e,t)));return function(t,a,i){for(var s,o=r[0](t,a,i),l=0;le(t,"params["+n+"]",this)),this)},n.prototype.map=function(e){return new n(this.conditionals.slice(),this.params.map(((t,n)=>this._ifNode(e(t,"params["+n+"]",this))),this))},n.prototype.clone=function(){return new n(this.conditionals,this.params)},n.prototype._toString=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"("+r.toString(e)+")":r.toString(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],s=0;s('+r.toHTML(e)+')':r.toHTML(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],s=0;s'+escape$1(a[this.conditionals[s]])+""+r[s+1];return i},n.prototype._toTex=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"\\left("+r.toTex(e)+"\right)":r.toTex(e)})),a=r[0],i=0;i{var{math:t,Unit:n,Node:r}=e;function a(e){return!!n&&n.isValuelessUnit(e)}function i(e){if(!(this instanceof i))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');this.name=e}return i.prototype=new r,i.prototype.type="SymbolNode",i.prototype.isSymbolNode=!0,i.prototype._compile=function(e,t){var r=this.name;if(!0===t[r])return function(e,t,n){return t[r]};if(r in e)return function(t,n,a){return t.has(r)?t.get(r):getSafeProperty(e,r)};var s=a(r);return function(e,t,a){return e.has(r)?e.get(r):s?new n(null,r):i.onUndefinedSymbol(r)}},i.prototype.forEach=function(e){},i.prototype.map=function(e){return this.clone()},i.onUndefinedSymbol=function(e){throw new Error("Undefined symbol "+e)},i.prototype.clone=function(){return new i(this.name)},i.prototype._toString=function(e){return this.name},i.prototype.toHTML=function(e){var t=escape$1(this.name);return"true"===t||"false"===t?''+t+"":"i"===t?''+t+"":"Infinity"===t?''+t+"":"NaN"===t?''+t+"":"null"===t?''+t+"":"undefined"===t?''+t+"":''+t+""},i.prototype.toJSON=function(){return{mathjs:"SymbolNode",name:this.name}},i.fromJSON=function(e){return new i(e.name)},i.prototype._toTex=function(e){var n=!1;void 0===t[this.name]&&a(this.name)&&(n=!0);var r=toSymbol(this.name,n);return"\\"===r[0]?r:" "+r},i}),{isClass:!0,isNode:!0});function createSubScope(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{var{math:t,Node:n,SymbolNode:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if("string"==typeof e&&(e=new r(e)),!isNode(e))throw new TypeError('Node expected as parameter "fn"');if(!Array.isArray(t)||!t.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.fn=e,this.args=t||[],Object.defineProperty(this,"name",{get:function(){return this.fn.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}a.prototype=new n,a.prototype.type="FunctionNode",a.prototype.isFunctionNode=!0;var i=e=>format$1(e,{truncate:78});a.prototype._compile=function(e,t){if(!(this instanceof a))throw new TypeError("No valid FunctionNode");var n=this.args.map((n=>n._compile(e,t)));if(!isSymbolNode(this.fn)){if(isAccessorNode(this.fn)&&isIndexNode(this.fn.index)&&this.fn.index.isObjectProperty()){var r=this.fn.object._compile(e,t),s=this.fn.index.getObjectProperty(),o=this.args;return function(t,a,i){var l=r(t,a,i);if(validateSafeMethod(l,s),l[s]&&l[s].rawArgs)return l[s](o,e,createSubScope(t,a),t);var u=n.map((e=>e(t,a,i)));return l[s].apply(l,u)}}var l=this.fn.toString(),u=this.fn._compile(e,t),c=this.args;return function(t,r,a){var s=u(t,r,a);if("function"!=typeof s)throw new TypeError("Expression '".concat(l,"' did not evaluate to a function; value is:")+"\n ".concat(i(s)));if(s.rawArgs)return s(c,e,createSubScope(t,r),t);var o=n.map((e=>e(t,r,a)));return s.apply(s,o)}}var p=this.fn.name;if(t[p]){var d=this.args;return function(t,r,a){var s=r[p];if("function"!=typeof s)throw new TypeError("Argument '".concat(p,"' was not a function; received: ").concat(i(s)));if(s.rawArgs)return s(d,e,createSubScope(t,r),t);var o=n.map((e=>e(t,r,a)));return s.apply(s,o)}}var m=p in e?getSafeProperty(e,p):void 0,h="function"==typeof m&&!0===m.rawArgs,f=t=>{var n;if(t.has(p))n=t.get(p);else{if(!(p in e))return a.onUndefinedFunction(p);n=getSafeProperty(e,p)}if("function"==typeof n)return n;throw new TypeError("'".concat(p,"' is not a function; its value is:\n ").concat(i(n)))};if(h){var y=this.args;return function(t,n,r){return f(t)(y,e,createSubScope(t,n),t)}}switch(n.length){case 0:return function(e,t,n){return f(e)()};case 1:return function(e,t,r){return f(e)((0,n[0])(e,t,r))};case 2:return function(e,t,r){var a=f(e),i=n[0],s=n[1];return a(i(e,t,r),s(e,t,r))};default:return function(e,t,r){return f(e)(...n.map((n=>n(e,t,r))))}}},a.prototype.forEach=function(e){e(this.fn,"fn",this);for(var t=0;t'+escape$1(this.fn)+'('+t.join(',')+')'};var l=a.prototype.toTex;return a.prototype.toTex=function(e){var t;return e&&"object"==typeof e.handler&&hasOwnProperty$2(e.handler,this.name)&&(t=e.handler[this.name](this,e)),void 0!==t?t:l.call(this,e)},a.prototype._toTex=function(e){var n,r,a=this.args.map((function(t){return t.toTex(e)}));switch(latexFunctions[this.name]&&(n=latexFunctions[this.name]),!t[this.name]||"function"!=typeof t[this.name].toTex&&"object"!=typeof t[this.name].toTex&&"string"!=typeof t[this.name].toTex||(n=t[this.name].toTex),typeof n){case"function":r=n(this,e);break;case"string":r=o(n,this,e);break;case"object":switch(typeof n[a.length]){case"function":r=n[a.length](this,e);break;case"string":r=o(n[a.length],this,e)}}return void 0!==r?r:o(defaultTemplate,this,e)},a.prototype.getIdentifier=function(){return this.type+":"+this.name},a}),{isClass:!0,isNode:!0}),name$1e="parse",dependencies$1e=["typed","numeric","config","AccessorNode","ArrayNode","AssignmentNode","BlockNode","ConditionalNode","ConstantNode","FunctionAssignmentNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","RangeNode","RelationalNode","SymbolNode"],createParse=factory(name$1e,dependencies$1e,(e=>{var{typed:t,numeric:n,config:r,AccessorNode:a,ArrayNode:i,AssignmentNode:s,BlockNode:o,ConditionalNode:l,ConstantNode:u,FunctionAssignmentNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:h,ParenthesisNode:f,RangeNode:y,RelationalNode:g,SymbolNode:b}=e,v=t(name$1e,{string:function(e){return B(e,{})},"Array | Matrix":function(e){return N(e,{})},"string, Object":function(e,t){return B(e,void 0!==t.nodes?t.nodes:{})},"Array | Matrix, Object":N});function N(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=void 0!==t.nodes?t.nodes:{};return deepMap(e,(function(e){if("string"!=typeof e)throw new TypeError("String expected");return B(e,n)}))}var T=0,C=1,A=2,V=3,x=4,S={",":!0,"(":!0,")":!0,"[":!0,"]":!0,"{":!0,"}":!0,'"':!0,"'":!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"~":!0,"!":!0,"&":!0,"|":!0,"^|":!0,"=":!0,":":!0,"?":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0,"<<":!0,">>":!0,">>>":!0},w={mod:!0,to:!0,in:!0,and:!0,xor:!0,or:!0,not:!0},E={true:!0,false:!1,null:null,undefined:void 0},D=["NaN","Infinity"];function O(e,t){return e.expression.substr(e.index,t)}function I(e){return O(e,1)}function R(e){e.index++}function _(e){return e.expression.charAt(e.index-1)}function M(e){return e.expression.charAt(e.index+1)}function P(e){for(e.tokenType=T,e.token="",e.comment="";;){if("#"===I(e))for(;"\n"!==I(e)&&""!==I(e);)e.comment+=I(e),R(e);if(!v.isWhitespace(I(e),e.nestingLevel))break;R(e)}if(""!==I(e)){if("\n"===I(e)&&!e.nestingLevel)return e.tokenType=C,e.token=I(e),void R(e);var t=I(e),n=O(e,2),r=O(e,3);if(3===r.length&&S[r])return e.tokenType=C,e.token=r,R(e),R(e),void R(e);if(2===n.length&&S[n])return e.tokenType=C,e.token=n,R(e),void R(e);if(S[t])return e.tokenType=C,e.token=t,void R(e);if(v.isDigitDot(t)){e.tokenType=A;var a=O(e,2);if("0b"===a||"0o"===a||"0x"===a){for(e.token+=I(e),R(e),e.token+=I(e),R(e);v.isHexDigit(I(e));)e.token+=I(e),R(e);if("."===I(e))for(e.token+=".",R(e);v.isHexDigit(I(e));)e.token+=I(e),R(e);else if("i"===I(e))for(e.token+="i",R(e);v.isDigit(I(e));)e.token+=I(e),R(e);return}if("."===I(e)){if(e.token+=I(e),R(e),!v.isDigit(I(e)))return void(e.tokenType=C)}else{for(;v.isDigit(I(e));)e.token+=I(e),R(e);v.isDecimalMark(I(e),M(e))&&(e.token+=I(e),R(e))}for(;v.isDigit(I(e));)e.token+=I(e),R(e);if("E"===I(e)||"e"===I(e))if(v.isDigit(M(e))||"-"===M(e)||"+"===M(e)){if(e.token+=I(e),R(e),"+"!==I(e)&&"-"!==I(e)||(e.token+=I(e),R(e)),!v.isDigit(I(e)))throw oe(e,'Digit expected, got "'+I(e)+'"');for(;v.isDigit(I(e));)e.token+=I(e),R(e);if(v.isDecimalMark(I(e),M(e)))throw oe(e,'Digit expected, got "'+I(e)+'"')}else if("."===M(e))throw R(e),oe(e,'Digit expected, got "'+I(e)+'"')}else{if(!v.isAlpha(I(e),_(e),M(e))){for(e.tokenType=x;""!==I(e);)e.token+=I(e),R(e);throw oe(e,'Syntax error in part "'+e.token+'"')}for(;v.isAlpha(I(e),_(e),M(e))||v.isDigit(I(e));)e.token+=I(e),R(e);hasOwnProperty$2(w,e.token)?e.tokenType=C:e.tokenType=V}}else e.tokenType=C}function F(e){do{P(e)}while("\n"===e.token)}function k(e){e.nestingLevel++}function $(e){e.nestingLevel--}function B(e,t){var n={extraNodes:{},expression:"",comment:"",index:0,token:"",tokenType:T,nestingLevel:0,conditionalLevel:null};_extends$1(n,{expression:e,extraNodes:t}),P(n);var r=function(e){var t,n,r=[];for(""!==e.token&&"\n"!==e.token&&";"!==e.token&&((t=L(e)).comment=e.comment);"\n"===e.token||";"===e.token;)0===r.length&&t&&(n=";"!==e.token,r.push({node:t,visible:n})),P(e),"\n"!==e.token&&";"!==e.token&&""!==e.token&&((t=L(e)).comment=e.comment,n=";"!==e.token,r.push({node:t,visible:n}));return r.length>0?new o(r):(t||((t=new u(void 0)).comment=e.comment),t)}(n);if(""!==n.token)throw n.tokenType===C?le(n,"Unexpected operator "+n.token):oe(n,'Unexpected part "'+n.token+'"');return r}function L(e){var t,n,r,a,i=function(e){for(var t=function(e){for(var t=z(e);"or"===e.token;)F(e),t=new h("or","or",[t,z(e)]);return t}(e);"?"===e.token;){var n=e.conditionalLevel;e.conditionalLevel=e.nestingLevel,F(e);var r=t,a=L(e);if(":"!==e.token)throw oe(e,"False part of conditional expression expected");e.conditionalLevel=null,F(e);var i=L(e);t=new l(r,a,i),e.conditionalLevel=n}return t}(e);if("="===e.token){if(isSymbolNode(i))return t=i.name,F(e),r=L(e),new s(new b(t),r);if(isAccessorNode(i))return F(e),r=L(e),new s(i.object,i.index,r);if(isFunctionNode(i)&&isSymbolNode(i.fn)&&(a=!0,n=[],t=i.name,i.args.forEach((function(e,t){isSymbolNode(e)?n[t]=e.name:a=!1})),a))return F(e),r=L(e),new c(t,n,r);throw oe(e,"Invalid left hand side of assignment operator =")}return i}function z(e){for(var t=U(e);"xor"===e.token;)F(e),t=new h("xor","xor",[t,U(e)]);return t}function U(e){for(var t=j(e);"and"===e.token;)F(e),t=new h("and","and",[t,j(e)]);return t}function j(e){for(var t=q(e);"|"===e.token;)F(e),t=new h("|","bitOr",[t,q(e)]);return t}function q(e){for(var t=G(e);"^|"===e.token;)F(e),t=new h("^|","bitXor",[t,G(e)]);return t}function G(e){for(var t=H(e);"&"===e.token;)F(e),t=new h("&","bitAnd",[t,H(e)]);return t}function H(e){for(var t=[W(e)],n=[],r={"==":"equal","!=":"unequal","<":"smaller",">":"larger","<=":"smallerEq",">=":"largerEq"};hasOwnProperty$2(r,e.token);){var a={name:e.token,fn:r[e.token]};n.push(a),F(e),t.push(W(e))}return 1===t.length?t[0]:2===t.length?new h(n[0].name,n[0].fn,t):new g(n.map((e=>e.fn)),t)}function W(e){var t,n,r,a;t=K(e);for(var i={"<<":"leftShift",">>":"rightArithShift",">>>":"rightLogShift"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),a=[t,K(e)],t=new h(n,r,a);return t}function K(e){var t,n,r,a;t=Z(e);for(var i={to:"to",in:"to"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),"in"===n&&""===e.token?t=new h("*","multiply",[t,new b("in")],!0):(a=[t,Z(e)],t=new h(n,r,a));return t}function Z(e){var t,n=[];if(t=":"===e.token?new u(1):X(e),":"===e.token&&e.conditionalLevel!==e.nestingLevel){for(n.push(t);":"===e.token&&n.length<3;)F(e),")"===e.token||"]"===e.token||","===e.token||""===e.token?n.push(new b("end")):n.push(X(e));t=3===n.length?new y(n[0],n[2],n[1]):new y(n[0],n[1])}return t}function X(e){var t,n,r,a;t=Y(e);for(var i={"+":"add","-":"subtract"};hasOwnProperty$2(i,e.token);){r=i[n=e.token],F(e);var s=Y(e);a=s.isPercentage?[t,new h("*","multiply",[t,s])]:[t,s],t=new h(n,r,a)}return t}function Y(e){var t,n,r,a;n=t=Q(e);for(var i={"*":"multiply",".*":"dotMultiply","/":"divide","./":"dotDivide"};hasOwnProperty$2(i,e.token);)a=i[r=e.token],F(e),n=Q(e),t=new h(r,a,[t,n]);return t}function Q(e){var t,n;for(n=t=J(e);e.tokenType===V||"in"===e.token&&isConstantNode(t)||!(e.tokenType!==A||isConstantNode(n)||isOperatorNode(n)&&"!"!==n.op)||"("===e.token;)n=J(e),t=new h("*","multiply",[t,n],!0);return t}function J(e){for(var t=ee(e),n=t,r=[];"/"===e.token&&isConstantNode(n);){if(r.push(_extends$1({},e)),F(e),e.tokenType!==A){_extends$1(e,r.pop());break}if(r.push(_extends$1({},e)),F(e),e.tokenType!==V&&"("!==e.token){r.pop(),_extends$1(e,r.pop());break}_extends$1(e,r.pop()),r.pop(),n=ee(e),t=new h("/","divide",[t,n])}return t}function ee(e){var t,n,r,a;t=te(e);for(var i={"%":"mod",mod:"mod"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),"%"===n&&e.tokenType===C&&"("!==e.token?t=new h("/","divide",[t,new u(100)],!1,!0):(a=[t,te(e)],t=new h(n,r,a));return t}function te(e){var t,a,s,o={"-":"unaryMinus","+":"unaryPlus","~":"bitNot",not:"not"};return hasOwnProperty$2(o,e.token)?(s=o[e.token],t=e.token,F(e),a=[te(e)],new h(t,s,a)):function(e){var t,a,s,o;return t=function(e){var t,a,s;t=function(e){var t=[];if(e.tokenType===V&&hasOwnProperty$2(e.extraNodes,e.token)){var a=e.extraNodes[e.token];if(P(e),"("===e.token){if(t=[],k(e),P(e),")"!==e.token)for(t.push(L(e));","===e.token;)P(e),t.push(L(e));if(")"!==e.token)throw oe(e,"Parenthesis ) expected");$(e),P(e)}return new a(t)}return function(e){var t;return e.tokenType===V||e.tokenType===C&&e.token in w?(t=e.token,P(e),ne(e,hasOwnProperty$2(E,t)?new u(E[t]):-1!==D.indexOf(t)?new u(n(t,"number")):new b(t))):function(e){var t;return'"'===e.token?(t=re(e),ne(e,new u(t))):function(e){var t;return"'"===e.token?(t=ae(e),ne(e,new u(t))):function(e){var t,a,s,o;if("["===e.token){if(k(e),P(e),"]"!==e.token){var l=ie(e);if(";"===e.token){for(s=1,a=[l];";"===e.token;)P(e),a[s]=ie(e),s++;if("]"!==e.token)throw oe(e,"End of matrix ] expected");$(e),P(e),o=a[0].items.length;for(var c=1;c0},v.isDecimalMark=function(e,t){return"."===e&&"/"!==t&&"*"!==t&&"^"!==t},v.isDigitDot=function(e){return e>="0"&&e<="9"||"."===e},v.isDigit=function(e){return e>="0"&&e<="9"},v.isHexDigit=function(e){return e>="0"&&e<="9"||e>="a"&&e<="f"||e>="A"&&e<="F"},v})),name$1d="compile",dependencies$1d=["typed","parse"],createCompile=factory(name$1d,dependencies$1d,(e=>{var{typed:t,parse:n}=e;return t(name$1d,{string:function(e){return n(e).compile()},"Array | Matrix":function(e){return deepMap(e,(function(e){return n(e).compile()}))}})})),name$1c="evaluate",dependencies$1c=["typed","parse"],createEvaluate=factory(name$1c,dependencies$1c,(e=>{var{typed:t,parse:n}=e;return t(name$1c,{string:function(e){var t=createEmptyMap();return n(e).compile().evaluate(t)},"string, Map | Object":function(e,t){return n(e).compile().evaluate(t)},"Array | Matrix":function(e){var t=createEmptyMap();return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))},"Array | Matrix, Map | Object":function(e,t){return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))}})})),name$1b="Parser",dependencies$1b=["evaluate"],createParserClass=factory(name$1b,dependencies$1b,(e=>{var{evaluate:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");Object.defineProperty(this,"scope",{value:createEmptyMap(),writable:!1})}return n.prototype.type="Parser",n.prototype.isParser=!0,n.prototype.evaluate=function(e){return t(e,this.scope)},n.prototype.get=function(e){if(this.scope.has(e))return this.scope.get(e)},n.prototype.getAll=function(){return toObject(this.scope)},n.prototype.getAllAsMap=function(){return this.scope},n.prototype.set=function(e,t){return this.scope.set(e,t),t},n.prototype.remove=function(e){this.scope.delete(e)},n.prototype.clear=function(){this.scope.clear()},n}),{isClass:!0}),name$1a="parser",dependencies$1a=["typed","Parser"],createParser=factory(name$1a,dependencies$1a,(e=>{var{typed:t,Parser:n}=e;return t(name$1a,{"":function(){return new n}})})),name$19="lup",dependencies$19=["typed","matrix","abs","addScalar","divideScalar","multiplyScalar","subtract","larger","equalScalar","unaryMinus","DenseMatrix","SparseMatrix","Spa"],createLup=factory(name$19,dependencies$19,(e=>{var{typed:t,matrix:n,abs:r,addScalar:a,divideScalar:i,multiplyScalar:s,subtract:o,larger:l,equalScalar:u,unaryMinus:c,DenseMatrix:p,SparseMatrix:d,Spa:m}=e;return t(name$19,{DenseMatrix:function(e){return h(e)},SparseMatrix:function(e){return function(e){var t,n,a,o=e._size[0],p=e._size[1],h=Math.min(o,p),f=e._values,y=e._index,g=e._ptr,b=[],v=[],N=[],T=[o,h],C=[],A=[],V=[],x=[h,p],S=[],w=[];for(t=0;t0&&e.forEach(0,n-1,(function(t,n){d._forEachRow(t,b,v,N,(function(r,a){r>t&&e.accumulate(r,c(s(a,n)))}))}));var E=n,D=e.get(n),O=r(D);e.forEach(n+1,o-1,(function(e,t){var n=r(t);l(n,O)&&(E=e,O=n,D=t)})),n!==E&&(d._swapRows(n,E,T[1],b,v,N),d._swapRows(n,E,x[1],C,A,V),e.swap(n,E),function(e,t){var n=w[e],r=w[t];S[n]=t,S[r]=e,w[e]=r,w[t]=n}(n,E)),e.forEach(0,o-1,(function(e,t){e<=n?(C.push(t),A.push(e)):(t=i(t,D),u(t,0)||(b.push(t),v.push(e)))}))};for(n=0;n0)for(t=0;t{var{typed:t,matrix:n,zeros:r,identity:a,isZero:i,equal:s,sign:o,sqrt:l,conj:u,unaryMinus:c,addScalar:p,divideScalar:d,multiplyScalar:m,subtract:h,complex:f}=e;return _extends$1(t(name$18,{DenseMatrix:function(e){return g(e)},SparseMatrix:function(e){return function(e){throw new Error("qr not implemented for sparse matrices yet")}()},Array:function(e){var t=g(n(e));return{Q:t.Q.valueOf(),R:t.R.valueOf()}}}),{_denseQRimpl:y});function y(e){var t,n,f,y=e._size[0],g=e._size[1],b=a([y],"dense"),v=b._data,N=e.clone(),T=N._data,C=r([y],"");for(f=0;f0)for(var r="Complex"===n[0][0].type?f(0):0,a=0;a=0;){var l=n[s+o],u=n[r+l];-1===u?(o--,i[t++]=l):(n[r+l]=n[a+u],n[s+ ++o]=u)}return t}function csPost(e,t){if(!e)return null;var n,r=0,a=[],i=[],s=t,o=2*t;for(n=0;n=0;n--)-1!==e[n]&&(i[s+n]=i[0+e[n]],i[0+e[n]]=n);for(n=0;n{var{add:t,multiply:n,transpose:r}=e;return function(e,s){if(!s||e<=0||e>3)return null;var o=s._size,l=o[0],u=o[1],c=0,p=Math.max(16,10*Math.sqrt(u)),d=function(e,a,i,s,o){var l=r(a);if(1===e&&s===i)return t(a,l);if(2===e){for(var u=l._index,c=l._ptr,p=0,d=0;do))for(var h=c[d+1];ms)n[o+d]=0,n[a+d]=-1,p++,t[d]=csFlip(e),n[o+e]++;else{var h=n[l+m];-1!==h&&(u[h]=d),n[c+d]=n[l+m],n[l+m]=d}}return p}(u,O,_,$,k,B,p,M,F,z,P),q=0;jG?(b=f,v=K,N=_[0+f]-G):(v=O[b=D[K++]],N=_[0+b]),g=1;g<=N;g++)(T=_[M+(m=D[v++])])<=0||(W+=T,_[M+m]=-T,D[X++]=m,-1!==_[P+m]&&(z[_[P+m]]=z[m]),-1!==z[m]?_[P+z[m]]=_[P+m]:_[F+_[$+m]]=_[P+m]);b!==f&&(O[b]=csFlip(f),_[B+b]=0)}for(0!==G&&(I=X),_[$+f]=W,O[f]=Z,_[0+f]=X-Z,_[k+f]=-2,U=a(U,c,_,B,u),C=Z;C=U?_[B+b]-=T:0!==_[B+b]&&(_[B+b]=_[$+b]+Y)}for(C=Z;C0?(E+=Q,D[S++]=b,w+=b):(O[b]=csFlip(f),_[B+b]=0)}_[k+m]=S-V+1;var J=S,ee=V+_[0+m];for(K=x+1;K=0))for(m=_[L+(w=z[m])],_[L+w]=-1;-1!==m&&-1!==_[P+m];m=_[P+m],U++){for(N=_[0+m],A=_[k+m],K=O[m]+1;K<=O[m]+N-1;K++)_[B+D[K]]=U;var ne=m;for(h=_[P+m];-1!==h;){var re=_[0+h]===N&&_[k+h]===A;for(K=O[h]+1;re&&K<=O[h]+N-1;K++)_[B+D[K]]!==U&&(re=0);re?(O[h]=csFlip(m),_[M+m]+=_[M+h],_[M+h]=0,_[k+h]=-1,h=_[P+h],_[P+ne]=h):(ne=h,h=_[P+h])}}for(K=Z,C=Z;C=0;h--)_[M+h]>0||(_[P+h]=_[F+O[h]],_[F+O[h]]=h);for(b=u;b>=0;b--)_[M+b]<=0||-1!==O[b]&&(_[P+b]=_[F+O[b]],_[F+O[b]]=b);for(f=0,m=0;m<=u;m++)-1===O[m]&&(f=csTdfs(m,f,_,F,P,R,B));return R.splice(R.length-1,1),R};function a(e,t,n,r,a){if(e<2||e+t<0){for(var i=0;i{var{transpose:t}=e;return function(e,n,r,a){if(!e||!n||!r)return null;var i,s,o,l,u,c,p,d=e._size,m=d[0],h=d[1],f=4*h+(a?h+m+1:0),y=[],g=h,b=2*h,v=3*h,N=4*h,T=5*h+1;for(o=0;o=1&&C[s]++,2===S.jleaf&&C[S.q]--}-1!==n[s]&&(y[0+s]=n[s])}for(s=0;s{var{add:t,multiply:n,transpose:r}=e,a=createCsAmd({add:t,multiply:n,transpose:r}),i=createCsCounts({transpose:r});return function(e,t,n){var r,s=t._ptr,o=t._size[1],l={};if(l.q=a(e,t),e&&!l.q)return null;if(n){var u=e?csPermute(t,null,l.q,0):t;l.parent=csEtree(u,1);var c=csPost(l.parent,o);if(l.cp=i(u,l.parent,c,1),u&&l.parent&&l.cp&&function(e,t){var n=e._ptr,r=e._index,a=e._size,i=a[0],s=a[1];t.pinv=[],t.leftmost=[];var o,l,u,c,p,d=t.parent,m=t.pinv,h=t.leftmost,f=[],y=i,g=i+s,b=i+2*s;for(l=0;l=0;l--)for(c=n[l],p=n[l+1],u=c;u=0;o--)m[o]=-1,-1!==(l=h[o])&&(0==f[b+l]++&&(f[g+l]=o),f[0+o]=f[y+l],f[y+l]=o);for(t.lnz=0,t.m2=i,l=0;l=0;){e=r[p];var d=a?a[e]:e;csMarked(u,e)||(csMark(u,e),r[c+p]=d<0?0:csUnflip(u[d]));var m=1;for(s=r[c+p],o=d<0?0:csUnflip(u[d+1]);s{var{divideScalar:t,multiply:n,subtract:r}=e;return function(e,a,i,s,o,l,u){var c,p,d,m,h=e._values,f=e._index,y=e._ptr,g=e._size[1],b=a._values,v=a._index,N=a._ptr,T=csReach(e,a,i,s,l);for(c=T;c{var{abs:t,divideScalar:n,multiply:r,subtract:a,larger:i,largerEq:s,SparseMatrix:o}=e,l=createCsSpsolve({divideScalar:n,multiply:r,subtract:a});return function(e,a,u){if(!e)return null;var c,p=e._size[1],d=100,m=100;a&&(c=a.q,d=a.lnz||d,m=a.unz||m);var h,f,y=[],g=[],b=[],v=new o({values:y,index:g,ptr:b,size:[p,p]}),N=[],T=[],C=[],A=new o({values:N,index:T,ptr:C,size:[p,p]}),V=[],x=[],S=[];for(h=0;h{var{typed:t,abs:n,add:r,multiply:a,transpose:i,divideScalar:s,subtract:o,larger:l,largerEq:u,SparseMatrix:c}=e,p=createCsSqr({add:r,multiply:a,transpose:i}),d=createCsLu({abs:n,divideScalar:s,multiply:a,subtract:o,larger:l,largerEq:u,SparseMatrix:c});return t(name$12,{"SparseMatrix, number, number":function(e,t,n){if(!isInteger$1(t)||t<0||t>3)throw new Error("Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]");if(n<0||n>1)throw new Error("Partial pivoting threshold must be a number from 0 to 1");var r=p(t,e,!1),a=d(e,r,n);return{L:a.L,U:a.U,p:a.pinv,q:r.q,toString:function(){return"L: "+this.L.toString()+"\nU: "+this.U.toString()+"\np: "+this.p.toString()+(this.q?"\nq: "+this.q.toString():"")+"\n"}}}})}));function csIpvec(e,t){var n,r=t.length,a=[];if(e)for(n=0;n{var{typed:t,matrix:n,lup:r,slu:a,usolve:i,lsolve:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$11,{"Array, Array | Matrix":function(e,t){e=n(e);var a=r(e);return c(a.L,a.U,a.p,null,t).valueOf()},"DenseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix, number, number":function(e,t,n,r){var i=a(e,n,r);return c(i.L,i.U,i.p,i.q,t)},"Object, Array | Matrix":function(e,t){return c(e.L,e.U,e.p,e.q,t)}});function u(e){if(isMatrix(e))return e;if(isArray$1(e))return n(e);throw new TypeError("Invalid Matrix LU decomposition")}function c(e,t,n,r,a){e=u(e),t=u(t),n&&((a=l(e,a,!0))._data=csIpvec(n,a._data));var o=s(e,a),c=i(t,o);return r&&(c._data=csIpvec(r,c._data)),c}})),name$10="Help",dependencies$10=["parse"],createHelpClass=factory(name$10,dependencies$10,(e=>{var{parse:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!e)throw new Error('Argument "doc" missing');this.doc=e}return n.prototype.type="Help",n.prototype.isHelp=!0,n.prototype.toString=function(){var e=this.doc||{},n="\n";if(e.name&&(n+="Name: "+e.name+"\n\n"),e.category&&(n+="Category: "+e.category+"\n\n"),e.description&&(n+="Description:\n "+e.description+"\n\n"),e.syntax&&(n+="Syntax:\n "+e.syntax.join("\n ")+"\n\n"),e.examples){n+="Examples:\n";for(var r={},a=0;a"mathjs"!==e)).forEach((n=>{t[n]=e[n]})),new n(t)},n.prototype.valueOf=n.prototype.toString,n}),{isClass:!0}),name$$="Chain",dependencies$$=["?on","math"],createChainClass=factory(name$$,dependencies$$,(e=>{var{on:t,math:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");isChain(e)?this.value=e.value:this.value=e}function a(e,t){lazy(r.prototype,e,(function(){var e=t();if("function"==typeof e)return i(e)}))}function i(e){return function(){for(var t=[this.value],n=0;ne[t]))};for(var o in e)n(o)}};var s={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return r.createProxy(n),t&&t("import",(function(e,t,n){n||a(e,t)})),r}),{isClass:!0}),eDocs={name:"e",category:"Constants",syntax:["e"],description:"Euler's number, the base of the natural logarithm. Approximately equal to 2.71828",examples:["e","e ^ 2","exp(2)","log(e)"],seealso:["exp"]},falseDocs={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]},iDocs={name:"i",category:"Constants",syntax:["i"],description:"Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.",examples:["i","i * i","sqrt(-1)"],seealso:[]},InfinityDocs={name:"Infinity",category:"Constants",syntax:["Infinity"],description:"Infinity, a number which is larger than the maximum number that can be handled by a floating point number.",examples:["Infinity","1 / 0"],seealso:[]},LN10Docs={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]},LN2Docs={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]},LOG10EDocs={name:"LOG10E",category:"Constants",syntax:["LOG10E"],description:"Returns the base-10 logarithm of E, approximately equal to 0.434",examples:["LOG10E","log(e, 10)"],seealso:[]},LOG2EDocs={name:"LOG2E",category:"Constants",syntax:["LOG2E"],description:"Returns the base-2 logarithm of E, approximately equal to 1.442",examples:["LOG2E","log(e, 2)"],seealso:[]},NaNDocs={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]},nullDocs={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]},phiDocs={name:"phi",category:"Constants",syntax:["phi"],description:"Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...",examples:["phi"],seealso:[]},piDocs={name:"pi",category:"Constants",syntax:["pi"],description:"The number pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, and is approximately equal to 3.14159",examples:["pi","sin(pi/2)"],seealso:["tau"]},SQRT12Docs={name:"SQRT1_2",category:"Constants",syntax:["SQRT1_2"],description:"Returns the square root of 1/2, approximately equal to 0.707",examples:["SQRT1_2","sqrt(1/2)"],seealso:[]},SQRT2Docs={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]},tauDocs={name:"tau",category:"Constants",syntax:["tau"],description:"Tau is the ratio constant of a circle's circumference to radius, equal to 2 * pi, approximately 6.2832.",examples:["tau","2 * pi"],seealso:["pi"]},trueDocs={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]},versionDocs={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]},bignumberDocs={name:"bignumber",category:"Construction",syntax:["bignumber(x)"],description:"Create a big number from a number or string.",examples:["0.1 + 0.2","bignumber(0.1) + bignumber(0.2)",'bignumber("7.2")','bignumber("7.2e500")',"bignumber([0.1, 0.2, 0.3])"],seealso:["boolean","complex","fraction","index","matrix","string","unit"]},booleanDocs={name:"boolean",category:"Construction",syntax:["x","boolean(x)"],description:"Convert a string or number into a boolean.",examples:["boolean(0)","boolean(1)","boolean(3)",'boolean("true")','boolean("false")',"boolean([1, 0, 1, 1])"],seealso:["bignumber","complex","index","matrix","number","string","unit"]},complexDocs={name:"complex",category:"Construction",syntax:["complex()","complex(re, im)","complex(string)"],description:"Create a complex number.",examples:["complex()","complex(2, 3)",'complex("7 - 2i")'],seealso:["bignumber","boolean","index","matrix","number","string","unit"]},createUnitDocs={name:"createUnit",category:"Construction",syntax:["createUnit(definitions)","createUnit(name, definition)"],description:"Create a user-defined unit and register it with the Unit type.",examples:['createUnit("foo")','createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})','createUnit("mph", "1 mile/hour")'],seealso:["unit","splitUnit"]},fractionDocs={name:"fraction",category:"Construction",syntax:["fraction(num)","fraction(matrix)","fraction(num,den)","fraction({n: num, d: den})"],description:"Create a fraction from a number or from integer numerator and denominator.",examples:["fraction(0.125)","fraction(1, 3) + fraction(2, 5)","fraction({n: 333, d: 53})","fraction([sqrt(9), sqrt(10), sqrt(11)])"],seealso:["bignumber","boolean","complex","index","matrix","string","unit"]},indexDocs={name:"index",category:"Construction",syntax:["[start]","[start:end]","[start:step:end]","[start1, start 2, ...]","[start1:end1, start2:end2, ...]","[start1:step1:end1, start2:step2:end2, ...]"],description:"Create an index to get or replace a subset of a matrix",examples:["[]","[1, 2, 3]","A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[0:2, 0:2] = ones(2, 2)"],seealso:["bignumber","boolean","complex","matrix,","number","range","string","unit"]},matrixDocs={name:"matrix",category:"Construction",syntax:["[]","[a1, b1, ...; a2, b2, ...]","matrix()",'matrix("dense")',"matrix([...])"],description:"Create a matrix.",examples:["[]","[1, 2, 3]","[1, 2, 3; 4, 5, 6]","matrix()","matrix([3, 4])",'matrix([3, 4; 5, 6], "sparse")','matrix([3, 4; 5, 6], "sparse", "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","sparse"]},numberDocs={name:"number",category:"Construction",syntax:["x","number(x)","number(unit, valuelessUnit)"],description:"Create a number or convert a string or boolean into a number.",examples:["2","2e3","4.05","number(2)",'number("7.2")',"number(true)","number([true, false, true, true])",'number(unit("52cm"), "m")'],seealso:["bignumber","boolean","complex","fraction","index","matrix","string","unit"]},sparseDocs={name:"sparse",category:"Construction",syntax:["sparse()","sparse([a1, b1, ...; a1, b2, ...])",'sparse([a1, b1, ...; a1, b2, ...], "number")'],description:"Create a sparse matrix.",examples:["sparse()","sparse([3, 4; 5, 6])",'sparse([3, 0; 5, 0], "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","matrix"]},splitUnitDocs={name:"splitUnit",category:"Construction",syntax:["splitUnit(unit: Unit, parts: Unit[])"],description:"Split a unit in an array of units whose sum is equal to the original unit.",examples:['splitUnit(1 m, ["feet", "inch"])'],seealso:["unit","createUnit"]},stringDocs={name:"string",category:"Construction",syntax:['"text"',"string(x)"],description:"Create a string or convert a value to a string",examples:['"Hello World!"',"string(4.2)","string(3 + 2i)"],seealso:["bignumber","boolean","complex","index","matrix","number","unit"]},unitDocs={name:"unit",category:"Construction",syntax:["value unit","unit(value, unit)","unit(string)"],description:"Create a unit.",examples:["5.5 mm","3 inch",'unit(7.1, "kilogram")','unit("23 deg")'],seealso:["bignumber","boolean","complex","index","matrix","number","string"]},configDocs={name:"config",category:"Core",syntax:["config()","config(options)"],description:"Get configuration or change configuration.",examples:["config()","1/3 + 1/4",'config({number: "Fraction"})',"1/3 + 1/4"],seealso:[]},importDocs={name:"import",category:"Core",syntax:["import(functions)","import(functions, options)"],description:"Import functions or constants from an object.",examples:["import({myFn: f(x)=x^2, myConstant: 32 })","myFn(2)","myConstant"],seealso:[]},typedDocs={name:"typed",category:"Core",syntax:["typed(signatures)","typed(name, signatures)"],description:"Create a typed function.",examples:['double = typed({ "number": f(x)=x+x })',"double(2)",'double("hello")'],seealso:[]},derivativeDocs={name:"derivative",category:"Algebra",syntax:["derivative(expr, variable)","derivative(expr, variable, {simplify: boolean})"],description:"Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.",examples:['derivative("2x^3", "x")','derivative("2x^3", "x", {simplify: false})','derivative("2x^2 + 3x + 4", "x")','derivative("sin(2x)", "x")','f = parse("x^2 + x")','x = parse("x")',"df = derivative(f, x)","df.evaluate({x: 3})"],seealso:["simplify","parse","evaluate"]},leafCountDocs={name:"leafCount",category:"Algebra",syntax:["leafCount(expr)"],description:"Computes the number of leaves in the parse tree of the given expression",examples:['leafCount("e^(i*pi)-1")','leafCount(parse("{a: 22/7, b: 10^(1/2)}"))'],seealso:["simplify"]},lsolveDocs={name:"lsolve",category:"Algebra",syntax:["x=lsolve(L, b)"],description:"Finds one solution of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolveAll","lup","lusolve","usolve","matrix","sparse"]},lsolveAllDocs={name:"lsolveAll",category:"Algebra",syntax:["x=lsolveAll(L, b)"],description:"Finds all solutions of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolve","lup","lusolve","usolve","matrix","sparse"]},lupDocs={name:"lup",category:"Algebra",syntax:["lup(m)"],description:"Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U",examples:["lup([[2, 1], [1, 4]])","lup(matrix([[2, 1], [1, 4]]))","lup(sparse([[2, 1], [1, 4]]))"],seealso:["lusolve","lsolve","usolve","matrix","sparse","slu","qr"]},lusolveDocs={name:"lusolve",category:"Algebra",syntax:["x=lusolve(A, b)","x=lusolve(lu, b)"],description:"Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lusolve(a, b)"],seealso:["lup","slu","lsolve","usolve","matrix","sparse"]},qrDocs={name:"qr",category:"Algebra",syntax:["qr(A)"],description:"Calculates the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix.",examples:["qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])"],seealso:["lup","slu","matrix"]},rationalizeDocs={name:"rationalize",category:"Algebra",syntax:["rationalize(expr)","rationalize(expr, scope)","rationalize(expr, scope, detailed)"],description:"Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.",examples:['rationalize("2x/y - y/(x+1)")','rationalize("2x/y - y/(x+1)", true)'],seealso:["simplify"]},resolveDocs={name:"resolve",category:"Algebra",syntax:["resolve(node, scope)"],description:"Recursively substitute variables in an expression tree.",examples:['resolve(parse("1 + x"), { x: 7 })','resolve(parse("size(text)"), { text: "Hello World" })','resolve(parse("x + y"), { x: parse("3z") })','resolve(parse("3x"), { x: parse("y+z"), z: parse("w^y") })'],seealso:["simplify","evaluate"],mayThrow:["ReferenceError"]},simplifyDocs={name:"simplify",category:"Algebra",syntax:["simplify(expr)","simplify(expr, rules)"],description:"Simplify an expression tree.",examples:['simplify("3 + 2 / 4")','simplify("2x + x")','f = parse("x * (x + 2 + x)")',"simplified = simplify(f)","simplified.evaluate({x: 2})"],seealso:["simplifyCore","derivative","evaluate","parse","rationalize","resolve"]},simplifyCoreDocs={name:"simplifyCore",category:"Algebra",syntax:["simplifyCore(node)"],description:"Perform simple one-pass simplifications on an expression tree.",examples:['simplifyCore(parse("0*x"))','simplifyCore(parse("(x+0)*2"))'],seealso:["simplify","evaluate"]},sluDocs={name:"slu",category:"Algebra",syntax:["slu(A, order, threshold)"],description:"Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U",examples:["slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)"],seealso:["lusolve","lsolve","usolve","matrix","sparse","lup","qr"]},symbolicEqualDocs={name:"symbolicEqual",category:"Algebra",syntax:["symbolicEqual(expr1, expr2)","symbolicEqual(expr1, expr2, options)"],description:"Returns true if the difference of the expressions simplifies to 0",examples:['symbolicEqual("x*y","y*x")','symbolicEqual("abs(x^2)", "x^2")','symbolicEqual("abs(x)", "x", {context: {abs: {trivial: true}}})'],seealso:["simplify","evaluate"]},usolveDocs={name:"usolve",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolveAll","lup","lusolve","lsolve","matrix","sparse"]},usolveAllDocs={name:"usolveAll",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds all solutions of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolve","lup","lusolve","lsolve","matrix","sparse"]},absDocs={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]},addDocs={name:"add",category:"Operators",syntax:["x + y","add(x, y)"],description:"Add two values.",examples:["a = 2.1 + 3.6","a - 3.6","3 + 2i","3 cm + 2 inch",'"2.3" + "4"'],seealso:["subtract"]},cbrtDocs={name:"cbrt",category:"Arithmetic",syntax:["cbrt(x)","cbrt(x, allRoots)"],description:"Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned",examples:["cbrt(64)","cube(4)","cbrt(-8)","cbrt(2 + 3i)","cbrt(8i)","cbrt(8i, true)","cbrt(27 m^3)"],seealso:["square","sqrt","cube","multiply"]},ceilDocs={name:"ceil",category:"Arithmetic",syntax:["ceil(x)"],description:"Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.",examples:["ceil(3.2)","ceil(3.8)","ceil(-4.2)"],seealso:["floor","fix","round"]},cubeDocs={name:"cube",category:"Arithmetic",syntax:["cube(x)"],description:"Compute the cube of a value. The cube of x is x * x * x.",examples:["cube(2)","2^3","2 * 2 * 2"],seealso:["multiply","square","pow"]},divideDocs={name:"divide",category:"Operators",syntax:["x / y","divide(x, y)"],description:"Divide two values.",examples:["a = 2 / 3","a * 3","4.5 / 2","3 + 4 / 2","(3 + 4) / 2","18 km / 4.5"],seealso:["multiply"]},dotDivideDocs={name:"dotDivide",category:"Operators",syntax:["x ./ y","dotDivide(x, y)"],description:"Divide two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a ./ b"],seealso:["multiply","dotMultiply","divide"]},dotMultiplyDocs={name:"dotMultiply",category:"Operators",syntax:["x .* y","dotMultiply(x, y)"],description:"Multiply two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a .* b"],seealso:["multiply","divide","dotDivide"]},dotPowDocs={name:"dotPow",category:"Operators",syntax:["x .^ y","dotPow(x, y)"],description:"Calculates the power of x to y element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","a .^ 2"],seealso:["pow"]},expDocs={name:"exp",category:"Arithmetic",syntax:["exp(x)"],description:"Calculate the exponent of a value.",examples:["exp(1.3)","e ^ 1.3","log(exp(1.3))","x = 2.4","(exp(i*x) == cos(x) + i*sin(x)) # Euler's formula"],seealso:["expm","expm1","pow","log"]},expmDocs={name:"expm",category:"Arithmetic",syntax:["exp(x)"],description:"Compute the matrix exponential, expm(A) = e^A. The matrix must be square. Not to be confused with exp(a), which performs element-wise exponentiation.",examples:["expm([[0,2],[0,0]])"],seealso:["exp"]},expm1Docs={name:"expm1",category:"Arithmetic",syntax:["expm1(x)"],description:"Calculate the value of subtracting 1 from the exponential value.",examples:["expm1(2)","pow(e, 2) - 1","log(expm1(2) + 1)"],seealso:["exp","pow","log"]},fixDocs={name:"fix",category:"Arithmetic",syntax:["fix(x)"],description:"Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.",examples:["fix(3.2)","fix(3.8)","fix(-4.2)","fix(-4.8)"],seealso:["ceil","floor","round"]},floorDocs={name:"floor",category:"Arithmetic",syntax:["floor(x)"],description:"Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.",examples:["floor(3.2)","floor(3.8)","floor(-4.2)"],seealso:["ceil","fix","round"]},gcdDocs={name:"gcd",category:"Arithmetic",syntax:["gcd(a, b)","gcd(a, b, c, ...)"],description:"Compute the greatest common divisor.",examples:["gcd(8, 12)","gcd(-4, 6)","gcd(25, 15, -10)"],seealso:["lcm","xgcd"]},hypotDocs={name:"hypot",category:"Arithmetic",syntax:["hypot(a, b, c, ...)","hypot([a, b, c, ...])"],description:"Calculate the hypotenusa of a list with values. ",examples:["hypot(3, 4)","sqrt(3^2 + 4^2)","hypot(-2)","hypot([3, 4, 5])"],seealso:["abs","norm"]},invmodDocs={name:"invmod",category:"Arithmetic",syntax:["invmod(a, b)"],description:"Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation ax ≣ 1 (mod b)",examples:["invmod(8, 12)=NaN","invmod(7, 13)=2","math.invmod(15151, 15122)=10429"],seealso:["gcd","xgcd"]},lcmDocs={name:"lcm",category:"Arithmetic",syntax:["lcm(x, y)"],description:"Compute the least common multiple.",examples:["lcm(4, 6)","lcm(6, 21)","lcm(6, 21, 5)"],seealso:["gcd"]},logDocs={name:"log",category:"Arithmetic",syntax:["log(x)","log(x, base)"],description:"Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).",examples:["log(3.5)","a = log(2.4)","exp(a)","10 ^ 4","log(10000, 10)","log(10000) / log(10)","b = log(1024, 2)","2 ^ b"],seealso:["exp","log1p","log2","log10"]},log10Docs={name:"log10",category:"Arithmetic",syntax:["log10(x)"],description:"Compute the 10-base logarithm of a value.",examples:["log10(0.00001)","log10(10000)","10 ^ 4","log(10000) / log(10)","log(10000, 10)"],seealso:["exp","log"]},log1pDocs={name:"log1p",category:"Arithmetic",syntax:["log1p(x)","log1p(x, base)"],description:"Calculate the logarithm of a `value+1`",examples:["log1p(2.5)","exp(log1p(1.4))","pow(10, 4)","log1p(9999, 10)","log1p(9999) / log(10)"],seealso:["exp","log","log2","log10"]},log2Docs={name:"log2",category:"Arithmetic",syntax:["log2(x)"],description:"Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.",examples:["log2(0.03125)","log2(16)","log2(16) / log2(2)","pow(2, 4)"],seealso:["exp","log1p","log","log10"]},modDocs={name:"mod",category:"Operators",syntax:["x % y","x mod y","mod(x, y)"],description:"Calculates the modulus, the remainder of an integer division.",examples:["7 % 3","11 % 2","10 mod 4","isOdd(x) = x % 2","isOdd(2)","isOdd(3)"],seealso:["divide"]},multiplyDocs={name:"multiply",category:"Operators",syntax:["x * y","multiply(x, y)"],description:"multiply two values.",examples:["a = 2.1 * 3.4","a / 3.4","2 * 3 + 4","2 * (3 + 4)","3 * 2.1 km"],seealso:["divide"]},normDocs={name:"norm",category:"Arithmetic",syntax:["norm(x)","norm(x, p)"],description:"Calculate the norm of a number, vector or matrix.",examples:["abs(-3.5)","norm(-3.5)","norm(3 - 4i)","norm([1, 2, -3], Infinity)","norm([1, 2, -3], -Infinity)","norm([3, 4], 2)","norm([[1, 2], [3, 4]], 1)",'norm([[1, 2], [3, 4]], "inf")','norm([[1, 2], [3, 4]], "fro")']},nthRootDocs={name:"nthRoot",category:"Arithmetic",syntax:["nthRoot(a)","nthRoot(a, root)"],description:'Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation "x^root = A".',examples:["4 ^ 3","nthRoot(64, 3)","nthRoot(9, 2)","sqrt(9)"],seealso:["nthRoots","pow","sqrt"]},nthRootsDocs={name:"nthRoots",category:"Arithmetic",syntax:["nthRoots(A)","nthRoots(A, root)"],description:'Calculate the nth roots of a value. An nth root of a positive real number A, is a positive real solution of the equation "x^root = A". This function returns an array of complex values.',examples:["nthRoots(1)","nthRoots(1, 3)"],seealso:["sqrt","pow","nthRoot"]},powDocs={name:"pow",category:"Operators",syntax:["x ^ y","pow(x, y)"],description:"Calculates the power of x to y, x^y.",examples:["2^3","2*2*2","1 + e ^ (pi * i)","math.pow([[1, 2], [4, 3]], 2)","math.pow([[1, 2], [4, 3]], -1)"],seealso:["multiply","nthRoot","nthRoots","sqrt"]},roundDocs={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)"],description:"round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.",examples:["round(3.2)","round(3.8)","round(-4.2)","round(-4.8)","round(pi, 3)","round(123.45678, 2)"],seealso:["ceil","floor","fix"]},signDocs={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]},sqrtDocs={name:"sqrt",category:"Arithmetic",syntax:["sqrt(x)"],description:"Compute the square root value. If x = y * y, then y is the square root of x.",examples:["sqrt(25)","5 * 5","sqrt(-1)"],seealso:["square","sqrtm","multiply","nthRoot","nthRoots","pow"]},sqrtmDocs={name:"sqrtm",category:"Arithmetic",syntax:["sqrtm(x)"],description:"Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.",examples:["sqrtm([[1, 2], [3, 4]])"],seealso:["sqrt","abs","square","multiply"]},squareDocs={name:"square",category:"Arithmetic",syntax:["square(x)"],description:"Compute the square of a value. The square of x is x * x.",examples:["square(3)","sqrt(9)","3^2","3 * 3"],seealso:["multiply","pow","sqrt","cube"]},subtractDocs={name:"subtract",category:"Operators",syntax:["x - y","subtract(x, y)"],description:"subtract two values.",examples:["a = 5.3 - 2","a + 2","2/3 - 1/6","2 * 3 - 3","2.1 km - 500m"],seealso:["add"]},unaryMinusDocs={name:"unaryMinus",category:"Operators",syntax:["-x","unaryMinus(x)"],description:"Inverse the sign of a value. Converts booleans and strings to numbers.",examples:["-4.5","-(-5.6)",'-"22"'],seealso:["add","subtract","unaryPlus"]},unaryPlusDocs={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]},xgcdDocs={name:"xgcd",category:"Arithmetic",syntax:["xgcd(a, b)"],description:"Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.",examples:["xgcd(8, 12)","gcd(8, 12)","xgcd(36163, 21199)"],seealso:["gcd","lcm"]},bitAndDocs={name:"bitAnd",category:"Bitwise",syntax:["x & y","bitAnd(x, y)"],description:"Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0",examples:["5 & 3","bitAnd(53, 131)","[1, 12, 31] & 42"],seealso:["bitNot","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]},bitNotDocs={name:"bitNot",category:"Bitwise",syntax:["~x","bitNot(x)"],description:"Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.",examples:["~1","~2","bitNot([2, -3, 4])"],seealso:["bitAnd","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]},bitOrDocs={name:"bitOr",category:"Bitwise",syntax:["x | y","bitOr(x, y)"],description:"Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.",examples:["5 | 3","bitOr([1, 2, 3], 4)"],seealso:["bitAnd","bitNot","bitXor","leftShift","rightArithShift","rightLogShift"]},bitXorDocs={name:"bitXor",category:"Bitwise",syntax:["bitXor(x, y)"],description:"Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.",examples:["bitOr(1, 2)","bitXor([2, 3, 4], 4)"],seealso:["bitAnd","bitNot","bitOr","leftShift","rightArithShift","rightLogShift"]},leftShiftDocs={name:"leftShift",category:"Bitwise",syntax:["x << y","leftShift(x, y)"],description:"Bitwise left logical shift of a value x by y number of bits.",examples:["4 << 1","8 >> 1"],seealso:["bitAnd","bitNot","bitOr","bitXor","rightArithShift","rightLogShift"]},rightArithShiftDocs={name:"rightArithShift",category:"Bitwise",syntax:["x >> y","rightArithShift(x, y)"],description:"Bitwise right arithmetic shift of a value x by y number of bits.",examples:["8 >> 1","4 << 1","-12 >> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightLogShift"]},rightLogShiftDocs={name:"rightLogShift",category:"Bitwise",syntax:["x >>> y","rightLogShift(x, y)"],description:"Bitwise right logical shift of a value x by y number of bits.",examples:["8 >>> 1","4 << 1","-12 >>> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightArithShift"]},bellNumbersDocs={name:"bellNumbers",category:"Combinatorics",syntax:["bellNumbers(n)"],description:"The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["bellNumbers(3)","bellNumbers(8)"],seealso:["stirlingS2"]},catalanDocs={name:"catalan",category:"Combinatorics",syntax:["catalan(n)"],description:"The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["catalan(3)","catalan(8)"],seealso:["bellNumbers"]},compositionDocs={name:"composition",category:"Combinatorics",syntax:["composition(n, k)"],description:"The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.",examples:["composition(5, 3)"],seealso:["combinations"]},stirlingS2Docs={name:"stirlingS2",category:"Combinatorics",syntax:["stirlingS2(n, k)"],description:"he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.",examples:["stirlingS2(5, 3)"],seealso:["bellNumbers"]},argDocs={name:"arg",category:"Complex",syntax:["arg(x)"],description:"Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).",examples:["arg(2 + 2i)","atan2(3, 2)","arg(2 + 3i)"],seealso:["re","im","conj","abs"]},conjDocs={name:"conj",category:"Complex",syntax:["conj(x)"],description:"Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.",examples:["conj(2 + 3i)","conj(2 - 3i)","conj(-5.2i)"],seealso:["re","im","abs","arg"]},imDocs={name:"im",category:"Complex",syntax:["im(x)"],description:"Get the imaginary part of a complex number.",examples:["im(2 + 3i)","re(2 + 3i)","im(-5.2i)","im(2.4)"],seealso:["re","conj","abs","arg"]},reDocs={name:"re",category:"Complex",syntax:["re(x)"],description:"Get the real part of a complex number.",examples:["re(2 + 3i)","im(2 + 3i)","re(-5.2i)","re(2.4)"],seealso:["im","conj","abs","arg"]},evaluateDocs={name:"evaluate",category:"Expression",syntax:["evaluate(expression)","evaluate([expr1, expr2, expr3, ...])"],description:"Evaluate an expression or an array with expressions.",examples:['evaluate("2 + 3")','evaluate("sqrt(" + 4 + ")")'],seealso:[]},helpDocs={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]},distanceDocs={name:"distance",category:"Geometry",syntax:["distance([x1, y1], [x2, y2])","distance([[x1, y1], [x2, y2]])"],description:"Calculates the Euclidean distance between two points.",examples:["distance([0,0], [4,4])","distance([[0,0], [4,4]])"],seealso:[]},intersectDocs={name:"intersect",category:"Geometry",syntax:["intersect(expr1, expr2, expr3, expr4)","intersect(expr1, expr2, expr3)"],description:"Computes the intersection point of lines and/or planes.",examples:["intersect([0, 0], [10, 10], [10, 0], [0, 10])","intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])"],seealso:[]},andDocs={name:"and",category:"Logical",syntax:["x and y","and(x, y)"],description:"Logical and. Test whether two values are both defined with a nonzero/nonempty value.",examples:["true and false","true and true","2 and 4"],seealso:["not","or","xor"]},notDocs={name:"not",category:"Logical",syntax:["not x","not(x)"],description:"Logical not. Flips the boolean value of given argument.",examples:["not true","not false","not 2","not 0"],seealso:["and","or","xor"]},orDocs={name:"or",category:"Logical",syntax:["x or y","or(x, y)"],description:"Logical or. Test if at least one value is defined with a nonzero/nonempty value.",examples:["true or false","false or false","0 or 4"],seealso:["not","and","xor"]},xorDocs={name:"xor",category:"Logical",syntax:["x xor y","xor(x, y)"],description:"Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.",examples:["true xor false","false xor false","true xor true","0 xor 4"],seealso:["not","and","or"]},columnDocs={name:"column",category:"Matrix",syntax:["column(x, index)"],description:"Return a column from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","column(A, 1)","column(A, 2)"],seealso:["row","matrixFromColumns"]},concatDocs={name:"concat",category:"Matrix",syntax:["concat(A, B, C, ...)","concat(A, B, C, ..., dim)"],description:"Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.",examples:["A = [1, 2; 5, 6]","B = [3, 4; 7, 8]","concat(A, B)","concat(A, B, 1)","concat(A, B, 2)"],seealso:["det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},countDocs={name:"count",category:"Matrix",syntax:["count(x)"],description:"Count the number of elements of a matrix, array or string.",examples:["a = [1, 2; 3, 4; 5, 6]","count(a)","size(a)",'count("hello world")'],seealso:["size"]},crossDocs={name:"cross",category:"Matrix",syntax:["cross(A, B)"],description:"Calculate the cross product for two vectors in three dimensional space.",examples:["cross([1, 1, 0], [0, 1, 1])","cross([3, -3, 1], [4, 9, 2])","cross([2, 3, 4], [5, 6, 7])"],seealso:["multiply","dot"]},ctransposeDocs={name:"ctranspose",category:"Matrix",syntax:["x'","ctranspose(x)"],description:"Complex Conjugate and Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","ctranspose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]},detDocs={name:"det",category:"Matrix",syntax:["det(x)"],description:"Calculate the determinant of a matrix",examples:["det([1, 2; 3, 4])","det([-2, 2, 3; -1, 1, 3; 2, 0, -1])"],seealso:["concat","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},diagDocs={name:"diag",category:"Matrix",syntax:["diag(x)","diag(x, k)"],description:"Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.",examples:["diag(1:3)","diag(1:3, 1)","a = [1, 2, 3; 4, 5, 6; 7, 8, 9]","diag(a)"],seealso:["concat","det","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},diffDocs={name:"diff",category:"Matrix",syntax:["diff(arr)","diff(arr, dim)"],description:["Create a new matrix or array with the difference of the passed matrix or array.","Dim parameter is optional and used to indicant the dimension of the array/matrix to apply the difference","If no dimension parameter is passed it is assumed as dimension 0","Dimension is zero-based in javascript and one-based in the parser","Arrays must be 'rectangular' meaning arrays like [1, 2]","If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays"],examples:["diff([1, 2, 4, 7, 0])","diff([1, 2, 4, 7, 0], 0)","diff(matrix([1, 2, 4, 7, 0]))","diff([[1, 2], [3, 4]])","diff([[1, 2], [3, 4]], 0)","diff([[1, 2], [3, 4]], 1)","diff([[1, 2], [3, 4]], bignumber(1))","diff(matrix([[1, 2], [3, 4]]), 1)","diff([[1, 2], matrix([3, 4])], 1)"],seealso:["subtract","partitionSelect"]},dotDocs={name:"dot",category:"Matrix",syntax:["dot(A, B)","A * B"],description:"Calculate the dot product of two vectors. The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn",examples:["dot([2, 4, 1], [2, 2, 3])","[2, 4, 1] * [2, 2, 3]"],seealso:["multiply","cross"]},eigsDocs={name:"eigs",category:"Matrix",syntax:["eigs(x)"],description:"Calculate the eigenvalues and eigenvectors of a real symmetric matrix",examples:["eigs([[5, 2.3], [2.3, 1]])"],seealso:["inv"]},filterDocs={name:"filter",category:"Matrix",syntax:["filter(x, test)"],description:"Filter items in a matrix.",examples:["isPositive(x) = x > 0","filter([6, -2, -1, 4, 3], isPositive)","filter([6, -2, 0, 1, 0], x != 0)"],seealso:["sort","map","forEach"]},flattenDocs={name:"flatten",category:"Matrix",syntax:["flatten(x)"],description:"Flatten a multi dimensional matrix into a single dimensional matrix.",examples:["a = [1, 2, 3; 4, 5, 6]","size(a)","b = flatten(a)","size(b)"],seealso:["concat","resize","size","squeeze"]},forEachDocs={name:"forEach",category:"Matrix",syntax:["forEach(x, callback)"],description:"Iterates over all elements of a matrix/array, and executes the given callback function.",examples:["numberOfPets = {}","addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;",'forEach(["Dog","Cat","Cat"], addPet)',"numberOfPets"],seealso:["map","sort","filter"]},getMatrixDataTypeDocs={name:"getMatrixDataType",category:"Matrix",syntax:["getMatrixDataType(x)"],description:'Find the data type of all elements in a matrix or array, for example "number" if all items are a number and "Complex" if all values are complex numbers. If a matrix contains more than one data type, it will return "mixed".',examples:["getMatrixDataType([1, 2, 3])","getMatrixDataType([[5 cm], [2 inch]])",'getMatrixDataType([1, "text"])',"getMatrixDataType([1, bignumber(4)])"],seealso:["matrix","sparse","typeOf"]},identityDocs={name:"identity",category:"Matrix",syntax:["identity(n)","identity(m, n)","identity([m, n])"],description:"Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.",examples:["identity(3)","identity(3, 5)","a = [1, 2, 3; 4, 5, 6]","identity(size(a))"],seealso:["concat","det","diag","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},invDocs={name:"inv",category:"Matrix",syntax:["inv(x)"],description:"Calculate the inverse of a matrix",examples:["inv([1, 2; 3, 4])","inv(4)","1 / 4"],seealso:["concat","det","diag","identity","ones","range","size","squeeze","subset","trace","transpose","zeros"]},pinvDocs={name:"pinv",category:"Matrix",syntax:["pinv(x)"],description:"Calculate the Moore–Penrose inverse of a matrix",examples:["pinv([1, 2; 3, 4])","pinv([[1, 0], [0, 1], [0, 1]])","pinv(4)"],seealso:["inv"]},kronDocs={name:"kron",category:"Matrix",syntax:["kron(x, y)"],description:"Calculates the kronecker product of 2 matrices or vectors.",examples:["kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])","kron([1,1], [2,3,4])"],seealso:["multiply","dot","cross"]},mapDocs={name:"map",category:"Matrix",syntax:["map(x, callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.",examples:["map([1, 2, 3], square)"],seealso:["filter","forEach"]},matrixFromColumnsDocs={name:"matrixFromColumns",category:"Matrix",syntax:["math.matrixFromColumns(...arr)","math.matrixFromColumns(row1, row2)","math.matrixFromColumns(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual columns.",examples:["matrixFromColumns([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromRows","matrixFromFunction","zeros"]},matrixFromFunctionDocs={name:"matrixFromFunction",category:"Matrix",syntax:["math.matrixFromFunction(size, fn)","math.matrixFromFunction(size, fn, format)","math.matrixFromFunction(size, fn, format, datatype)","math.matrixFromFunction(size, format, fn)","math.matrixFromFunction(size, format, datatype, fn)"],description:"Create a matrix by evaluating a generating function at each index.",examples:["f(I) = I[1] - I[2]","matrixFromFunction([3,3], f)","g(I) = I[1] - I[2] == 1 ? 4 : 0",'matrixFromFunction([100, 100], "sparse", g)',"matrixFromFunction([5], random)"],seealso:["matrix","matrixFromRows","matrixFromColumns","zeros"]},matrixFromRowsDocs={name:"matrixFromRows",category:"Matrix",syntax:["math.matrixFromRows(...arr)","math.matrixFromRows(row1, row2)","math.matrixFromRows(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual rows.",examples:["matrixFromRows([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromColumns","matrixFromFunction","zeros"]},onesDocs={name:"ones",category:"Matrix",syntax:["ones(m)","ones(m, n)","ones(m, n, p, ...)","ones([m])","ones([m, n])","ones([m, n, p, ...])"],description:"Create a matrix containing ones.",examples:["ones(3)","ones(3, 5)","ones([2,3]) * 4.5","a = [1, 2, 3; 4, 5, 6]","ones(size(a))"],seealso:["concat","det","diag","identity","inv","range","size","squeeze","subset","trace","transpose","zeros"]},partitionSelectDocs={name:"partitionSelect",category:"Matrix",syntax:["partitionSelect(x, k)","partitionSelect(x, k, compare)"],description:"Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.",examples:["partitionSelect([5, 10, 1], 2)",'partitionSelect(["C", "B", "A", "D"], 1)'],seealso:["sort"]},rangeDocs={name:"range",category:"Type",syntax:["start:end","start:step:end","range(start, end)","range(start, end, step)","range(string)"],description:"Create a range. Lower bound of the range is included, upper bound is excluded.",examples:["1:5","3:-1:-3","range(3, 7)","range(0, 12, 2)",'range("4:10")',"a = [1, 2, 3, 4; 5, 6, 7, 8]","a[1:2, 1:2]"],seealso:["concat","det","diag","identity","inv","ones","size","squeeze","subset","trace","transpose","zeros"]},reshapeDocs={name:"reshape",category:"Matrix",syntax:["reshape(x, sizes)"],description:"Reshape a multi dimensional array to fit the specified dimensions.",examples:["reshape([1, 2, 3, 4, 5, 6], [2, 3])","reshape([[1, 2], [3, 4]], [1, 4])","reshape([[1, 2], [3, 4]], [4])"],seealso:["size","squeeze","resize"]},resizeDocs={name:"resize",category:"Matrix",syntax:["resize(x, size)","resize(x, size, defaultValue)"],description:"Resize a matrix.",examples:["resize([1,2,3,4,5], [3])","resize([1,2,3], [5])","resize([1,2,3], [5], -1)","resize(2, [2, 3])",'resize("hello", [8], "!")'],seealso:["size","subset","squeeze","reshape"]},rotateDocs={name:"rotate",category:"Matrix",syntax:["rotate(w, theta)","rotate(w, theta, v)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotate([1, 0], math.pi / 2)",'rotate(matrix([1, 0]), unit("35deg"))','rotate([1, 0, 0], unit("90deg"), [0, 0, 1])','rotate(matrix([1, 0, 0]), unit("90deg"), matrix([0, 0, 1]))'],seealso:["matrix","rotationMatrix"]},rotationMatrixDocs={name:"rotationMatrix",category:"Matrix",syntax:["rotationMatrix(theta)","rotationMatrix(theta, v)","rotationMatrix(theta, v, format)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotationMatrix(pi / 2)",'rotationMatrix(unit("45deg"), [0, 0, 1])','rotationMatrix(1, matrix([0, 0, 1]), "sparse")'],seealso:["cos","sin"]},rowDocs={name:"row",category:"Matrix",syntax:["row(x, index)"],description:"Return a row from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","row(A, 1)","row(A, 2)"],seealso:["column","matrixFromRows"]},sizeDocs={name:"size",category:"Matrix",syntax:["size(x)"],description:"Calculate the size of a matrix.",examples:["size(2.3)",'size("hello world")',"a = [1, 2; 3, 4; 5, 6]","size(a)","size(1:6)"],seealso:["concat","count","det","diag","identity","inv","ones","range","squeeze","subset","trace","transpose","zeros"]},sortDocs={name:"sort",category:"Matrix",syntax:["sort(x)","sort(x, compare)"],description:'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',examples:["sort([5, 10, 1])",'sort(["C", "B", "A", "D"])',"sortByLength(a, b) = size(a)[1] - size(b)[1]",'sort(["Langdon", "Tom", "Sara"], sortByLength)','sort(["10", "1", "2"], "natural")'],seealso:["map","filter","forEach"]},squeezeDocs={name:"squeeze",category:"Matrix",syntax:["squeeze(x)"],description:"Remove inner and outer singleton dimensions from a matrix.",examples:["a = zeros(3,2,1)","size(squeeze(a))","b = zeros(1,1,3)","size(squeeze(b))"],seealso:["concat","det","diag","identity","inv","ones","range","size","subset","trace","transpose","zeros"]},subsetDocs={name:"subset",category:"Matrix",syntax:["value(index)","value(index) = replacement","subset(value, [index])","subset(value, [index], replacement)"],description:"Get or set a subset of the entries of a matrix or characters of a string. Indexes are one-based. There should be one index specification for each dimension of the target. Each specification can be a single index, a list of indices, or a range in colon notation `l:u`. In a range, both the lower bound l and upper bound u are included; and if a bound is omitted it defaults to the most extreme valid value. The cartesian product of the indices specified in each dimension determines the target of the operation.",examples:["d = [1, 2; 3, 4]","e = []","e[1, 1:2] = [5, 6]","e[2, :] = [7, 8]","f = d * e","f[2, 1]","f[:, 1]","f[[1,2], [1,3]] = [9, 10; 11, 12]","f"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","trace","transpose","zeros"]},traceDocs={name:"trace",category:"Matrix",syntax:["trace(A)"],description:"Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.",examples:["A = [1, 2, 3; -1, 2, 3; 2, 0, 3]","trace(A)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","transpose","zeros"]},transposeDocs={name:"transpose",category:"Matrix",syntax:["x'","transpose(x)"],description:"Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","transpose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]},zerosDocs={name:"zeros",category:"Matrix",syntax:["zeros(m)","zeros(m, n)","zeros(m, n, p, ...)","zeros([m])","zeros([m, n])","zeros([m, n, p, ...])"],description:"Create a matrix containing zeros.",examples:["zeros(3)","zeros(3, 5)","a = [1, 2, 3; 4, 5, 6]","zeros(size(a))"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose"]},fftDocs={name:"fft",category:"Matrix",syntax:["fft(x)"],description:"Calculate N-dimensional fourier transform",examples:["fft([[1, 0], [1, 0]])"],seealso:["ifft"]},ifftDocs={name:"ifft",category:"Matrix",syntax:["ifft(x)"],description:"Calculate N-dimensional inverse fourier transform",examples:["ifft([[2, 2], [0, 0]])"],seealso:["fft"]},combinationsDocs={name:"combinations",category:"Probability",syntax:["combinations(n, k)"],description:"Compute the number of combinations of n items taken k at a time",examples:["combinations(7, 5)"],seealso:["combinationsWithRep","permutations","factorial"]},combinationsWithRepDocs={name:"combinationsWithRep",category:"Probability",syntax:["combinationsWithRep(n, k)"],description:"Compute the number of combinations of n items taken k at a time with replacements.",examples:["combinationsWithRep(7, 5)"],seealso:["combinations","permutations","factorial"]},factorialDocs={name:"factorial",category:"Probability",syntax:["n!","factorial(n)"],description:"Compute the factorial of a value",examples:["5!","5 * 4 * 3 * 2 * 1","3!"],seealso:["combinations","combinationsWithRep","permutations","gamma"]},gammaDocs={name:"gamma",category:"Probability",syntax:["gamma(n)"],description:"Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.",examples:["gamma(4)","3!","gamma(1/2)","sqrt(pi)"],seealso:["factorial"]},lgammaDocs={name:"lgamma",category:"Probability",syntax:["lgamma(n)"],description:"Logarithm of the gamma function for real, positive numbers and complex numbers, using Lanczos approximation for numbers and Stirling series for complex numbers.",examples:["lgamma(4)","lgamma(1/2)","lgamma(math.i)","lgamma(complex(1.1, 2))"],seealso:["gamma"]},kldivergenceDocs={name:"kldivergence",category:"Probability",syntax:["kldivergence(x, y)"],description:"Calculate the Kullback-Leibler (KL) divergence between two distributions.",examples:["kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])"],seealso:[]},multinomialDocs={name:"multinomial",category:"Probability",syntax:["multinomial(A)"],description:"Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.",examples:["multinomial([1, 2, 1])"],seealso:["combinations","factorial"]},permutationsDocs={name:"permutations",category:"Probability",syntax:["permutations(n)","permutations(n, k)"],description:"Compute the number of permutations of n items taken k at a time",examples:["permutations(5)","permutations(5, 3)"],seealso:["combinations","combinationsWithRep","factorial"]},pickRandomDocs={name:"pickRandom",category:"Probability",syntax:["pickRandom(array)","pickRandom(array, number)","pickRandom(array, weights)","pickRandom(array, number, weights)","pickRandom(array, weights, number)"],description:"Pick a random entry from a given array.",examples:["pickRandom(0:10)","pickRandom([1, 3, 1, 6])","pickRandom([1, 3, 1, 6], 2)","pickRandom([1, 3, 1, 6], [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)"],seealso:["random","randomInt"]},randomDocs={name:"random",category:"Probability",syntax:["random()","random(max)","random(min, max)","random(size)","random(size, max)","random(size, min, max)"],description:"Return a random number.",examples:["random()","random(10, 20)","random([2, 3])"],seealso:["pickRandom","randomInt"]},randomIntDocs={name:"randomInt",category:"Probability",syntax:["randomInt(max)","randomInt(min, max)","randomInt(size)","randomInt(size, max)","randomInt(size, min, max)"],description:"Return a random integer number",examples:["randomInt(10, 20)","randomInt([2, 3], 10)"],seealso:["pickRandom","random"]},compareDocs={name:"compare",category:"Relational",syntax:["compare(x, y)"],description:"Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compare(2, 3)","compare(3, 2)","compare(2, 2)","compare(5cm, 40mm)","compare(2, [1, 2, 3])"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compareNatural","compareText"]},compareNaturalDocs={name:"compareNatural",category:"Relational",syntax:["compareNatural(x, y)"],description:"Compare two values of any type in a deterministic, natural way. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compareNatural(2, 3)","compareNatural(3, 2)","compareNatural(2, 2)","compareNatural(5cm, 40mm)",'compareNatural("2", "10")',"compareNatural(2 + 3i, 2 + 4i)","compareNatural([1, 2, 4], [1, 2, 3])","compareNatural([1, 5], [1, 2, 3])","compareNatural([1, 2], [1, 2])","compareNatural({a: 2}, {a: 4})"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare","compareText"]},compareTextDocs={name:"compareText",category:"Relational",syntax:["compareText(x, y)"],description:"Compare two strings lexically. Comparison is case sensitive. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:['compareText("B", "A")','compareText("A", "B")','compareText("A", "A")','compareText("2", "10")','compare("2", "10")',"compare(2, 10)",'compareNatural("2", "10")','compareText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural"]},deepEqualDocs={name:"deepEqual",category:"Relational",syntax:["deepEqual(x, y)"],description:"Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.",examples:["deepEqual([1,3,4], [1,3,4])","deepEqual([1,3,4], [1,3])"],seealso:["equal","unequal","smaller","larger","smallerEq","largerEq","compare"]},equalDocs={name:"equal",category:"Relational",syntax:["x == y","equal(x, y)"],description:"Check equality of two values. Returns true if the values are equal, and false if not.",examples:["2+2 == 3","2+2 == 4","a = 3.2","b = 6-2.8","a == b","50cm == 0.5m"],seealso:["unequal","smaller","larger","smallerEq","largerEq","compare","deepEqual","equalText"]},equalTextDocs={name:"equalText",category:"Relational",syntax:["equalText(x, y)"],description:"Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.",examples:['equalText("Hello", "Hello")','equalText("a", "A")','equal("2e3", "2000")','equalText("2e3", "2000")','equalText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural","compareText","equal"]},largerDocs={name:"larger",category:"Relational",syntax:["x > y","larger(x, y)"],description:"Check if value x is larger than y. Returns true if x is larger than y, and false if not.",examples:["2 > 3","5 > 2*2","a = 3.3","b = 6-2.8","(a > b)","(b < a)","5 cm > 2 inch"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare"]},largerEqDocs={name:"largerEq",category:"Relational",syntax:["x >= y","largerEq(x, y)"],description:"Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.",examples:["2 >= 1+1","2 > 1+1","a = 3.2","b = 6-2.8","(a >= b)"],seealso:["equal","unequal","smallerEq","smaller","compare"]},smallerDocs={name:"smaller",category:"Relational",syntax:["x < y","smaller(x, y)"],description:"Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.",examples:["2 < 3","5 < 2*2","a = 3.3","b = 6-2.8","(a < b)","5 cm < 2 inch"],seealso:["equal","unequal","larger","smallerEq","largerEq","compare"]},smallerEqDocs={name:"smallerEq",category:"Relational",syntax:["x <= y","smallerEq(x, y)"],description:"Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.",examples:["2 <= 1+1","2 < 1+1","a = 3.2","b = 6-2.8","(a <= b)"],seealso:["equal","unequal","larger","smaller","largerEq","compare"]},unequalDocs={name:"unequal",category:"Relational",syntax:["x != y","unequal(x, y)"],description:"Check unequality of two values. Returns true if the values are unequal, and false if they are equal.",examples:["2+2 != 3","2+2 != 4","a = 3.2","b = 6-2.8","a != b","50cm != 0.5m","5 cm != 2 inch"],seealso:["equal","smaller","larger","smallerEq","largerEq","compare","deepEqual"]},setCartesianDocs={name:"setCartesian",category:"Set",syntax:["setCartesian(set1, set2)"],description:"Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays and the values will be sorted in ascending order before the operation.",examples:["setCartesian([1, 2], [3, 4])"],seealso:["setUnion","setIntersect","setDifference","setPowerset"]},setDifferenceDocs={name:"setDifference",category:"Set",syntax:["setDifference(set1, set2)"],description:"Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setDifference([1, 2, 3, 4], [3, 4, 5, 6])","setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setSymDifference"]},setDistinctDocs={name:"setDistinct",category:"Set",syntax:["setDistinct(set)"],description:"Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setDistinct([1, 1, 1, 2, 2, 3])"],seealso:["setMultiplicity"]},setIntersectDocs={name:"setIntersect",category:"Set",syntax:["setIntersect(set1, set2)"],description:"Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIntersect([1, 2, 3, 4], [3, 4, 5, 6])","setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setDifference"]},setIsSubsetDocs={name:"setIsSubset",category:"Set",syntax:["setIsSubset(set1, set2)"],description:"Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIsSubset([1, 2], [3, 4, 5, 6])","setIsSubset([3, 4], [3, 4, 5, 6])"],seealso:["setUnion","setIntersect","setDifference"]},setMultiplicityDocs={name:"setMultiplicity",category:"Set",syntax:["setMultiplicity(element, set)"],description:"Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setMultiplicity(1, [1, 2, 2, 4])","setMultiplicity(2, [1, 2, 2, 4])"],seealso:["setDistinct","setSize"]},setPowersetDocs={name:"setPowerset",category:"Set",syntax:["setPowerset(set)"],description:"Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setPowerset([1, 2, 3])"],seealso:["setCartesian"]},setSizeDocs={name:"setSize",category:"Set",syntax:["setSize(set)","setSize(set, unique)"],description:'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.',examples:["setSize([1, 2, 2, 4])","setSize([1, 2, 2, 4], true)"],seealso:["setUnion","setIntersect","setDifference"]},setSymDifferenceDocs={name:"setSymDifference",category:"Set",syntax:["setSymDifference(set1, set2)"],description:"Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])","setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setDifference"]},setUnionDocs={name:"setUnion",category:"Set",syntax:["setUnion(set1, set2)"],description:"Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setUnion([1, 2, 3, 4], [3, 4, 5, 6])","setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setIntersect","setDifference"]},erfDocs={name:"erf",category:"Special",syntax:["erf(x)"],description:"Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x",examples:["erf(0.2)","erf(-0.5)","erf(4)"],seealso:[]},madDocs={name:"mad",category:"Statistics",syntax:["mad(a, b, c, ...)","mad(A)"],description:"Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.",examples:["mad(10, 20, 30)","mad([1, 2, 3])"],seealso:["mean","median","std","abs"]},maxDocs={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dim)"],description:"Compute the maximum value of a list of values.",examples:["max(2, 3, 4, 1)","max([2, 3, 4, 1])","max([2, 5; 4, 3])","max([2, 5; 4, 3], 1)","max([2, 5; 4, 3], 2)","max(2.7, 7.1, -4.5, 2.0, 4.1)","min(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["mean","median","min","prod","std","sum","variance"]},meanDocs={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dim)"],description:"Compute the arithmetic mean of a list of values.",examples:["mean(2, 3, 4, 1)","mean([2, 3, 4, 1])","mean([2, 5; 4, 3])","mean([2, 5; 4, 3], 1)","mean([2, 5; 4, 3], 2)","mean([1.0, 2.7, 3.2, 4.0])"],seealso:["max","median","min","prod","std","sum","variance"]},medianDocs={name:"median",category:"Statistics",syntax:["median(a, b, c, ...)","median(A)"],description:"Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.",examples:["median(5, 2, 7)","median([3, -1, 5, 7])"],seealso:["max","mean","min","prod","std","sum","variance","quantileSeq"]},minDocs={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dim)"],description:"Compute the minimum value of a list of values.",examples:["min(2, 3, 4, 1)","min([2, 3, 4, 1])","min([2, 5; 4, 3])","min([2, 5; 4, 3], 1)","min([2, 5; 4, 3], 2)","min(2.7, 7.1, -4.5, 2.0, 4.1)","max(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["max","mean","median","prod","std","sum","variance"]},modeDocs={name:"mode",category:"Statistics",syntax:["mode(a, b, c, ...)","mode(A)","mode(A, a, b, B, c, ...)"],description:"Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.",examples:["mode(2, 1, 4, 3, 1)","mode([1, 2.7, 3.2, 4, 2.7])","mode(1, 4, 6, 1, 6)"],seealso:["max","mean","min","median","prod","std","sum","variance"]},prodDocs={name:"prod",category:"Statistics",syntax:["prod(a, b, c, ...)","prod(A)"],description:"Compute the product of all values.",examples:["prod(2, 3, 4)","prod([2, 3, 4])","prod([2, 5; 4, 3])"],seealso:["max","mean","min","median","min","std","sum","variance"]},quantileSeqDocs={name:"quantileSeq",category:"Statistics",syntax:["quantileSeq(A, prob[, sorted])","quantileSeq(A, [prob1, prob2, ...][, sorted])","quantileSeq(A, N[, sorted])"],description:"Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probablity are: Number, BigNumber. \n\nIn case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.",examples:["quantileSeq([3, -1, 5, 7], 0.5)","quantileSeq([3, -1, 5, 7], [1/3, 2/3])","quantileSeq([3, -1, 5, 7], 2)","quantileSeq([-1, 3, 5, 7], 0.5, true)"],seealso:["mean","median","min","max","prod","std","sum","variance"]},stdDocs={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, normalization)"],description:'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["std(2, 4, 6)","std([2, 4, 6, 8])",'std([2, 4, 6, 8], "uncorrected")','std([2, 4, 6, 8], "biased")',"std([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","prod","sum","variance"]},cumSumDocs={name:"cumsum",category:"Statistics",syntax:["cumsum(a, b, c, ...)","cumsum(A)"],description:"Compute the cumulative sum of all values.",examples:["cumsum(2, 3, 4, 1)","cumsum([2, 3, 4, 1])","cumsum([1, 2; 3, 4])","cumsum([1, 2; 3, 4], 1)","cumsum([1, 2; 3, 4], 2)"],seealso:["max","mean","median","min","prod","std","sum","variance"]},sumDocs={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)"],description:"Compute the sum of all values.",examples:["sum(2, 3, 4, 1)","sum([2, 3, 4, 1])","sum([2, 5; 4, 3])"],seealso:["max","mean","median","min","prod","std","sum","variance"]},varianceDocs={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, normalization)"],description:'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["variance(2, 4, 6)","variance([2, 4, 6, 8])",'variance([2, 4, 6, 8], "uncorrected")','variance([2, 4, 6, 8], "biased")',"variance([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","std","sum"]},acosDocs={name:"acos",category:"Trigonometry",syntax:["acos(x)"],description:"Compute the inverse cosine of a value in radians.",examples:["acos(0.5)","acos(cos(2.3))"],seealso:["cos","atan","asin"]},acoshDocs={name:"acosh",category:"Trigonometry",syntax:["acosh(x)"],description:"Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.",examples:["acosh(1.5)"],seealso:["cosh","asinh","atanh"]},acotDocs={name:"acot",category:"Trigonometry",syntax:["acot(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acot(0.5)","acot(cot(0.5))","acot(2)"],seealso:["cot","atan"]},acothDocs={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.",examples:["acoth(2)","acoth(0.5)"],seealso:["acsch","asech"]},acscDocs={name:"acsc",category:"Trigonometry",syntax:["acsc(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acsc(2)","acsc(csc(0.5))","acsc(0.5)"],seealso:["csc","asin","asec"]},acschDocs={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]},asecDocs={name:"asec",category:"Trigonometry",syntax:["asec(x)"],description:"Calculate the inverse secant of a value.",examples:["asec(0.5)","asec(sec(0.5))","asec(2)"],seealso:["acos","acot","acsc"]},asechDocs={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]},asinDocs={name:"asin",category:"Trigonometry",syntax:["asin(x)"],description:"Compute the inverse sine of a value in radians.",examples:["asin(0.5)","asin(sin(0.5))"],seealso:["sin","acos","atan"]},asinhDocs={name:"asinh",category:"Trigonometry",syntax:["asinh(x)"],description:"Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.",examples:["asinh(0.5)"],seealso:["acosh","atanh"]},atanDocs={name:"atan",category:"Trigonometry",syntax:["atan(x)"],description:"Compute the inverse tangent of a value in radians.",examples:["atan(0.5)","atan(tan(0.5))"],seealso:["tan","acos","asin"]},atan2Docs={name:"atan2",category:"Trigonometry",syntax:["atan2(y, x)"],description:"Computes the principal value of the arc tangent of y/x in radians.",examples:["atan2(2, 2) / pi","angle = 60 deg in rad","x = cos(angle)","y = sin(angle)","atan2(y, x)"],seealso:["sin","cos","tan"]},atanhDocs={name:"atanh",category:"Trigonometry",syntax:["atanh(x)"],description:"Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.",examples:["atanh(0.5)"],seealso:["acosh","asinh"]},cosDocs={name:"cos",category:"Trigonometry",syntax:["cos(x)"],description:"Compute the cosine of x in radians.",examples:["cos(2)","cos(pi / 4) ^ 2","cos(180 deg)","cos(60 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["acos","sin","tan"]},coshDocs={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]},cotDocs={name:"cot",category:"Trigonometry",syntax:["cot(x)"],description:"Compute the cotangent of x in radians. Defined as 1/tan(x)",examples:["cot(2)","1 / tan(2)"],seealso:["sec","csc","tan"]},cothDocs={name:"coth",category:"Trigonometry",syntax:["coth(x)"],description:"Compute the hyperbolic cotangent of x in radians.",examples:["coth(2)","1 / tanh(2)"],seealso:["sech","csch","tanh"]},cscDocs={name:"csc",category:"Trigonometry",syntax:["csc(x)"],description:"Compute the cosecant of x in radians. Defined as 1/sin(x)",examples:["csc(2)","1 / sin(2)"],seealso:["sec","cot","sin"]},cschDocs={name:"csch",category:"Trigonometry",syntax:["csch(x)"],description:"Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)",examples:["csch(2)","1 / sinh(2)"],seealso:["sech","coth","sinh"]},secDocs={name:"sec",category:"Trigonometry",syntax:["sec(x)"],description:"Compute the secant of x in radians. Defined as 1/cos(x)",examples:["sec(2)","1 / cos(2)"],seealso:["cot","csc","cos"]},sechDocs={name:"sech",category:"Trigonometry",syntax:["sech(x)"],description:"Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)",examples:["sech(2)","1 / cosh(2)"],seealso:["coth","csch","cosh"]},sinDocs={name:"sin",category:"Trigonometry",syntax:["sin(x)"],description:"Compute the sine of x in radians.",examples:["sin(2)","sin(pi / 4) ^ 2","sin(90 deg)","sin(30 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["asin","cos","tan"]},sinhDocs={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]},tanDocs={name:"tan",category:"Trigonometry",syntax:["tan(x)"],description:"Compute the tangent of x in radians.",examples:["tan(0.5)","sin(0.5) / cos(0.5)","tan(pi / 4)","tan(45 deg)"],seealso:["atan","sin","cos"]},tanhDocs={name:"tanh",category:"Trigonometry",syntax:["tanh(x)"],description:"Compute the hyperbolic tangent of x in radians.",examples:["tanh(0.5)","sinh(0.5) / cosh(0.5)"],seealso:["sinh","cosh"]},toDocs={name:"to",category:"Units",syntax:["x to unit","to(x, unit)"],description:"Change the unit of a value.",examples:["5 inch to cm","3.2kg to g","16 bytes in bits"],seealso:[]},binDocs={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]},cloneDocs={name:"clone",category:"Utils",syntax:["clone(x)"],description:"Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices",examples:["clone(3.5)","clone(2 - 4i)","clone(45 deg)","clone([1, 2; 3, 4])",'clone("hello world")'],seealso:[]},formatDocs={name:"format",category:"Utils",syntax:["format(value)","format(value, precision)"],description:"Format a value of any type as string.",examples:["format(2.3)","format(3 - 4i)","format([])","format(pi, 3)"],seealso:["print"]},hasNumericValueDocs={name:"hasNumericValue",category:"Utils",syntax:["hasNumericValue(x)"],description:"Test whether a value is an numeric value. In case of a string, true is returned if the string contains a numeric value.",examples:["hasNumericValue(2)",'hasNumericValue("2")','isNumeric("2")',"hasNumericValue(0)","hasNumericValue(bignumber(500))","hasNumericValue(fraction(0.125))","hasNumericValue(2 + 3i)",'hasNumericValue([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","isNumeric"]},hexDocs={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]},isIntegerDocs={name:"isInteger",category:"Utils",syntax:["isInteger(x)"],description:"Test whether a value is an integer number.",examples:["isInteger(2)","isInteger(3.5)","isInteger([3, 0.5, -2])"],seealso:["isNegative","isNumeric","isPositive","isZero"]},isNaNDocs={name:"isNaN",category:"Utils",syntax:["isNaN(x)"],description:"Test whether a value is NaN (not a number)",examples:["isNaN(2)","isNaN(0 / 0)","isNaN(NaN)","isNaN(Infinity)"],seealso:["isNegative","isNumeric","isPositive","isZero"]},isNegativeDocs={name:"isNegative",category:"Utils",syntax:["isNegative(x)"],description:"Test whether a value is negative: smaller than zero.",examples:["isNegative(2)","isNegative(0)","isNegative(-4)","isNegative([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isPositive","isZero"]},isNumericDocs={name:"isNumeric",category:"Utils",syntax:["isNumeric(x)"],description:"Test whether a value is a numeric value. Returns true when the input is a number, BigNumber, Fraction, or boolean.",examples:["isNumeric(2)",'isNumeric("2")','hasNumericValue("2")',"isNumeric(0)","isNumeric(bignumber(500))","isNumeric(fraction(0.125))","isNumeric(2 + 3i)",'isNumeric([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","hasNumericValue"]},isPositiveDocs={name:"isPositive",category:"Utils",syntax:["isPositive(x)"],description:"Test whether a value is positive: larger than zero.",examples:["isPositive(2)","isPositive(0)","isPositive(-4)","isPositive([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},isPrimeDocs={name:"isPrime",category:"Utils",syntax:["isPrime(x)"],description:"Test whether a value is prime: has no divisors other than itself and one.",examples:["isPrime(3)","isPrime(-2)","isPrime([2, 17, 100])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},isZeroDocs={name:"isZero",category:"Utils",syntax:["isZero(x)"],description:"Test whether a value is zero.",examples:["isZero(2)","isZero(0)","isZero(-4)","isZero([3, 0, -2, 0])"],seealso:["isInteger","isNumeric","isNegative","isPositive"]},numericDocs={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "BigNumber")','numeric("4", "Fraction)','numeric(4, "Fraction")','numeric(fraction(2, 5), "number)'],seealso:["number","fraction","bignumber","string","format"]},octDocs={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]},printDocs={name:"print",category:"Utils",syntax:["print(template, values)","print(template, values, precision)"],description:"Interpolate values into a string template.",examples:['print("Lucy is $age years old", {age: 5})','print("The value of pi is $pi", {pi: pi}, 3)','print("Hello, $user.name!", {user: {name: "John"}})','print("Values: $0, $1, $2", [6, 9, 4])'],seealso:["format"]},typeOfDocs={name:"typeOf",category:"Utils",syntax:["typeOf(x)"],description:"Get the type of a variable.",examples:["typeOf(3.5)","typeOf(2 - 4i)","typeOf(45 deg)",'typeOf("hello world")'],seealso:["getMatrixDataType"]},embeddedDocs={bignumber:bignumberDocs,boolean:booleanDocs,complex:complexDocs,createUnit:createUnitDocs,fraction:fractionDocs,index:indexDocs,matrix:matrixDocs,number:numberDocs,sparse:sparseDocs,splitUnit:splitUnitDocs,string:stringDocs,unit:unitDocs,e:eDocs,E:eDocs,false:falseDocs,i:iDocs,Infinity:InfinityDocs,LN2:LN2Docs,LN10:LN10Docs,LOG2E:LOG2EDocs,LOG10E:LOG10EDocs,NaN:NaNDocs,null:nullDocs,pi:piDocs,PI:piDocs,phi:phiDocs,SQRT1_2:SQRT12Docs,SQRT2:SQRT2Docs,tau:tauDocs,true:trueDocs,version:versionDocs,speedOfLight:{description:"Speed of light in vacuum",examples:["speedOfLight"]},gravitationConstant:{description:"Newtonian constant of gravitation",examples:["gravitationConstant"]},planckConstant:{description:"Planck constant",examples:["planckConstant"]},reducedPlanckConstant:{description:"Reduced Planck constant",examples:["reducedPlanckConstant"]},magneticConstant:{description:"Magnetic constant (vacuum permeability)",examples:["magneticConstant"]},electricConstant:{description:"Electric constant (vacuum permeability)",examples:["electricConstant"]},vacuumImpedance:{description:"Characteristic impedance of vacuum",examples:["vacuumImpedance"]},coulomb:{description:"Coulomb's constant",examples:["coulomb"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Borh magneton",examples:["bohrMagneton"]},conductanceQuantum:{description:"Conductance quantum",examples:["conductanceQuantum"]},inverseConductanceQuantum:{description:"Inverse conductance quantum",examples:["inverseConductanceQuantum"]},magneticFluxQuantum:{description:"Magnetic flux quantum",examples:["magneticFluxQuantum"]},nuclearMagneton:{description:"Nuclear magneton",examples:["nuclearMagneton"]},klitzing:{description:"Von Klitzing constant",examples:["klitzing"]},bohrRadius:{description:"Borh radius",examples:["bohrRadius"]},classicalElectronRadius:{description:"Classical electron radius",examples:["classicalElectronRadius"]},electronMass:{description:"Electron mass",examples:["electronMass"]},fermiCoupling:{description:"Fermi coupling constant",examples:["fermiCoupling"]},fineStructure:{description:"Fine-structure constant",examples:["fineStructure"]},hartreeEnergy:{description:"Hartree energy",examples:["hartreeEnergy"]},protonMass:{description:"Proton mass",examples:["protonMass"]},deuteronMass:{description:"Deuteron Mass",examples:["deuteronMass"]},neutronMass:{description:"Neutron mass",examples:["neutronMass"]},quantumOfCirculation:{description:"Quantum of circulation",examples:["quantumOfCirculation"]},rydberg:{description:"Rydberg constant",examples:["rydberg"]},thomsonCrossSection:{description:"Thomson cross section",examples:["thomsonCrossSection"]},weakMixingAngle:{description:"Weak mixing angle",examples:["weakMixingAngle"]},efimovFactor:{description:"Efimov factor",examples:["efimovFactor"]},atomicMass:{description:"Atomic mass constant",examples:["atomicMass"]},avogadro:{description:"Avogadro's number",examples:["avogadro"]},boltzmann:{description:"Boltzmann constant",examples:["boltzmann"]},faraday:{description:"Faraday constant",examples:["faraday"]},firstRadiation:{description:"First radiation constant",examples:["firstRadiation"]},loschmidt:{description:"Loschmidt constant at T=273.15 K and p=101.325 kPa",examples:["loschmidt"]},gasConstant:{description:"Gas constant",examples:["gasConstant"]},molarPlanckConstant:{description:"Molar Planck constant",examples:["molarPlanckConstant"]},molarVolume:{description:"Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa",examples:["molarVolume"]},sackurTetrode:{description:"Sackur-Tetrode constant at T=1 K and p=101.325 kPa",examples:["sackurTetrode"]},secondRadiation:{description:"Second radiation constant",examples:["secondRadiation"]},stefanBoltzmann:{description:"Stefan-Boltzmann constant",examples:["stefanBoltzmann"]},wienDisplacement:{description:"Wien displacement law constant",examples:["wienDisplacement"]},molarMass:{description:"Molar mass constant",examples:["molarMass"]},molarMassC12:{description:"Molar mass constant of carbon-12",examples:["molarMassC12"]},gravity:{description:"Standard acceleration of gravity (standard acceleration of free-fall on Earth)",examples:["gravity"]},planckLength:{description:"Planck length",examples:["planckLength"]},planckMass:{description:"Planck mass",examples:["planckMass"]},planckTime:{description:"Planck time",examples:["planckTime"]},planckCharge:{description:"Planck charge",examples:["planckCharge"]},planckTemperature:{description:"Planck temperature",examples:["planckTemperature"]},derivative:derivativeDocs,lsolve:lsolveDocs,lsolveAll:lsolveAllDocs,lup:lupDocs,lusolve:lusolveDocs,leafCount:leafCountDocs,resolve:resolveDocs,simplify:simplifyDocs,simplifyCore:simplifyCoreDocs,symbolicEqual:symbolicEqualDocs,rationalize:rationalizeDocs,slu:sluDocs,usolve:usolveDocs,usolveAll:usolveAllDocs,qr:qrDocs,abs:absDocs,add:addDocs,cbrt:cbrtDocs,ceil:ceilDocs,cube:cubeDocs,divide:divideDocs,dotDivide:dotDivideDocs,dotMultiply:dotMultiplyDocs,dotPow:dotPowDocs,exp:expDocs,expm:expmDocs,expm1:expm1Docs,fix:fixDocs,floor:floorDocs,gcd:gcdDocs,hypot:hypotDocs,lcm:lcmDocs,log:logDocs,log2:log2Docs,log1p:log1pDocs,log10:log10Docs,mod:modDocs,multiply:multiplyDocs,norm:normDocs,nthRoot:nthRootDocs,nthRoots:nthRootsDocs,pow:powDocs,round:roundDocs,sign:signDocs,sqrt:sqrtDocs,sqrtm:sqrtmDocs,square:squareDocs,subtract:subtractDocs,unaryMinus:unaryMinusDocs,unaryPlus:unaryPlusDocs,xgcd:xgcdDocs,invmod:invmodDocs,bitAnd:bitAndDocs,bitNot:bitNotDocs,bitOr:bitOrDocs,bitXor:bitXorDocs,leftShift:leftShiftDocs,rightArithShift:rightArithShiftDocs,rightLogShift:rightLogShiftDocs,bellNumbers:bellNumbersDocs,catalan:catalanDocs,composition:compositionDocs,stirlingS2:stirlingS2Docs,config:configDocs,import:importDocs,typed:typedDocs,arg:argDocs,conj:conjDocs,re:reDocs,im:imDocs,evaluate:evaluateDocs,help:helpDocs,distance:distanceDocs,intersect:intersectDocs,and:andDocs,not:notDocs,or:orDocs,xor:xorDocs,concat:concatDocs,count:countDocs,cross:crossDocs,column:columnDocs,ctranspose:ctransposeDocs,det:detDocs,diag:diagDocs,diff:diffDocs,dot:dotDocs,getMatrixDataType:getMatrixDataTypeDocs,identity:identityDocs,filter:filterDocs,flatten:flattenDocs,forEach:forEachDocs,inv:invDocs,pinv:pinvDocs,eigs:eigsDocs,kron:kronDocs,matrixFromFunction:matrixFromFunctionDocs,matrixFromRows:matrixFromRowsDocs,matrixFromColumns:matrixFromColumnsDocs,map:mapDocs,ones:onesDocs,partitionSelect:partitionSelectDocs,range:rangeDocs,resize:resizeDocs,reshape:reshapeDocs,rotate:rotateDocs,rotationMatrix:rotationMatrixDocs,row:rowDocs,size:sizeDocs,sort:sortDocs,squeeze:squeezeDocs,subset:subsetDocs,trace:traceDocs,transpose:transposeDocs,zeros:zerosDocs,fft:fftDocs,ifft:ifftDocs,combinations:combinationsDocs,combinationsWithRep:combinationsWithRepDocs,factorial:factorialDocs,gamma:gammaDocs,kldivergence:kldivergenceDocs,lgamma:lgammaDocs,multinomial:multinomialDocs,permutations:permutationsDocs,pickRandom:pickRandomDocs,random:randomDocs,randomInt:randomIntDocs,compare:compareDocs,compareNatural:compareNaturalDocs,compareText:compareTextDocs,deepEqual:deepEqualDocs,equal:equalDocs,equalText:equalTextDocs,larger:largerDocs,largerEq:largerEqDocs,smaller:smallerDocs,smallerEq:smallerEqDocs,unequal:unequalDocs,setCartesian:setCartesianDocs,setDifference:setDifferenceDocs,setDistinct:setDistinctDocs,setIntersect:setIntersectDocs,setIsSubset:setIsSubsetDocs,setMultiplicity:setMultiplicityDocs,setPowerset:setPowersetDocs,setSize:setSizeDocs,setSymDifference:setSymDifferenceDocs,setUnion:setUnionDocs,erf:erfDocs,cumsum:cumSumDocs,mad:madDocs,max:maxDocs,mean:meanDocs,median:medianDocs,min:minDocs,mode:modeDocs,prod:prodDocs,quantileSeq:quantileSeqDocs,std:stdDocs,sum:sumDocs,variance:varianceDocs,acos:acosDocs,acosh:acoshDocs,acot:acotDocs,acoth:acothDocs,acsc:acscDocs,acsch:acschDocs,asec:asecDocs,asech:asechDocs,asin:asinDocs,asinh:asinhDocs,atan:atanDocs,atanh:atanhDocs,atan2:atan2Docs,cos:cosDocs,cosh:coshDocs,cot:cotDocs,coth:cothDocs,csc:cscDocs,csch:cschDocs,sec:secDocs,sech:sechDocs,sin:sinDocs,sinh:sinhDocs,tan:tanDocs,tanh:tanhDocs,to:toDocs,clone:cloneDocs,format:formatDocs,bin:binDocs,oct:octDocs,hex:hexDocs,isNaN:isNaNDocs,isInteger:isIntegerDocs,isNegative:isNegativeDocs,isNumeric:isNumericDocs,hasNumericValue:hasNumericValueDocs,isPositive:isPositiveDocs,isPrime:isPrimeDocs,isZero:isZeroDocs,print:printDocs,typeOf:typeOfDocs,numeric:numericDocs},name$_="help",dependencies$_=["typed","mathWithTransform","Help"],createHelp=factory(name$_,dependencies$_,(e=>{var{typed:t,mathWithTransform:n,Help:r}=e;return t(name$_,{any:function(e){var t,a=e;if("string"!=typeof e)for(t in n)if(hasOwnProperty$2(n,t)&&e===n[t]){a=t;break}var i=getSafeProperty(embeddedDocs,a);if(!i){var s="function"==typeof a?a.name:a;throw new Error('No documentation found on "'+s+'"')}return new r(i)}})})),name$Z="chain",dependencies$Z=["typed","Chain"],createChain=factory(name$Z,dependencies$Z,(e=>{var{typed:t,Chain:n}=e;return t(name$Z,{"":function(){return new n},any:function(e){return new n(e)}})})),name$Y="det",dependencies$Y=["typed","matrix","subtract","multiply","divideScalar","isZero","unaryMinus"],createDet=factory(name$Y,dependencies$Y,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a,divideScalar:i,isZero:s,unaryMinus:o}=e;return t(name$Y,{any:function(e){return clone$3(e)},"Array | Matrix":function(e){var t;switch((t=isMatrix(e)?e.size():Array.isArray(e)?(e=n(e)).size():[]).length){case 0:return clone$3(e);case 1:if(1===t[0])return clone$3(e.valueOf()[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var l=t[0];if(l===t[1])return function(e,t,n){if(1===t)return clone$3(e[0][0]);if(2===t)return r(a(e[0][0],e[1][1]),a(e[1][0],e[0][1]));for(var l=!1,u=new Array(t).fill(0).map(((e,t)=>t)),c=0;c{var{typed:t,matrix:n,divideScalar:r,addScalar:a,multiply:i,unaryMinus:s,det:o,identity:l,abs:u}=e;return t(name$X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return isMatrix(e)?n([r(1,e.valueOf()[0])]):[r(1,e[0])];throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0],i=t[1];if(a===i)return isMatrix(e)?n(c(e.valueOf(),a,i),e.storage()):c(e,a,i);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return r(1,e)}});function c(e,t,n){var c,p,d,m,h;if(1===t){if(0===(m=e[0][0]))throw Error("Cannot calculate inverse, determinant is zero");return[[r(1,m)]]}if(2===t){var f=o(e);if(0===f)throw Error("Cannot calculate inverse, determinant is zero");return[[r(e[1][1],f),r(s(e[0][1]),f)],[r(s(e[1][0]),f),r(e[0][0],f)]]}var y=e.concat();for(c=0;cv&&(v=u(y[c][b]),N=c),c++;if(0===v)throw Error("Cannot calculate inverse, determinant is zero");(c=N)!==b&&(h=y[b],y[b]=y[c],y[c]=h,h=g[b],g[b]=g[c],g[c]=h);var T=y[b],C=g[b];for(c=0;c{var{typed:t,matrix:n,inv:r,deepEqual:a,equal:i,dotDivide:s,dot:o,ctranspose:l,divideScalar:u,multiply:c,add:p,Complex:d}=e;return t(name$W,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:return f(e)?l(e):1===t[0]?r(e):s(l(e),o(e,e));case 2:if(f(e))return l(e);var a=t[0],i=t[1];if(a===i)try{return r(e)}catch(e){if(!(e instanceof Error&&e.message.match(/Cannot calculate inverse, determinant is zero/)))throw e}return isMatrix(e)?n(m(e.valueOf(),a,i),e.storage()):m(e,a,i);default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return i(e,0)?clone$3(e):u(1,e)}});function m(e,t,n){var{C:a,F:i}=function(e,t,n){var r=function(e,t,n){for(var r=clone$3(e),a=0,i=0;ie.filter(((e,n)=>n!h(o(r[t],r[t]))));return{C:a,F:i}}(e,t,n),u=c(r(c(l(a),a)),l(a)),d=c(l(i),r(c(i,l(i))));return c(d,u)}function h(e){return i(p(e,d(1,1)),p(0,d(1,1)))}function f(e){return a(p(e,d(1,1)),p(c(e,0),d(1,1)))}}));function createComplexEigs(e){var{addScalar:t,subtract:n,flatten:r,multiply:a,multiplyScalar:i,divideScalar:s,sqrt:o,abs:l,bignumber:u,diag:c,inv:p,qr:d,usolve:m,usolveAll:h,equal:f,complex:y,larger:g,smaller:b,matrixFromColumns:v,dot:N}=e;function T(e,r,a,s){var l=t(e,s),u=n(i(e,s),i(r,a)),c=i(l,.5),p=i(o(n(i(l,l),i(4,u))),.5);return[t(c,p),n(c,p)]}function C(e,t,r,a,i,s,o,c){var p="BigNumber"===c,d="Complex"===c,m=p?u(0):d?y(0):0,h=p?u(1):d?y(1):1;if(b(l(r),o))return[[h,m],[m,h]];if(g(l(n(i,s)),o))return[[n(i,a),n(s,a)],[r,r]];var f=n(e,i),v=n(t,i),N=n(r,i),T=n(a,i);return b(l(v),o)?[[f,h],[N,m]]:[[v,m],[T,h]]}function A(e,t){for(var n=0;n=5)return null;for(o=0;;){var l=m(e,i);if(b(E(w(i,[l])),r))break;if(++o>=10)return null;i=D(l)}return i}function S(e,t,n){var r="BigNumber"===n,a="Complex"===n,i=Array(e).fill(0).map((e=>2*Math.random()-1));return r&&(i=i.map((e=>u(e)))),a&&(i=i.map((e=>y(e)))),D(i=w(i,t),n)}function w(e,t){for(var r of t)e=n(e,a(s(N(r,e),N(r,r)),r));return e}function E(e){return l(o(N(e,e)))}function D(e,t){var n="Complex"===t,r="BigNumber"===t?u(1):n?y(1):1;return a(s(r,E(e)),e)}return function(e,o,m,N,S){void 0===S&&(S=!0);var w=function(e,n,r,a,o){var p,d="BigNumber"===a,m="Complex"===a,h=d?u(0):0,v=d?u(1):m?y(1):1,N=d?u(1):1,T=d?u(10):2,C=i(T,T);o&&(p=Array(n).fill(v));for(var A=!1;!A;){A=!0;for(var V=0;V1&&(x=c(Array(v-1).fill(h)))),v-=1,f.pop();for(var I=0;I2&&(x=c(Array(v-2).fill(h)))),v-=2,f.pop(),f.pop();for(var _=0;_+n(l(e),l(t)))),S>100){var M=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+g.join(", "));throw M.values=g,M.vectors=[],M}var P=o?a(V,function(e,t){for(var n=[],r=0;ra(f,e))),E.push(...c.map((e=>r(e))))},M=0;M2&&void 0!==arguments[2]?arguments[2]:t.epsilon,i=arguments.length>3?arguments[3]:void 0;if("number"===i)return function(e,t){for(var n,r=e.length,a=Math.abs(t/r),i=new Array(r),s=0;s=Math.abs(a);){var l=o[0][0],u=o[0][1];e=b(e,n=m(e[l][l],e[u][u],e[l][u]),l,u),i=f(i,n,l,u),o=v(e)}for(var c=C(r,0),p=0;p=a(i);){var u=l[0][0],c=l[0][1];e=g(e,n=h(e[u][u],e[c][c],e[u][c]),u,c),s=y(s,n,u,c),l=N(e)}for(var p=C(r,0),d=0;d{var{config:t,typed:n,matrix:r,addScalar:a,subtract:i,equal:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:p,divideScalar:d,inv:m,bignumber:h,multiply:f,add:y,larger:g,column:b,flatten:v,number:N,complex:T,sqrt:C,diag:A,qr:V,usolve:x,usolveAll:S,im:w,re:E,smaller:D,matrixFromColumns:O,dot:I}=e,R=createRealSymmetric({config:t,addScalar:a,subtract:i,column:b,flatten:v,equal:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:p,inv:m,bignumber:h,complex:T,multiply:f,add:y}),_=createComplexEigs({config:t,addScalar:a,subtract:i,multiply:f,multiplyScalar:p,flatten:v,divideScalar:d,sqrt:C,abs:o,bignumber:h,diag:A,qr:V,inv:m,usolve:x,usolveAll:S,equal:s,complex:T,larger:g,smaller:D,matrixFromColumns:O,dot:I});return n("eigs",{Array:function(e){return M(r(e))},"Array, number|BigNumber":function(e,t){return M(r(e),t)},Matrix:function(e){var{values:t,vectors:n}=M(e);return{values:r(t),vectors:r(n)}},"Matrix, number|BigNumber":function(e,t){var{values:n,vectors:a}=M(e,t);return{values:r(n),vectors:r(a)}}});function M(e,n){void 0===n&&(n=t.epsilon);var r=e.size();if(2!==r.length||r[0]!==r[1])throw new RangeError("Matrix must be square (size: "+format$1(r)+")");var a=e.toArray(),s=r[0];if(function(e,t,n){for(var r=0;r{var{typed:t,abs:n,add:r,identity:a,inv:i,multiply:s}=e;return t(name$U,{Matrix:function(e){var t=e.size();if(2!==t.length||t[0]!==t[1])throw new RangeError("Matrix must be square (size: "+format$1(t)+")");for(var l=t[0],u=function(e){for(var t=e.size()[0],r=0,a=0;a1&&(g=s(g,m),b=-b),h=r(h,s(y=y*(p-v+1)/((2*p-v+1)*v),g)),f=r(f,s(y*b,g));for(var N=s(i(f),h),T=0;T{var{typed:t,abs:n,add:r,multiply:a,sqrt:i,subtract:s,inv:o,size:l,max:u,identity:c}=e,p=1e-6;return t(name$T,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return i(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:if(t[0]===t[1])return function(e){var t,i=0,d=e,m=c(l(e));do{var h=d;if(d=a(.5,r(h,o(m))),m=a(.5,r(m,o(h))),(t=u(n(s(d,h))))>p&&++i>1e3)throw new Error("computing square root of matrix: iterative method could not converge")}while(t>p);return d}(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be at most two dimensional (size: "+format$1(t)+")")}}})})),name$S="divide",dependencies$S=["typed","matrix","multiply","equalScalar","divideScalar","inv"],createDivide=factory(name$S,dependencies$S,(e=>{var{typed:t,matrix:n,multiply:r,equalScalar:a,divideScalar:i,inv:s}=e,o=createAlgorithm11({typed:t,equalScalar:a}),l=createAlgorithm14({typed:t});return t("divide",extend$2({"Array | Matrix, Array | Matrix":function(e,t){return r(e,s(t))},"DenseMatrix, any":function(e,t){return l(e,t,i,!1)},"SparseMatrix, any":function(e,t){return o(e,t,i,!1)},"Array, any":function(e,t){return l(n(e),t,i,!1).valueOf()},"any, Array | Matrix":function(e,t){return r(e,s(t))}},i.signatures))})),name$R="distance",dependencies$R=["typed","addScalar","subtract","divideScalar","multiplyScalar","unaryMinus","sqrt","abs"],createDistance=factory(name$R,dependencies$R,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,unaryMinus:s,sqrt:o,abs:l}=e;return t(name$R,{"Array, Array, Array":function(e,t,n){if(2===e.length&&2===t.length&&2===n.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!c(t))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!c(n))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");var o=i(r(n[1],n[0]),r(t[1],t[0])),l=a(a(o,o),t[0]),u=s(a(o,t[0])),p=e[1];return f(e[0],e[1],l,u,p)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(e,t,n){if(2===Object.keys(e).length&&2===Object.keys(t).length&&2===Object.keys(n).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!c(t))throw new TypeError("Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers");if(!c(n))throw new TypeError("Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"lineOnePtX"in t&&"lineOnePtY"in t&&"lineTwoPtX"in n&&"lineTwoPtY"in n){var o=i(r(n.lineTwoPtY,n.lineTwoPtX),r(t.lineOnePtY,t.lineOnePtX)),l=a(a(o,o),t.lineOnePtX),u=s(a(o,t.lineOnePtX)),p=e.pointX;return f(e.pointX,e.pointY,l,u,p)}throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(e,t){if(2===e.length&&3===t.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!p(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return f(e[0],e[1],t[0],t[1],t[2])}if(3===e.length&&6===t.length){if(!p(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!m(t))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return y(e[0],e[1],e[2],t[0],t[1],t[2],t[3],t[4],t[5])}if(e.length===t.length&&e.length>0){if(!d(e))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!d(t))throw new TypeError("All values of an array should be numbers or BigNumbers");return g(e,t)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(e,t){if(2===Object.keys(e).length&&3===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"xCoeffLine"in t&&"yCoeffLine"in t&&"constant"in t)return f(e.pointX,e.pointY,t.xCoeffLine,t.yCoeffLine,t.constant);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&6===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!m(t))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"x0"in t&&"y0"in t&&"z0"in t&&"a"in t&&"b"in t&&"c"in t)return y(e.pointX,e.pointY,e.pointZ,t.x0,t.y0,t.z0,t.a,t.b,t.c);throw new TypeError("Key names do not match")}if(2===Object.keys(e).length&&2===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!c(t))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointTwoX"in t&&"pointTwoY"in t)return g([e.pointOneX,e.pointOneY],[t.pointTwoX,t.pointTwoY]);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&3===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointOneZ"in e&&"pointTwoX"in t&&"pointTwoY"in t&&"pointTwoZ"in t)return g([e.pointOneX,e.pointOneY,e.pointOneZ],[t.pointTwoX,t.pointTwoY,t.pointTwoZ]);throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},Array:function(e){if(!function(e){if(2===e[0].length&&u(e[0][0])&&u(e[0][1])){if(e.some((e=>2!==e.length||!u(e[0])||!u(e[1]))))return!1}else{if(!(3===e[0].length&&u(e[0][0])&&u(e[0][1])&&u(e[0][2])))return!1;if(e.some((e=>3!==e.length||!u(e[0])||!u(e[1])||!u(e[2]))))return!1}return!0}(e))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return function(e){for(var t=[],n=[],r=[],a=0;a{var{typed:t,config:n,abs:r,add:a,addScalar:i,matrix:s,multiply:o,multiplyScalar:l,divideScalar:u,subtract:c,smaller:p,equalScalar:d,flatten:m,isZero:h,isNumeric:f}=e;return t("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":g,"Matrix, Matrix, Matrix":function(e,t,n){var r=y(e.valueOf(),t.valueOf(),n.valueOf());return null===r?null:s(r)},"Matrix, Matrix, Matrix, Matrix":function(e,t,n,r){var a=g(e.valueOf(),t.valueOf(),n.valueOf(),r.valueOf());return null===a?null:s(a)}});function y(e,t,n){if(e=b(e),t=b(t),n=b(n),!N(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!N(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!function(e){return 4===e.length&&f(e[0])&&f(e[1])&&f(e[2])&&f(e[3])}(n))throw new TypeError("Array with 4 numbers expected as third argument");return function(e,t,n,r,a,s,o,p,d,m){var h=l(e,o),f=l(r,o),y=l(t,p),g=l(a,p),b=l(n,d),v=l(s,d),N=c(c(c(m,h),y),b),T=c(c(c(i(i(f,g),v),h),y),b),C=u(N,T);return[i(e,l(C,c(r,e))),i(t,l(C,c(a,t))),i(n,l(C,c(s,n)))]}(e[0],e[1],e[2],t[0],t[1],t[2],n[0],n[1],n[2],n[3])}function g(e,t,s,m){if(e=b(e),t=b(t),s=b(s),m=b(m),2===e.length){if(!v(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!v(t))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!v(s))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!v(m))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return function(e,t,s,d){var m=e,f=s,y=c(m,t),g=c(f,d),b=c(l(y[0],g[1]),l(g[0],y[1]));if(h(b))return null;if(p(r(b),n.epsilon))return null;var v=l(g[0],m[1]),N=l(g[1],m[0]),T=l(g[0],f[1]),C=l(g[1],f[0]),A=u(i(c(c(v,N),T),C),b);return a(o(y,A),m)}(e,t,s,m)}if(3===e.length){if(!N(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!N(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!N(s))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!N(m))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return function(e,t,n,r,a,s,o,p,m,f,y,g){var b=T(e,o,f,o,t,p,y,p,n,m,g,m),v=T(f,o,r,e,y,p,a,t,g,m,s,n),N=T(e,o,r,e,t,p,a,t,n,m,s,n),C=T(f,o,f,o,y,p,y,p,g,m,g,m),A=T(r,e,r,e,a,t,a,t,s,n,s,n),V=c(l(b,v),l(N,C)),x=c(l(A,C),l(v,v));if(h(x))return null;var S=u(V,x),w=u(i(b,l(S,v)),C),E=i(e,l(S,c(r,e))),D=i(t,l(S,c(a,t))),O=i(n,l(S,c(s,n))),I=i(o,l(w,c(f,o))),R=i(p,l(w,c(y,p))),_=i(m,l(w,c(g,m)));return d(E,I)&&d(D,R)&&d(O,_)?[E,D,O]:null}(e[0],e[1],e[2],t[0],t[1],t[2],s[0],s[1],s[2],m[0],m[1],m[2])}throw new TypeError("Arrays with two or thee dimensional points expected")}function b(e){return 1===e.length?e[0]:e.length>1&&Array.isArray(e[0])&&e.every((e=>Array.isArray(e)&&1===e.length))?m(e):e}function v(e){return 2===e.length&&f(e[0])&&f(e[1])}function N(e){return 3===e.length&&f(e[0])&&f(e[1])&&f(e[2])}function T(e,t,n,r,a,s,o,u,p,d,m,h){var f=l(c(e,t),c(n,r)),y=l(c(a,s),c(o,u)),g=l(c(p,d),c(m,h));return i(i(f,y),g)}})),name$P="sum",dependencies$P=["typed","config","add","numeric"],createSum=factory(name$P,dependencies$P,(e=>{var{typed:t,config:n,add:r,numeric:a}=e;return t(name$P,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){try{return reduce$2(e,t,r)}catch(e){throw improveErrorMessage(e,"sum")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function sum");return i(e)}});function i(e){var t;return deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"sum",e)}})),void 0===t&&(t=a(0,n.number)),"string"==typeof t&&(t=a(t,n.number)),t}})),name$O="cumsum",dependencies$O=["typed","add","unaryPlus"],createCumSum=factory(name$O,dependencies$O,(e=>{var{typed:t,add:n,unaryPlus:r}=e;return t(name$O,{Array:a,Matrix:function(e){return e.create(a(e.valueOf()))},"Array, number | BigNumber":s,"Matrix, number | BigNumber":function(e,t){return e.create(s(e.valueOf(),t))},"...":function(e){if(containsCollections(e))throw new TypeError("All values expected to be scalar in function cumsum");return a(e)}});function a(e){try{return i(e)}catch(e){throw improveErrorMessage(e,name$O)}}function i(e){if(0===e.length)return[];for(var t=[r(e[0])],a=1;a=n.length)throw new IndexError(t,n.length);try{return o(e,t)}catch(e){throw improveErrorMessage(e,name$O)}}function o(e,t){var n,r,a;if(t<=0){var s=e[0][0];if(Array.isArray(s)){for(a=_switch$1(e),r=[],n=0;n{var{typed:t,add:n,divide:r}=e;return t(name$N,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":function(e,t){try{var a=reduce$2(e,t,n),i=Array.isArray(e)?arraySize(e):e.size();return r(a,i[t])}catch(e){throw improveErrorMessage(e,"mean")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function mean");return a(e)}});function a(e){var t,a=0;if(deepForEach(e,(function(e){try{t=void 0===t?e:n(t,e),a++}catch(t){throw improveErrorMessage(t,"mean",e)}})),0===a)throw new Error("Cannot calculate the mean of an empty array");return r(t,a)}})),name$M="median",dependencies$M=["typed","add","divide","compare","partitionSelect"],createMedian=factory(name$M,dependencies$M,(e=>{var{typed:t,add:n,divide:r,compare:a,partitionSelect:i}=e;function s(e){try{var t=(e=flatten$4(e.valueOf())).length;if(0===t)throw new Error("Cannot calculate median of an empty array");if(t%2==0){for(var n=t/2-1,r=i(e,n+1),s=e[n],u=0;u0&&(s=e[u]);return l(s,r)}var c=i(e,(t-1)/2);return o(c)}catch(e){throw improveErrorMessage(e,"median")}}var o=t({"number | BigNumber | Complex | Unit":function(e){return e}}),l=t({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(e,t){return r(n(e,t),2)}});return t(name$M,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("median(A, dim) is not yet supported")},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function median");return s(e)}})})),name$L="mad",dependencies$L=["typed","abs","map","median","subtract"],createMad=factory(name$L,dependencies$L,(e=>{var{typed:t,abs:n,map:r,median:a,subtract:i}=e;return t(name$L,{"Array | Matrix":s,"...":function(e){return s(e)}});function s(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var t=a(e);return a(r(e,(function(e){return n(i(e,t))})))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf("median")?new TypeError(e.message.replace("median","mad")):improveErrorMessage(e,"mad")}}})),DEFAULT_NORMALIZATION="unbiased",name$K="variance",dependencies$K=["typed","add","subtract","multiply","divide","apply","isNaN"],createVariance=factory(name$K,dependencies$K,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o}=e;return t(name$K,{"Array | Matrix":function(e){return l(e,DEFAULT_NORMALIZATION)},"Array | Matrix, string":l,"Array | Matrix, number | BigNumber":function(e,t){return u(e,t,DEFAULT_NORMALIZATION)},"Array | Matrix, number | BigNumber, string":u,"...":function(e){return l(e,DEFAULT_NORMALIZATION)}});function l(e,t){var s,l=0;if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(deepForEach(e,(function(e){try{s=void 0===s?e:n(s,e),l++}catch(t){throw improveErrorMessage(t,"variance",e)}})),0===l)throw new Error("Cannot calculate variance of an empty array");var u=i(s,l);if(s=void 0,deepForEach(e,(function(e){var t=r(e,u);s=void 0===s?a(t,t):n(s,a(t,t))})),o(s))return s;switch(t){case"uncorrected":return i(s,l);case"biased":return i(s,l+1);case"unbiased":var c=isBigNumber(s)?s.mul(0):0;return 1===l?c:i(s,l-1);default:throw new Error('Unknown normalization "'+t+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function u(e,t,n){try{if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return s(e,t,(e=>l(e,n)))}catch(e){throw improveErrorMessage(e,"variance")}}})),name$J="quantileSeq",dependencies$J=["typed","add","multiply","partitionSelect","compare"],createQuantileSeq=factory(name$J,dependencies$J,(e=>{var{typed:t,add:n,multiply:r,partitionSelect:a,compare:i}=e;function s(e,t,s){var l=flatten$4(e),u=l.length;if(0===u)throw new Error("Cannot calculate quantile of an empty sequence");if(isNumber$1(t)){var c=t*(u-1),p=c%1;if(0===p){var d=s?l[c]:a(l,c);return o(d),d}var m,h,f=Math.floor(c);if(s)m=l[f],h=l[f+1];else{h=a(l,f+1),m=l[f];for(var y=0;y0&&(m=l[y])}return o(m),o(h),n(r(m,1-p),r(h,p))}var g=t.times(u-1);if(g.isInteger()){g=g.toNumber();var b=s?l[g]:a(l,g);return o(b),b}var v,N,T=g.floor(),C=g.minus(T),A=T.toNumber();if(s)v=l[A],N=l[A+1];else{N=a(l,A+1),v=l[A];for(var V=0;V0&&(v=l[V])}o(v),o(N);var x=new C.constructor(1);return n(r(v,x.minus(C)),r(N,C))}var o=t({"number | BigNumber | Unit":function(e){return e}});return function(e,t,n){var r,a,i;if(arguments.length<2||arguments.length>3)throw new SyntaxError("Function quantileSeq requires two or three parameters");if(isCollection(e)){if("boolean"==typeof(n=n||!1)){if(a=e.valueOf(),isNumber$1(t)){if(t<0)throw new Error("N/prob must be non-negative");if(t<=1)return s(a,t,n);if(t>1){if(!isInteger$1(t))throw new Error("N must be a positive integer");var o=t+1;r=new Array(t);for(var l=0;l4294967295)throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var p=new u(c+1);r=new Array(c);for(var d=0;d1)throw new Error("Probability must be between 0 and 1, inclusive")}else{if(!isBigNumber(h))throw new TypeError("Unexpected type of argument in function quantileSeq");if(i=new h.constructor(1),h.isNegative()||h.gt(i))throw new Error("Probability must be between 0 and 1, inclusive")}r[m]=s(a,h,n)}return r}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}})),name$I="std",dependencies$I=["typed","sqrt","variance"],createStd=factory(name$I,dependencies$I,(e=>{var{typed:t,sqrt:n,variance:r}=e;return t(name$I,{"Array | Matrix":a,"Array | Matrix, string":a,"Array | Matrix, number | BigNumber":a,"Array | Matrix, number | BigNumber, string":a,"...":function(e){return a(e)}});function a(e,t){if(0===e.length)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{return n(r.apply(null,arguments))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf(" variance")?new TypeError(e.message.replace(" variance"," std")):e}}})),name$H="combinations",dependencies$H=["typed"],createCombinations=factory(name$H,dependencies$H,(e=>{var{typed:t}=e;return t(name$H,{"number, number":combinationsNumber,"BigNumber, BigNumber":function(e,t){var n,r,a=e.constructor,i=e.minus(t),s=new a(1);if(!isPositiveInteger$2(e)||!isPositiveInteger$2(t))throw new TypeError("Positive integer value expected in function combinations");if(t.gt(e))throw new TypeError("k must be less than n in function combinations");if(n=s,t.lt(i))for(r=s;r.lte(i);r=r.plus(s))n=n.times(t.plus(r)).dividedBy(r);else for(r=s;r.lte(t);r=r.plus(s))n=n.times(i.plus(r)).dividedBy(r);return n}})}));function isPositiveInteger$2(e){return e.isInteger()&&e.gte(0)}var name$G="combinationsWithRep",dependencies$G=["typed"],createCombinationsWithRep=factory(name$G,dependencies$G,(e=>{var{typed:t}=e;return t(name$G,{"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(e<1)throw new TypeError("k must be less than or equal to n + k - 1");return t{var{typed:t,config:n,multiplyScalar:r,pow:a,BigNumber:i,Complex:s}=e;return t(name$F,{number:gammaNumber,Complex:function(e){if(0===e.im)return this(e.re);if(e.re<.5){var t=new s(1-e.re,-e.im),n=new s(Math.PI*e.re,Math.PI*e.im);return new s(Math.PI).div(n.sin()).div(this(t))}e=new s(e.re-1,e.im);for(var r=new s(gammaP[0],0),a=1;a2;)l+=a-=2,s=s.times(l);return new i(s.toPrecision(i.precision))}})),name$E="lgamma",dependencies$E=["Complex","typed"],createLgamma=factory(name$E,dependencies$E,(e=>{var{Complex:t,typed:n}=e,r=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return n(name$E,{number:lgammaNumber,Complex:function(e){if(e.isNaN())return new t(NaN,NaN);if(0===e.im)return new t(lgammaNumber(e.re),0);if(e.re>=7||Math.abs(e.im)>=7)return a(e);if(e.re<=.1){var n=copysign(6.283185307179586,e.im)*Math.floor(.5*e.re+.25),r=e.mul(Math.PI).sin().log(),s=this(new t(1-e.re,-e.im));return new t(1.1447298858494002,n).sub(r).sub(s)}return e.im>=0?i(e):i(e.conjugate()).conjugate()},BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function a(e){for(var n=e.sub(.5).mul(e.log()).sub(e).add(lnSqrt2PI),a=new t(1,0).div(e),i=a.div(e),s=r[0],o=r[1],l=2*i.re,u=i.re*i.re+i.im*i.im,c=2;c<8;c++){var p=o;o=-u*s+r[c],s=l*s+p}var d=a.mul(i.mul(s).add(o));return n.add(d)}function i(e){var n=0,r=0,i=e;for(e=e.add(1);e.re<=7;){var s=(i=i.mul(e)).im<0?1:0;0!==s&&0===r&&n++,r=s,e=e.add(1)}return a(e).sub(i.log()).sub(new t(0,2*n*Math.PI*1))}})),name$D="factorial",dependencies$D=["typed","gamma"],createFactorial=factory(name$D,dependencies$D,(e=>{var{typed:t,gamma:n}=e;return t(name$D,{number:function(e){if(e<0)throw new Error("Value must be non-negative");return n(e+1)},BigNumber:function(e){if(e.isNegative())throw new Error("Value must be non-negative");return n(e.plus(1))},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$C="kldivergence",dependencies$C=["typed","matrix","divide","sum","multiply","dotDivide","log","isNumeric"],createKldivergence=factory(name$C,dependencies$C,(e=>{var{typed:t,matrix:n,divide:r,sum:a,multiply:i,dotDivide:s,log:o,isNumeric:l}=e;return t(name$C,{"Array, Array":function(e,t){return u(n(e),n(t))},"Matrix, Array":function(e,t){return u(e,n(t))},"Array, Matrix":function(e,t){return u(n(e),t)},"Matrix, Matrix":function(e,t){return u(e,t)}});function u(e,t){var n=t.size().length,u=e.size().length;if(n>1)throw new Error("first object must be one dimensional");if(u>1)throw new Error("second object must be one dimensional");if(n!==u)throw new Error("Length of two vectors must be equal");if(0===a(e))throw new Error("Sum of elements in first object must be non zero");if(0===a(t))throw new Error("Sum of elements in second object must be non zero");var c=r(e,a(e)),p=r(t,a(t)),d=a(i(c,o(s(c,p))));return l(d)?d:Number.NaN}})),name$B="multinomial",dependencies$B=["typed","add","divide","multiply","factorial","isInteger","isPositive"],createMultinomial=factory(name$B,dependencies$B,(e=>{var{typed:t,add:n,divide:r,multiply:a,factorial:i,isInteger:s,isPositive:o}=e;return t(name$B,{"Array | Matrix":function(e){var t=0,l=1;return deepForEach(e,(function(e){if(!s(e)||!o(e))throw new TypeError("Positive integer value expected in function multinomial");t=n(t,e),l=a(l,i(e))})),r(i(t),l)}})})),name$A="permutations",dependencies$A=["typed","factorial"],createPermutations=factory(name$A,dependencies$A,(e=>{var{typed:t,factorial:n}=e;return t(name$A,{"number | BigNumber":n,"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function permutations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function permutations");if(t>e)throw new TypeError("second argument k must be less than or equal to first argument n");return product(e-t+1,e)},"BigNumber, BigNumber":function(e,t){var n,r;if(!isPositiveInteger(e)||!isPositiveInteger(t))throw new TypeError("Positive integer value expected in function permutations");if(t.gt(e))throw new TypeError("second argument k must be less than or equal to first argument n");for(n=e.mul(0).add(1),r=e.minus(t).plus(1);r.lte(e);r=r.plus(1))n=n.times(r);return n}})}));function isPositiveInteger(e){return e.isInteger()&&e.gte(0)}var alea$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n=function(){var e=4022871197;return function(t){t=String(t);for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)}}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function i(e,t){var n=new r(e),i=t&&t.state,s=n.next;return s.int32=function(){return 4294967296*n.next()|0},s.double=function(){return s()+11102230246251565e-32*(2097152*s()|0)},s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.alea=i}(0,e)}(alea$1);var xor128$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xor128=i}(0,e)}(xor128$1);var xorwow$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function i(e,t){var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xorwow=i}(0,e)}(xorwow$1);var xorshift7$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&(i.x&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xorshift7=i}(0,e)}(xorshift7$1);var xor4096$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,i=t.i;return t.w=r=r+1640531527|0,n=a[i+34&127],e=a[i=i+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[i]=n^e,t.i=i,n+(r^r>>>16)|0},function(e,t){var n,r,a,i,s,o=[],l=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,l=Math.max(l,t.length)),a=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,i>=0&&(s=s+1640531527|0,a=0==(n=o[127&i]^=r+s)?a+1:0);for(a>=128&&(o[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=o[a+34&127],n=o[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[a]=r^n;e.w=s,e.X=o,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&(i.X&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xor4096=i}(0,e)}(xor4096$1);var tychei$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.tychei=i}(0,e)}(tychei$1);var seedrandom$2={exports:{}},_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1);!function(e){!function(t,n,r){var a,i=256,s="random",o=r.pow(i,6),l=r.pow(2,52),u=2*l,c=255;function p(e,c,p){var g=[],b=f(h((c=1==c?{entropy:!0}:c||{}).entropy?[e,y(n)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(i):(e=new Uint8Array(i),(t.crypto||t.msCrypto).getRandomValues(e)),y(e)}catch(e){var r=t.navigator,s=r&&r.plugins;return[+new Date,t,s,t.screen,y(n)]}}():e,3),g),v=new d(g),N=function(){for(var e=v.g(6),t=o,n=0;e=u;)e/=2,t/=2,n>>>=1;return(e+n)/t};return N.int32=function(){return 0|v.g(4)},N.quick=function(){return v.g(4)/4294967296},N.double=N,f(y(v.S),n),(c.pass||p||function(e,t,n,a){return a&&(a.S&&m(a,v),e.state=function(){return m(v,{})}),n?(r[s]=e,t):e})(N,b,"global"in c?c.global:this==r,c.state)}function d(e){var t,n=e.length,r=this,a=0,s=r.i=r.j=0,o=r.S=[];for(n||(e=[n++]);a{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$z,{"Array | Matrix":function(e){return i(e,{})},"Array | Matrix, Object":function(e,t){return i(e,t)},"Array | Matrix, number":function(e,t){return i(e,{number:t})},"Array | Matrix, Array | Matrix":function(e,t){return i(e,{weights:t})},"Array | Matrix, Array | Matrix, number":function(e,t,n){return i(e,{number:n,weights:t})},"Array | Matrix, number, Array | Matrix":function(e,t,n){return i(e,{number:t,weights:n})}});function i(e,t){var{number:n,weights:r,elementWise:i=!0}=t,s=void 0===n;s&&(n=1);var o=isMatrix(e)?e.create:isMatrix(r)?r.create:null;e=e.valueOf(),r&&(r=r.valueOf()),!0===i&&(e=flatten$4(e),r=flatten$4(r));var l=0;if(void 0!==r){if(r.length!==e.length)throw new Error("Weights must have the same length as possibles");for(var u=0,c=r.length;u1)for(var r=0,a=e.shift();r{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$y,{"":()=>s(0,1),number:e=>s(0,e),"number, number":(e,t)=>s(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>s(t,n)));return isMatrix(e)?e.create(r):r}function s(e,t){return e+a()*(t-e)}})),name$x="randomInt",dependencies$x=["typed","config","?on"],createRandomInt=factory(name$x,dependencies$x,(e=>{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$x,{"":()=>s(0,1),number:e=>s(0,e),"number, number":(e,t)=>s(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>s(t,n)));return isMatrix(e)?e.create(r):r}function s(e,t){return Math.floor(e+a()*(t-e))}})),name$w="stirlingS2",dependencies$w=["typed","addScalar","subtract","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],createStirlingS2=factory(name$w,dependencies$w,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,pow:s,factorial:o,combinations:l,isNegative:u,isInteger:c,number:p,bignumber:d,larger:m}=e,h=[],f=[];return t(name$w,{"number | BigNumber, number | BigNumber":function(e,t){if(!c(e)||u(e)||!c(t)||u(t))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(m(t,e))throw new TypeError("k must be less than or equal to n in function stirlingS2");var r=!(isNumber$1(e)&&isNumber$1(t)),i=r?f:h,s=r?d:p,o=p(e),l=p(t);if(i[o]&&i[o].length>l)return i[o][l];for(var y=0;y<=o;++y)if(i[y]||(i[y]=[s(0===y?1:0)]),0!==y)for(var g=i[y],b=i[y-1],v=g.length;v<=y&&v<=l;++v)g[v]=v===y?1:n(a(s(v),b[v]),b[v-1]);return i[o][l]}})})),name$v="bellNumbers",dependencies$v=["typed","addScalar","isNegative","isInteger","stirlingS2"],createBellNumbers=factory(name$v,dependencies$v,(e=>{var{typed:t,addScalar:n,isNegative:r,isInteger:a,stirlingS2:i}=e;return t(name$v,{"number | BigNumber":function(e){if(!a(e)||r(e))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var t=0,s=0;s<=e;s++)t=n(t,i(e,s));return t}})})),name$u="catalan",dependencies$u=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],createCatalan=factory(name$u,dependencies$u,(e=>{var{typed:t,addScalar:n,divideScalar:r,multiplyScalar:a,combinations:i,isNegative:s,isInteger:o}=e;return t(name$u,{"number | BigNumber":function(e){if(!o(e)||s(e))throw new TypeError("Non-negative integer value expected in function catalan");return r(i(a(e,2),e),n(e,1))}})})),name$t="composition",dependencies$t=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],createComposition=factory(name$t,dependencies$t,(e=>{var{typed:t,addScalar:n,combinations:r,isPositive:a,isNegative:i,isInteger:s,larger:o}=e;return t(name$t,{"number | BigNumber, number | BigNumber":function(e,t){if(!(s(e)&&a(e)&&s(t)&&a(t)))throw new TypeError("Positive integer value expected in function composition");if(o(t,e))throw new TypeError("k must be less than or equal to n in function composition");return r(n(e,-1),n(t,-1))}})})),name$s="leafCount",dependencies$s=["parse","typed"],createLeafCount=factory(name$s,dependencies$s,(e=>{var{parse:t,typed:n}=e;function r(e){var t=0;return e.forEach((e=>{t+=r(e)})),t||1}return n(name$s,{string:function(e){return this(t(e))},Node:function(e){return r(e)}})}));function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread(e){for(var t=1;t{var{FunctionNode:t,OperatorNode:n,SymbolNode:r}=e,a=!0,i=!1,s="defaultF",o={add:{trivial:a,total:a,commutative:a,associative:a},unaryPlus:{trivial:a,total:a,commutative:a,associative:a},subtract:{trivial:i,total:a,commutative:i,associative:i},multiply:{trivial:a,total:a,commutative:a,associative:a},divide:{trivial:i,total:a,commutative:i,associative:i},paren:{trivial:a,total:a,commutative:a,associative:i},defaultF:{trivial:i,total:a,commutative:i,associative:i}};function l(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o,r=s;if("string"==typeof e?r=e:isOperatorNode(e)?r=e.fn.toString():isFunctionNode(e)?r=e.name:isParenthesisNode(e)&&(r="paren"),hasOwnProperty$2(n,r)){var a=n[r];if(hasOwnProperty$2(a,t))return a[t];if(hasOwnProperty$2(o,r))return o[r][t]}if(hasOwnProperty$2(n,s)){var i=n[s];return hasOwnProperty$2(i,t)?i[t]:o[s][t]}if(hasOwnProperty$2(o,r)){var l=o[r];if(hasOwnProperty$2(l,t))return l[t]}return o[s][t]}function u(e){return l(e,"associative",arguments.length>1&&void 0!==arguments[1]?arguments[1]:o)}function c(e,t){var n,r=[];return u(e,t)?(n=e.op,function e(t){for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:o)},isAssociative:u,mergeContext:function(e,t){var n=_objectSpread({},e);for(var r in t)hasOwnProperty$2(e,r)?n[r]=_objectSpread(_objectSpread({},t[r]),e[r]):n[r]=t[r];return n},flatten:function e(t,n){if(!t.args||0===t.args.length)return t;t.args=c(t,n);for(var r=0;r2&&u(t,n)){for(var s=t.args.pop();t.args.length>0;)s=r([t.args.pop(),s]);t.args=s.args}}},unflattenl:function e(t,n){if(t.args&&0!==t.args.length){for(var r=p(t),a=t.args.length,i=0;i2&&u(t,n)){for(var s=t.args.shift();t.args.length>0;)s=r([s,t.args.shift()]);t.args=s.args}}},defaultContext:o,realContext:{divide:{total:i},log:{total:i}},positiveContext:{subtract:{total:i},abs:{trivial:a},log:{total:a}}}})),name$q="simplifyConstant",dependencies$q=["typed","config","mathWithTransform","matrix","?fraction","?bignumber","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode"],createSimplifyConstant=factory(name$q,dependencies$q,(e=>{var{typed:t,config:n,mathWithTransform:r,matrix:a,fraction:i,bignumber:s,AccessorNode:o,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:p,ObjectNode:d,OperatorNode:m,SymbolNode:h}=e,{isCommutative:f,isAssociative:y,allChildren:g,createMakeNodeFunction:b}=createUtil({FunctionNode:c,OperatorNode:m,SymbolNode:h});function v(e,t){return A(E(e,t))}function N(e){return isFraction(e)?e.valueOf():e instanceof Array?e.map(N):isMatrix(e)?a(N(e.valueOf())):e}function T(e,t,n){try{return r[e].apply(null,t)}catch(a){return t=t.map(N),x(r[e].apply(null,t),n)}}var C=t({Fraction:function(e){var t,n=e.s*e.n;return t=n<0?new m("-","unaryMinus",[new u(-n)]):new u(n),1===e.d?t:new m("/","divide",[t,new u(e.d)])},number:function(e){return e<0?S(new u(-e)):new u(e)},BigNumber:function(e){return e<0?S(new u(-e)):new u(e)},Complex:function(e){throw new Error("Cannot convert Complex number to Node")},string:function(e){return new u(e)},Matrix:function(e){return new l(e.valueOf().map((e=>C(e))))}});function A(e){return isNode(e)?e:C(e)}function V(e,t){if(t&&!1!==t.exactFractions&&isFinite(e)&&i){var n=i(e),r=t&&"number"==typeof t.fractionsLimit?t.fractionsLimit:1/0;if(n.valueOf()===e&&n.nE(e,t)));if(!n.some(isNode))try{return T(e.name,n,t)}catch(e){}if("size"===e.name&&1===n.length&&isArrayNode(n[0])){for(var i=[],s=n[0];isArrayNode(s);)i.push(s.items.length),s=s.items[0];return a(i)}return new c(e.name,n.map(A))}case"OperatorNode":var m,h,N=e.fn.toString(),C=b(e);if(isOperatorNode(e)&&e.isUnary())h=isNode((m=[E(e.args[0],t)])[0])?C(m):T(N,m,t);else if(y(e,t.context))if(m=(m=g(e,t.context)).map((e=>E(e,t))),f(N,t.context)){for(var V=[],S=[],D=0;D1?(h=w(N,V,C,t),S.unshift(h),h=w(N,S,C,t)):h=w(N,m,C,t)}else h=w(N,m,C,t);else h=w(N,m=e.args.map((e=>E(e,t))),C,t);return h;case"ParenthesisNode":return E(e.content,t);case"AccessorNode":return function(e,t,n){if(!isIndexNode(t))return new o(A(e),A(t));if(isArrayNode(e)||isMatrix(e)){for(var r=Array.from(t.dimensions);r.length>0;)if(isConstantNode(r[0])&&"string"!=typeof r[0].value){var i=x(r.shift().value,n);isArrayNode(e)?e=e.items[i-1]:(e=e.valueOf()[i-1])instanceof Array&&(e=a(e))}else{if(!(r.length>1&&isConstantNode(r[1])&&"string"!=typeof r[1].value))break;var s=x(r[1].value,n),c=[],d=isArrayNode(e)?e.items:e.valueOf();for(var m of d)if(isArrayNode(m))c.push(m.items[s-1]);else{if(!isMatrix(e))break;c.push(m[s-1])}if(c.length!==d.length)break;e=isArrayNode(e)?new l(c):a(c),r.splice(1,1)}return r.length===t.dimensions.length?new o(A(e),t):r.length>0?(t=new p(r),new o(A(e),t)):e}if(isObjectNode(e)&&1===t.dimensions.length&&isConstantNode(t.dimensions[0])){var h=t.dimensions[0].value;return h in e.properties?e.properties[h]:new u}return new o(A(e),t)}(E(e.object,t),E(e.index,t),t);case"ArrayNode":var O=e.items.map((e=>E(e,t)));return O.some(isNode)?new l(O.map(A)):a(O);case"IndexNode":return new p(e.dimensions.map((e=>v(e,t))));case"ObjectNode":var I={};for(var R in e.properties)I[R]=v(e.properties[R],t);return new d(I);default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(e.type))}}return v})),name$p="simplify",dependencies$p=["config","typed","parse","add","subtract","multiply","divide","pow","isZero","equal","resolve","simplifyCore","?fraction","?bignumber","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],createSimplify=factory(name$p,dependencies$p,(e=>{var{config:t,typed:n,parse:r,add:a,subtract:i,multiply:s,divide:o,pow:l,isZero:u,equal:c,resolve:p,simplifyCore:d,fraction:m,bignumber:h,mathWithTransform:f,matrix:y,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,ParenthesisNode:V,SymbolNode:x}=e,S=createSimplifyConstant({typed:n,config:t,mathWithTransform:f,matrix:y,fraction:m,bignumber:h,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:x}),{hasProperty:w,isCommutative:E,isAssociative:D,mergeContext:O,flatten:I,unflattenr:R,unflattenl:_,createMakeNodeFunction:M,defaultContext:P,realContext:F,positiveContext:k}=createUtil({FunctionNode:N,OperatorNode:A,SymbolNode:x}),$=n("simplify",{string:function(e){return this(r(e),this.rules,createEmptyMap(),{})},"string, Map | Object":function(e,t){return this(r(e),this.rules,t,{})},"string, Map | Object, Object":function(e,t,n){return this(r(e),this.rules,t,n)},"string, Array":function(e,t){return this(r(e),t,createEmptyMap(),{})},"string, Array, Map | Object":function(e,t,n){return this(r(e),t,n,{})},"string, Array, Map | Object, Object":function(e,t,n,a){return this(r(e),t,n,a)},"Node, Map | Object":function(e,t){return this(e,this.rules,t,{})},"Node, Map | Object, Object":function(e,t,n){return this(e,this.rules,t,n)},Node:function(e){return this(e,this.rules,createEmptyMap(),{})},"Node, Array":function(e,t){return this(e,t,createEmptyMap(),{})},"Node, Array, Map | Object":function(e,t,n){return this(e,t,n,{})},"Node, Array, Object, Object":function(e,t,n,r){return this(e,t,createMap$1(n),r)},"Node, Array, Map, Object":function(e,t,n,r){var a=r.consoleDebug;t=function(e,t){for(var n=[],r=0;r ").concat(t[u].r.toString()))),a){var d=i.toString({parenthesis:"all"});d!==l&&(console.log("Applying",c,"produced",d),l=d)}_(i,r.context)}o=i.toString({parenthesis:"all"})}return i}});function B(e){return e.transform((function(e,t,n){return isParenthesisNode(e)?B(e.content):e}))}$.defaultContext=P,$.realContext=F,$.positiveContext=k;var L={true:!0,false:!0,e:!0,i:!0,Infinity:!0,LN2:!0,LN10:!0,LOG2E:!0,LOG10E:!0,NaN:!0,phi:!0,pi:!0,SQRT1_2:!0,SQRT2:!0,tau:!0};function z(e,t){var n={};if(e.s){var a=e.s.split("->");if(2!==a.length)throw SyntaxError("Could not parse rule: "+e.s);n.l=a[0],n.r=a[1]}else n.l=e.l,n.r=e.r;for(var i of(n.l=B(r(n.l)),n.r=B(r(n.r)),["imposeContext","repeat","assuming"]))i in e&&(n[i]=e[i]);if(e.evaluate&&(n.evaluate=r(e.evaluate)),D(n.l,t)){var s=M(n.l),o=new x("_p"+U++);n.expanded={},n.expanded.l=s([n.l.clone(),o]),I(n.expanded.l,t),R(n.expanded.l,t),n.expanded.r=s([n.r,o])}return n}$.rules=[d,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(c*v) -> v * (-c)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(c*v) -> (-c) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*c) -> v * (-c)",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{l:"-(n1/n2)",r:"-n1/n2"},{l:"-v",r:"v * (-1)"},{l:"(n1 + n2)*(-1)",r:"n1*(-1) + n2*(-1)",repeat:!0},{l:"n/n1^n2",r:"n*n1^-n2"},{l:"n/n1",r:"n*n1^-1"},{s:"(n1*n2)^n3 -> n1^n3 * n2^n3",assuming:{multiply:{commutative:!0}}},{s:"(n1*n2)^(-1) -> n2^(-1) * n1^(-1)",assuming:{multiply:{commutative:!1}}},{s:"(n ^ n1) ^ n2 -> n ^ (n1 * n2)",assuming:{divide:{total:!0}}},{l:" v * ( v * n1 + n2)",r:"v^2 * n1 + v * n2"},{s:" v * (v^n4 * n1 + n2) -> v^(1+n4) * n1 + v * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * ( v * n1 + n2) -> v^(n3+1) * n1 + v^n3 * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * (v^n4 * n1 + n2) -> v^(n3+n4) * n1 + v^n3 * n2",assuming:{divide:{total:!0}}},{l:"n*n",r:"n^2"},{s:"n * n^n1 -> n^(n1+1)",assuming:{divide:{total:!0}}},{s:"n^n1 * n^n2 -> n^(n1+n2)",assuming:{divide:{total:!0}}},S,{s:"n+n -> 2*n",assuming:{add:{total:!0}}},{l:"n+-n",r:"0"},{l:"v*n + v",r:"v*(n+1)"},{l:"n3*n1 + n3*n2",r:"n3*(n1+n2)"},{l:"n3^(-n4)*n1 + n3 * n2",r:"n3^(-n4)*(n1 + n3^(n4+1) *n2)"},{l:"n3^(-n4)*n1 + n3^n5 * n2",r:"n3^(-n4)*(n1 + n3^(n4+n5)*n2)"},{s:"n*v + v -> (n+1)*v",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3 -> (n1 + n2*n3^(n4 + 1))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{l:"n*c + c",r:"(n+1)*c"},{s:"c*n + c -> c*(n+1)",assuming:{multiply:{commutative:!1}}},S,{s:"(-n)*n1 -> -(n*n1)",assuming:{subtract:{total:!0}}},{s:"n1*(-n) -> -(n1*n)",assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:"c+v -> v+c",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"v*c -> c*v",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{l:"n+-n1",r:"n-n1"},{s:"n*(n1^-1) -> n/n1",assuming:{multiply:{commutative:!0}}},{s:"n*n1^-n2 -> n/n1^n2",assuming:{multiply:{commutative:!0}}},{s:"n^-1 -> 1/n",assuming:{multiply:{commutative:!0}}},{l:"n^1",r:"n"},{s:"n*(n1/n2) -> (n*n1)/n2",assuming:{multiply:{associative:!0}}},{s:"n-(n1+n2) -> n-n1-n2",assuming:{addition:{associative:!0,commutative:!0}}},{l:"1*n",r:"n",imposeContext:{multiply:{commutative:!0}}},{s:"n1/(n2/n3) -> (n1*n3)/n2",assuming:{multiply:{associative:!0}}},{l:"n1/(-n2)",r:"-n1/n2"}];var U=0;function j(e,t,n){var r=e;if(e)for(var a=0;a=2&&2===e.args.length){for(var i=function(e,t){var n,r,a=[],i=M(e);if(E(e,t))for(var s=0;s1&&(l=i(e.args.slice(0,o))),n=1===(r=e.args.slice(o)).length?r[0]:i(r),a.push(i([l,n]))}return a}(t,n),s=[],o=0;o2)throw Error("Unexpected non-binary associative function: "+e.toString());return[]}for(var u=[],p=0;p2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var m=W(e.args[0],t.args[1],n);if(0===m.length)return[];var h=W(e.args[1],t.args[0],n);if(0===h.length)return[];u=[m,h]}a=function(e){if(0===e.length)return e;for(var t=e.reduce(H),n=[],r={},a=0;a{var{equal:t,isZero:n,add:r,subtract:a,multiply:i,divide:s,pow:o,AccessorNode:l,ArrayNode:u,ConstantNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:h,ParenthesisNode:f,SymbolNode:y}=e,g=new c(0),b=new c(1),{hasProperty:v,isCommutative:N}=createUtil({FunctionNode:p,OperatorNode:h,SymbolNode:y});return function e(f,y){var T=y?y.context:void 0;if(v(f,"trivial",T)){if(isFunctionNode(f)&&1===f.args.length)return e(f.args[0],y);var C=!1,A=0;if(f.forEach((t=>{1==++A&&(C=e(t,y))})),1===A)return C}if(isOperatorNode(f)&&f.isUnary()){var V=e(f.args[0],y);if("-"===f.op){if(isOperatorNode(V)){if(V.isUnary()&&"-"===V.op)return V.args[0];if(V.isBinary()&&"subtract"===V.fn)return new h("-","subtract",[V.args[1],V.args[0]])}return new h(f.op,f.fn,[V])}}else{if(isOperatorNode(f)&&f.isBinary()){var x=e(f.args[0],y),S=e(f.args[1],y);if("+"===f.op){if(isConstantNode(x)){if(n(x.value))return S;if(isConstantNode(S))return new c(r(x.value,S.value))}return isConstantNode(S)&&n(S.value)?x:isOperatorNode(S)&&S.isUnary()&&"-"===S.op?new h("-","subtract",[x,S.args[0]]):new h(f.op,f.fn,S?[x,S]:[x])}if("-"===f.op){if(isConstantNode(x)&&S){if(isConstantNode(S))return new c(a(x.value,S.value));if(n(x.value))return new h("-","unaryMinus",[S])}if("subtract"===f.fn)return isConstantNode(S)&&n(S.value)?x:isOperatorNode(S)&&S.isUnary()&&"-"===S.op?e(new h("+","add",[x,S.args[0]]),y):new h(f.op,f.fn,[x,S])}else{if("*"===f.op){if(isConstantNode(x)){if(n(x.value))return g;if(t(x.value,1))return S;if(isConstantNode(S))return new c(i(x.value,S.value))}if(isConstantNode(S)){if(n(S.value))return g;if(t(S.value,1))return x;if(isOperatorNode(x)&&x.isBinary()&&x.op===f.op&&N(f,T)){var w=x.args[0];if(isConstantNode(w)){var E=new c(i(w.value,S.value));return new h(f.op,f.fn,[E,x.args[1]],f.implicit)}}return N(f,T)?new h(f.op,f.fn,[S,x],f.implicit):new h(f.op,f.fn,[x,S],f.implicit)}return new h(f.op,f.fn,[x,S],f.implicit)}if("/"===f.op){if(isConstantNode(x)){if(n(x.value))return g;if(isConstantNode(S)&&(t(S.value,1)||t(S.value,2)||t(S.value,4)))return new c(s(x.value,S.value))}return new h(f.op,f.fn,[x,S])}if("^"===f.op&&isConstantNode(S)){if(n(S.value))return b;if(t(S.value,1))return x;if(isConstantNode(x))return new c(o(x.value,S.value));if(isOperatorNode(x)&&x.isBinary()&&"^"===x.op){var D=x.args[1];if(isConstantNode(D))return new h(f.op,f.fn,[x.args[0],new c(i(D.value,S.value))])}}}return new h(f.op,f.fn,[x,S])}if(isFunctionNode(f))return new p(e(f.fn),f.args.map((t=>e(t,y))));if(isArrayNode(f))return new u(f.items.map((t=>e(t,y))));if(isAccessorNode(f))return new l(e(f.object,y),e(f.index,y));if(isIndexNode(f))return new d(f.dimensions.map((t=>e(t,y))));if(isObjectNode(f)){var O={};for(var I in f.properties)O[I]=e(f.properties[I],y);return new m(O)}}return f}})),name$n="resolve",dependencies$n=["parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],createResolve=factory(name$n,dependencies$n,(e=>{var{parse:t,ConstantNode:n,FunctionNode:r,OperatorNode:a,ParenthesisNode:i}=e;return function e(s,o){var l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Set;if(!o)return s;if(isMap$1(o)||(o=createMap$1(o)),isSymbolNode(s)){if(l.has(s.name)){var u=Array.from(l).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(u,"}"))}var c=o.get(s.name);if(isNode(c)){var p=new Set(l);return p.add(s.name),e(c,o,p)}return"number"==typeof c?t(String(c)):void 0!==c?new n(c):s}if(isOperatorNode(s)){var d=s.args.map((function(t){return e(t,o,l)}));return new a(s.op,s.fn,d,s.implicit)}if(isParenthesisNode(s))return new i(e(s.content,o,l));if(isFunctionNode(s)){var m=s.args.map((function(t){return e(t,o,l)}));return new r(s.name,m)}return s.map((t=>e(t,o,l)))}})),name$m="symbolicEqual",dependencies$m=["parse","simplify","typed","OperatorNode"],createSymbolicEqual=factory(name$m,dependencies$m,(e=>{var{parse:t,simplify:n,typed:r,OperatorNode:a}=e;return r(name$m,{"string, string":function(e,n){return this(t(e),t(n),{})},"string, string, Object":function(e,n,r){return this(t(e),t(n),r)},"Node, string":function(e,n){return this(e,t(n),{})},"Node, string, Object":function(e,n,r){return this(e,t(n),r)},"string, Node":function(e,n){return this(t(e),n,{})},"string, Node, Object":function(e,n,r){return this(t(e),n,r)},"Node, Node":function(e,t){return this(e,t,{})},"Node, Node, Object":function(e,t,r){var i=new a("-","subtract",[e,t]),s=n(i,{},r);return isConstantNode(s)&&!s.value}})})),name$l="derivative",dependencies$l=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],createDerivative=factory(name$l,dependencies$l,(e=>{var{typed:t,config:n,parse:r,simplify:a,equal:i,isZero:s,numeric:o,ConstantNode:l,FunctionNode:u,OperatorNode:c,ParenthesisNode:p,SymbolNode:d}=e,m=t("derivative",{"Node, SymbolNode, Object":function(e,t,n){var r={};f(r,e,t.name);var i=y(e,r);return n.simplify?a(i):i},"Node, SymbolNode":function(e,t){return this(e,t,{simplify:!0})},"string, SymbolNode":function(e,t){return this(r(e),t)},"string, SymbolNode, Object":function(e,t,n){return this(r(e),t,n)},"string, string":function(e,t){return this(r(e),r(t))},"string, string, Object":function(e,t,n){return this(r(e),r(t),n)},"Node, string":function(e,t){return this(e,r(t))},"Node, string, Object":function(e,t,n){return this(e,r(t),n)}});m._simplify=!0,m.toTex=function(e){return h.apply(null,e.args)};var h=t("_derivTex",{"Node, SymbolNode":function(e,t){return isConstantNode(e)&&"string"===typeOf$1(e.value)?h(r(e.value).toString(),t.toString(),1):h(e.toTex(),t.toString(),1)},"Node, ConstantNode":function(e,t){if("string"===typeOf$1(t.value))return h(e,r(t.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(e,t,n){return h(e.toString(),t.name,n.value)},"string, string, number":function(e,t,n){return(1===n?"{d\\over d"+t+"}":"{d^{"+n+"}\\over d"+t+"^{"+n+"}}")+"\\left[".concat(e,"\\right]")}}),f=t("constTag",{"Object, ConstantNode, string":function(e,t){return e[t]=!0,!0},"Object, SymbolNode, string":function(e,t,n){return t.name!==n&&(e[t]=!0,!0)},"Object, ParenthesisNode, string":function(e,t,n){return f(e,t.content,n)},"Object, FunctionAssignmentNode, string":function(e,t,n){return-1===t.params.indexOf(n)?(e[t]=!0,!0):f(e,t.expr,n)},"Object, FunctionNode | OperatorNode, string":function(e,t,n){if(t.args.length>0){for(var r=f(e,t.args[0],n),a=1;a0){var r=e.args.filter((function(e){return void 0===t[e]})),a=1===r.length?r[0]:new c("*","multiply",r),o=n.concat(y(a,t));return new c("*","multiply",o)}return new c("+","add",e.args.map((function(n){return new c("*","multiply",e.args.map((function(e){return e===n?y(e,t):e.clone()})))})))}if("/"===e.op&&e.isBinary()){var l=e.args[0],p=e.args[1];return void 0!==t[p]?new c("/","divide",[y(l,t),p]):void 0!==t[l]?new c("*","multiply",[new c("-","unaryMinus",[l]),new c("/","divide",[y(p,t),new c("^","pow",[p.clone(),g(2)])])]):new c("/","divide",[new c("-","subtract",[new c("*","multiply",[y(l,t),p.clone()]),new c("*","multiply",[l.clone(),y(p,t)])]),new c("^","pow",[p.clone(),g(2)])])}if("^"===e.op&&e.isBinary()){var d=e.args[0],m=e.args[1];if(void 0!==t[d])return isConstantNode(d)&&(s(d.value)||i(d.value,1))?g(0):new c("*","multiply",[e,new c("*","multiply",[new u("log",[d.clone()]),y(m.clone(),t)])]);if(void 0!==t[m]){if(isConstantNode(m)){if(s(m.value))return g(0);if(i(m.value,1))return y(d,t)}var h=new c("^","pow",[d.clone(),new c("-","subtract",[m,g(1)])]);return new c("*","multiply",[m.clone(),new c("*","multiply",[y(d,t),h])])}return new c("*","multiply",[new c("^","pow",[d.clone(),m.clone()]),new c("+","add",[new c("*","multiply",[y(d,t),new c("/","divide",[m.clone(),d.clone()])]),new c("*","multiply",[y(m,t),new u("log",[d.clone()])])])])}throw new Error('Operator "'+e.op+'" is not supported by derivative, or a wrong number of arguments is passed')}});function g(e,t){return new l(o(e,t||n.number))}return m})),name$k="rationalize",dependencies$k=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],createRationalize=factory(name$k,dependencies$k,(e=>{var{config:t,typed:n,equal:r,isZero:a,add:i,subtract:s,multiply:o,divide:l,pow:u,parse:c,simplifyCore:p,simplify:d,fraction:m,bignumber:h,mathWithTransform:f,matrix:y,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:V,ParenthesisNode:x}=e,S=createSimplifyConstant({typed:n,config:t,mathWithTransform:f,matrix:y,fraction:m,bignumber:h,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:V});return n(name$k,{string:function(e){return this(c(e),{},!1)},"string, boolean":function(e,t){return this(c(e),{},t)},"string, Object":function(e,t){return this(c(e),t,!1)},"string, Object, boolean":function(e,t,n){return this(c(e),t,n)},Node:function(e){return this(e,{},!1)},"Node, boolean":function(e,t){return this(e,{},t)},"Node, Object":function(e,t){return this(e,t,!1)},"Node, Object, boolean":function(e,t,n){var r=function(){var e=[p,{l:"n+n",r:"2*n"},{l:"n+-n",r:"0"},S,{l:"n*(n1^-1)",r:"n/n1"},{l:"n*n1^-n2",r:"n/n1^n2"},{l:"n1^-1",r:"1/n1"},{l:"n*(n1/n2)",r:"(n*n1)/n2"},{l:"1*n",r:"n"}],t=[{l:"(-n1)/(-n2)",r:"n1/n2"},{l:"(-n1)*(-n2)",r:"n1*n2"},{l:"n1--n2",r:"n1+n2"},{l:"n1-n2",r:"n1+(-n2)"},{l:"(n1+n2)*n3",r:"(n1*n3 + n2*n3)"},{l:"n1*(n2+n3)",r:"(n1*n2+n1*n3)"},{l:"c1*n + c2*n",r:"(c1+c2)*n"},{l:"c1*n + n",r:"(c1+1)*n"},{l:"c1*n - c2*n",r:"(c1-c2)*n"},{l:"c1*n - n",r:"(c1-1)*n"},{l:"v/c",r:"(1/c)*v"},{l:"v/-c",r:"-(1/c)*v"},{l:"-v*-c",r:"c*v"},{l:"-v*c",r:"-c*v"},{l:"v*-c",r:"-c*v"},{l:"v*c",r:"c*v"},{l:"-(-n1*n2)",r:"(n1*n2)"},{l:"-(n1*n2)",r:"(-n1*n2)"},{l:"-(-n1+n2)",r:"(n1-n2)"},{l:"-(n1+n2)",r:"(-n1-n2)"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"},{l:"-(-n1/n2)",r:"(n1/n2)"},{l:"-(n1/n2)",r:"(-n1/n2)"}],n=[{l:"(n1/(n2/n3))",r:"((n1*n3)/n2)"},{l:"(n1/n2/n3)",r:"(n1/(n2*n3))"}],r={};return r.firstRules=e.concat(t,n),r.distrDivRules=[{l:"(n1/n2 + n3/n4)",r:"((n1*n4 + n3*n2)/(n2*n4))"},{l:"(n1/n2 + n3)",r:"((n1 + n3*n2)/n2)"},{l:"(n1 + n2/n3)",r:"((n1*n3 + n2)/n3)"}],r.sucDivRules=n,r.firstRulesAgain=e.concat(t),r.finalRules=[p,{l:"n*-n",r:"-n^2"},{l:"n*n",r:"n^2"},S,{l:"n*-n^n1",r:"-n^(n1+1)"},{l:"n*n^n1",r:"n^(n1+1)"},{l:"n^n1*-n^n2",r:"-n^(n1+n2)"},{l:"n^n1*n^n2",r:"n^(n1+n2)"},{l:"n^n1*-n",r:"-n^(n1+1)"},{l:"n^n1*n",r:"n^(n1+1)"},{l:"n^n1/-n",r:"-n^(n1-1)"},{l:"n^n1/n",r:"n^(n1-1)"},{l:"n/-n^n1",r:"-n^(1-n1)"},{l:"n/n^n1",r:"n^(1-n1)"},{l:"n^n1/-n^n2",r:"n^(n1-n2)"},{l:"n^n1/n^n2",r:"n^(n1-n2)"},{l:"n1+(-n2*n3)",r:"n1-n2*n3"},{l:"v*(-c)",r:"-c*v"},{l:"n1+-n2",r:"n1-n2"},{l:"v*c",r:"c*v"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"}],r}(),a=function(e,t,n,r){var a=[],i=d(e,r,t,{exactFractions:!1}),s="+-*"+((n=!!n)?"/":"");!function e(t){var n=t.type;if("FunctionNode"===n)throw new Error("There is an unsolved function call");if("OperatorNode"===n)if("^"===t.op){if("ConstantNode"!==t.args[1].type||!isInteger$1(parseFloat(t.args[1].value)))throw new Error("There is a non-integer exponent");e(t.args[0])}else{if(-1===s.indexOf(t.op))throw new Error("Operator "+t.op+" invalid in polynomial expression");for(var r=0;r=1){var l,u;e=w(e);var c,m=!0,h=!1;for(e=d(e,r.firstRules,{},s);u=m?r.distrDivRules:r.sucDivRules,m=!m,(c=(e=d(e,u,{},o)).toString())!==l;)h=!0,l=c;h&&(e=d(e,r.firstRulesAgain,{},s)),e=d(e,r.finalRules,{},s)}var f=[],y={};return"OperatorNode"===e.type&&e.isBinary()&&"/"===e.op?(1===i&&(e.args[0]=E(e.args[0],f),e.args[1]=E(e.args[1])),n&&(y.numerator=e.args[0],y.denominator=e.args[1])):(1===i&&(e=E(e,f)),n&&(y.numerator=e,y.denominator=null)),n?(y.coefficients=f,y.variables=a.variables,y.expression=e,y):e}});function w(e,t,n){var r=e.type,a=arguments.length>1;if("OperatorNode"===r&&e.isBinary()){var i,s=!1;if("^"===e.op&&("ParenthesisNode"!==e.args[0].type&&"OperatorNode"!==e.args[0].type||"ConstantNode"!==e.args[1].type||(s=(i=parseFloat(e.args[1].value))>=2&&isInteger$1(i))),s){if(i>2){var o=e.args[0],l=new A("^","pow",[e.args[0].cloneDeep(),new v(i-1)]);e=new A("*","multiply",[o,l])}else e=new A("*","multiply",[e.args[0],e.args[0].cloneDeep()]);a&&("content"===n?t.content=e:t.args[n]=e)}}if("ParenthesisNode"===r)w(e.content,e,"content");else if("ConstantNode"!==r&&"SymbolNode"!==r)for(var u=0;un&&(t[u]=0),t[u]+=s.cte*("+"===s.oper?1:-1),void(n=Math.max(u,n))}s.cte=u,""===s.fire&&(t[0]+=s.cte*("+"===s.oper?1:-1))}}(e,null,{cte:1,oper:"+",fire:""});for(var a,i=!0,s=n=t.length-1;s>=0;s--)if(0!==t[s]){var o=new v(i?t[s]:Math.abs(t[s])),l=t[s]<0?"-":"+";if(s>0){var u=new V(r);if(s>1){var c=new v(s);u=new A("^","pow",[u,c])}o=-1===t[s]&&i?new A("-","unaryMinus",[u]):1===Math.abs(t[s])?u:new A("*","multiply",[o,u])}a=i?o:"+"===l?new A("+","add",[a,o]):new A("-","subtract",[a,o]),i=!1}return i?new v(0):a}})),name$j="reviver",dependencies$j=["classes"],createReviver=factory(name$j,dependencies$j,(e=>{var{classes:t}=e;return function(e,n){var r=t[n&&n.mathjs];return r&&"function"==typeof r.fromJSON?r.fromJSON(n):n}})),name$i="replacer",dependencies$i=[],createReplacer=factory(name$i,dependencies$i,(()=>function(e,t){return"number"!=typeof t||isFinite(t)&&!isNaN(t)?t:{mathjs:"number",value:String(t)}})),version$2="10.6.4",createTrue=factory("true",[],(()=>!0)),createFalse=factory("false",[],(()=>!1)),createNull=factory("null",[],(()=>null)),createInfinity=recreateFactory("Infinity",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1/0):1/0})),createNaN=recreateFactory("NaN",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(NaN):NaN})),createPi=recreateFactory("pi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPi(n):pi$1})),createTau=recreateFactory("tau",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberTau(n):tau$1})),createE=recreateFactory("e",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberE(n):e$1})),createPhi=recreateFactory("phi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPhi(n):phi$1})),createLN2=recreateFactory("LN2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).ln():Math.LN2})),createLN10=recreateFactory("LN10",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(10).ln():Math.LN10})),createLOG2E=recreateFactory("LOG2E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(2).ln()):Math.LOG2E})),createLOG10E=recreateFactory("LOG10E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(10).ln()):Math.LOG10E})),createSQRT1_2=recreateFactory("SQRT1_2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n("0.5").sqrt():Math.SQRT1_2})),createSQRT2=recreateFactory("SQRT2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).sqrt():Math.SQRT2})),createI=recreateFactory("i",["Complex"],(e=>{var{Complex:t}=e;return t.I})),createUppercasePi=factory("PI",["pi"],(e=>{var{pi:t}=e;return t})),createUppercaseE=factory("E",["e"],(e=>{var{e:t}=e;return t})),createVersion=factory("version",[],(()=>version$2));function recreateFactory(e,t,n){return factory(e,t,n,{recreateOnConfigChange:!0})}var createSpeedOfLight=unitFactory("speedOfLight","299792458","m s^-1"),createGravitationConstant=unitFactory("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),createPlanckConstant=unitFactory("planckConstant","6.62607015e-34","J s"),createReducedPlanckConstant=unitFactory("reducedPlanckConstant","1.0545718176461565e-34","J s"),createMagneticConstant=unitFactory("magneticConstant","1.25663706212e-6","N A^-2"),createElectricConstant=unitFactory("electricConstant","8.8541878128e-12","F m^-1"),createVacuumImpedance=unitFactory("vacuumImpedance","376.730313667","ohm"),createCoulomb=unitFactory("coulomb","8.987551792261171e9","N m^2 C^-2"),createElementaryCharge=unitFactory("elementaryCharge","1.602176634e-19","C"),createBohrMagneton=unitFactory("bohrMagneton","9.2740100783e-24","J T^-1"),createConductanceQuantum=unitFactory("conductanceQuantum","7.748091729863649e-5","S"),createInverseConductanceQuantum=unitFactory("inverseConductanceQuantum","12906.403729652257","ohm"),createMagneticFluxQuantum=unitFactory("magneticFluxQuantum","2.0678338484619295e-15","Wb"),createNuclearMagneton=unitFactory("nuclearMagneton","5.0507837461e-27","J T^-1"),createKlitzing=unitFactory("klitzing","25812.807459304513","ohm"),createBohrRadius=unitFactory("bohrRadius","5.29177210903e-11","m"),createClassicalElectronRadius=unitFactory("classicalElectronRadius","2.8179403262e-15","m"),createElectronMass=unitFactory("electronMass","9.1093837015e-31","kg"),createFermiCoupling=unitFactory("fermiCoupling","1.1663787e-5","GeV^-2"),createFineStructure=numberFactory("fineStructure",.0072973525693),createHartreeEnergy=unitFactory("hartreeEnergy","4.3597447222071e-18","J"),createProtonMass=unitFactory("protonMass","1.67262192369e-27","kg"),createDeuteronMass=unitFactory("deuteronMass","3.3435830926e-27","kg"),createNeutronMass=unitFactory("neutronMass","1.6749271613e-27","kg"),createQuantumOfCirculation=unitFactory("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),createRydberg=unitFactory("rydberg","10973731.568160","m^-1"),createThomsonCrossSection=unitFactory("thomsonCrossSection","6.6524587321e-29","m^2"),createWeakMixingAngle=numberFactory("weakMixingAngle",.2229),createEfimovFactor=numberFactory("efimovFactor",22.7),createAtomicMass=unitFactory("atomicMass","1.66053906660e-27","kg"),createAvogadro=unitFactory("avogadro","6.02214076e23","mol^-1"),createBoltzmann=unitFactory("boltzmann","1.380649e-23","J K^-1"),createFaraday=unitFactory("faraday","96485.33212331001","C mol^-1"),createFirstRadiation=unitFactory("firstRadiation","3.7417718521927573e-16","W m^2"),createLoschmidt=unitFactory("loschmidt","2.686780111798444e25","m^-3"),createGasConstant=unitFactory("gasConstant","8.31446261815324","J K^-1 mol^-1"),createMolarPlanckConstant=unitFactory("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),createMolarVolume=unitFactory("molarVolume","0.022413969545014137","m^3 mol^-1"),createSackurTetrode=numberFactory("sackurTetrode",-1.16487052358),createSecondRadiation=unitFactory("secondRadiation","0.014387768775039337","m K"),createStefanBoltzmann=unitFactory("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),createWienDisplacement=unitFactory("wienDisplacement","2.897771955e-3","m K"),createMolarMass=unitFactory("molarMass","0.99999999965e-3","kg mol^-1"),createMolarMassC12=unitFactory("molarMassC12","11.9999999958e-3","kg mol^-1"),createGravity=unitFactory("gravity","9.80665","m s^-2"),createPlanckLength=unitFactory("planckLength","1.616255e-35","m"),createPlanckMass=unitFactory("planckMass","2.176435e-8","kg"),createPlanckTime=unitFactory("planckTime","5.391245e-44","s"),createPlanckCharge=unitFactory("planckCharge","1.87554603778e-18","C"),createPlanckTemperature=unitFactory("planckTemperature","1.416785e+32","K");function unitFactory(e,t,n){return factory(e,["config","Unit","BigNumber"],(e=>{var{config:r,Unit:a,BigNumber:i}=e,s=new a("BigNumber"===r.number?new i(t):parseFloat(t),n);return s.fixPrefix=!0,s}))}function numberFactory(e,t){return factory(e,["config","BigNumber"],(e=>{var{config:n,BigNumber:r}=e;return"BigNumber"===n.number?new r(t):t}))}var name$h="apply",dependencies$h=["typed","isInteger"],createApplyTransform=factory(name$h,dependencies$h,(e=>{var{typed:t,isInteger:n}=e,r=createApply({typed:t,isInteger:n});return t("apply",{"...any":function(e){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1));try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$g="column",dependencies$g=["typed","Index","matrix","range"],createColumnTransform=factory(name$g,dependencies$g,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createColumn({typed:t,Index:n,matrix:r,range:a});return t("column",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0});function compileInlineExpression(e,t,n){var r=e.filter((function(e){return isSymbolNode(e)&&!(e.name in t)&&!n.has(e.name)}))[0];if(!r)throw new Error('No undefined variable found in inline expression "'+e+'"');var a=r.name,i=createSubScope(n),s=e.compile();return function(e){return i.set(a,e),s.evaluate(i)}}var name$f="filter",dependencies$f=["typed"],createFilterTransform=factory(name$f,dependencies$f,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("filter",{"Array, function":_filter,"Matrix, function":function(e,t){return e.create(_filter(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}});return n}),{isTransformFunction:!0});function _filter(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r+1]):t(e,[r+1],a)}))}var name$e="forEach",dependencies$e=["typed"],createForEachTransform=factory(name$e,dependencies$e,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("forEach",{"Array | Matrix, function":function(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t+1))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e.valueOf(),[])}});return n}),{isTransformFunction:!0}),name$d="index",dependencies$d=["Index"],createIndexTransform=factory(name$d,dependencies$d,(e=>{var{Index:t}=e;return function(){for(var e=[],n=0,r=arguments.length;n0?0:2;else if(a&&!0===a.isSet)a=a.map((function(e){return e-1}));else if(isArray$1(a)||isMatrix(a))a=a.map((function(e){return e-1}));else if(isNumber$1(a))a--;else if(isBigNumber(a))a=a.toNumber()-1;else if("string"!=typeof a)throw new TypeError("Dimension must be an Array, Matrix, number, string, or Range");e[n]=a}var i=new t;return t.apply(i,e),i}}),{isTransformFunction:!0}),name$c="map",dependencies$c=["typed"],createMapTransform=factory(name$c,dependencies$c,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("map",{"Array, function":function(e,t){return _map(e,t,e)},"Matrix, function":function(e,t){return e.create(_map(e.valueOf(),t,e))}});return n}),{isTransformFunction:!0});function _map(e,t,n){var r=maxArgumentCount(t);return function e(a,i){return Array.isArray(a)?map$2(a,(function(t,n){return e(t,i.concat(n+1))})):1===r?t(a):2===r?t(a,i):t(a,i,n)}(e,[])}function lastDimToZeroBase(e){if(2===e.length&&isCollection(e[0])){var t=(e=e.slice())[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}return e}var name$b="max",dependencies$b=["typed","config","numeric","larger"],createMaxTransform=factory(name$b,dependencies$b,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e,i=createMax({typed:t,config:n,numeric:r,larger:a});return t("max",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$a="mean",dependencies$a=["typed","add","divide"],createMeanTransform=factory(name$a,dependencies$a,(e=>{var{typed:t,add:n,divide:r}=e,a=createMean({typed:t,add:n,divide:r});return t("mean",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$9="min",dependencies$9=["typed","config","numeric","smaller"],createMinTransform=factory(name$9,dependencies$9,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e,i=createMin({typed:t,config:n,numeric:r,smaller:a});return t("min",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$8="range",dependencies$8=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRangeTransform=factory(name$8,dependencies$8,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l}=e,u=createRange({typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l});return t("range",{"...any":function(e){return"boolean"!=typeof e[e.length-1]&&e.push(!0),u.apply(null,e)}})}),{isTransformFunction:!0}),name$7="row",dependencies$7=["typed","Index","matrix","range"],createRowTransform=factory(name$7,dependencies$7,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createRow({typed:t,Index:n,matrix:r,range:a});return t("row",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$6="subset",dependencies$6=["typed","matrix"],createSubsetTransform=factory(name$6,dependencies$6,(e=>{var{typed:t,matrix:n}=e,r=createSubset({typed:t,matrix:n});return t("subset",{"...any":function(e){try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$5="concat",dependencies$5=["typed","matrix","isInteger"],createConcatTransform=factory(name$5,dependencies$5,(e=>{var{typed:t,matrix:n,isInteger:r}=e,a=createConcat({typed:t,matrix:n,isInteger:r});return t("concat",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)?e[t]=n-1:isBigNumber(n)&&(e[t]=n.minus(1));try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$4="diff",dependencies$4=["typed","matrix","subtract","number","bignumber"],createDiffTransform=factory(name$4,dependencies$4,(e=>{var{typed:t,matrix:n,subtract:r,number:a,bignumber:i}=e,s=createDiff({typed:t,matrix:n,subtract:r,number:a,bignumber:i});return t(name$4,{"...any":function(e){e=lastDimToZeroBase(e);try{return s.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$3="std",dependencies$3=["typed","sqrt","variance"],createStdTransform=factory(name$3,dependencies$3,(e=>{var{typed:t,sqrt:n,variance:r}=e,a=createStd({typed:t,sqrt:n,variance:r});return t("std",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$2="sum",dependencies$2=["typed","config","add","numeric"],createSumTransform=factory(name$2,dependencies$2,(e=>{var{typed:t,config:n,add:r,numeric:a}=e,i=createSum({typed:t,config:n,add:r,numeric:a});return t(name$2,{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$1="cumsum",dependencies$1=["typed","add","unaryPlus"],createCumSumTransform=factory(name$1,dependencies$1,(e=>{var{typed:t,add:n,unaryPlus:r}=e,a=createCumSum({typed:t,add:n,unaryPlus:r});return t(name$1,{"...any":function(e){if(2===e.length&&isCollection(e[0])){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name="variance",dependencies=["typed","add","subtract","multiply","divide","apply","isNaN"],createVarianceTransform=factory(name,dependencies,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o}=e,l=createVariance({typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o});return t(name,{"...any":function(e){e=lastDimToZeroBase(e);try{return l.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),allFactories=Object.freeze({__proto__:null,createTyped:createTyped,createResultSet:createResultSet,createBigNumberClass:createBigNumberClass,createComplexClass:createComplexClass,createFractionClass:createFractionClass,createRangeClass:createRangeClass,createMatrixClass:createMatrixClass,createDenseMatrixClass:createDenseMatrixClass,createClone:createClone,createIsInteger:createIsInteger,createIsNegative:createIsNegative,createIsNumeric:createIsNumeric,createHasNumericValue:createHasNumericValue,createIsPositive:createIsPositive,createIsZero:createIsZero,createIsNaN:createIsNaN,createTypeOf:createTypeOf,createEqualScalar:createEqualScalar,createSparseMatrixClass:createSparseMatrixClass,createNumber:createNumber,createString:createString,createBoolean:createBoolean,createBignumber:createBignumber,createComplex:createComplex,createFraction:createFraction,createMatrix:createMatrix,createMatrixFromFunction:createMatrixFromFunction,createMatrixFromRows:createMatrixFromRows,createMatrixFromColumns:createMatrixFromColumns,createSplitUnit:createSplitUnit,createUnaryMinus:createUnaryMinus,createUnaryPlus:createUnaryPlus,createAbs:createAbs,createApply:createApply,createAddScalar:createAddScalar,createCbrt:createCbrt,createCeil:createCeil,createCube:createCube,createExp:createExp,createExpm1:createExpm1,createFix:createFix,createFloor:createFloor,createGcd:createGcd,createLcm:createLcm,createLog10:createLog10,createLog2:createLog2,createMod:createMod,createMultiplyScalar:createMultiplyScalar,createMultiply:createMultiply,createNthRoot:createNthRoot,createSign:createSign,createSqrt:createSqrt,createSquare:createSquare,createSubtract:createSubtract,createXgcd:createXgcd,createInvmod:createInvmod,createDotMultiply:createDotMultiply,createBitAnd:createBitAnd,createBitNot:createBitNot,createBitOr:createBitOr,createBitXor:createBitXor,createArg:createArg,createConj:createConj,createIm:createIm,createRe:createRe,createNot:createNot,createOr:createOr,createXor:createXor,createConcat:createConcat,createColumn:createColumn,createCount:createCount,createCross:createCross,createDiag:createDiag,createFilter:createFilter,createFlatten:createFlatten,createForEach:createForEach,createGetMatrixDataType:createGetMatrixDataType,createIdentity:createIdentity,createKron:createKron,createMap:createMap,createDiff:createDiff,createOnes:createOnes,createRange:createRange,createReshape:createReshape,createResize:createResize,createRotate:createRotate,createRotationMatrix:createRotationMatrix,createRow:createRow,createSize:createSize,createSqueeze:createSqueeze,createSubset:createSubset,createTranspose:createTranspose,createCtranspose:createCtranspose,createZeros:createZeros,createFft:createFft,createIfft:createIfft,createErf:createErf,createMode:createMode,createProd:createProd,createFormat:createFormat,createBin:createBin,createOct:createOct,createHex:createHex,createPrint:createPrint,createTo:createTo,createIsPrime:createIsPrime,createNumeric:createNumeric,createDivideScalar:createDivideScalar,createPow:createPow,createRound:createRound,createLog:createLog,createLog1p:createLog1p,createNthRoots:createNthRoots,createDotPow:createDotPow,createDotDivide:createDotDivide,createLsolve:createLsolve,createUsolve:createUsolve,createLsolveAll:createLsolveAll,createUsolveAll:createUsolveAll,createLeftShift:createLeftShift,createRightArithShift:createRightArithShift,createRightLogShift:createRightLogShift,createAnd:createAnd,createCompare:createCompare,createCompareNatural:createCompareNatural,createCompareText:createCompareText,createEqual:createEqual,createEqualText:createEqualText,createSmaller:createSmaller,createSmallerEq:createSmallerEq,createLarger:createLarger,createLargerEq:createLargerEq,createDeepEqual:createDeepEqual,createUnequal:createUnequal,createPartitionSelect:createPartitionSelect,createSort:createSort,createMax:createMax,createMin:createMin,createImmutableDenseMatrixClass:createImmutableDenseMatrixClass,createIndexClass:createIndexClass,createFibonacciHeapClass:createFibonacciHeapClass,createSpaClass:createSpaClass,createUnitClass:createUnitClass,createUnitFunction:createUnitFunction,createSparse:createSparse,createCreateUnit:createCreateUnit,createAcos:createAcos,createAcosh:createAcosh,createAcot:createAcot,createAcoth:createAcoth,createAcsc:createAcsc,createAcsch:createAcsch,createAsec:createAsec,createAsech:createAsech,createAsin:createAsin,createAsinh:createAsinh,createAtan:createAtan,createAtan2:createAtan2,createAtanh:createAtanh,createCos:createCos,createCosh:createCosh,createCot:createCot,createCoth:createCoth,createCsc:createCsc,createCsch:createCsch,createSec:createSec,createSech:createSech,createSin:createSin,createSinh:createSinh,createTan:createTan,createTanh:createTanh,createSetCartesian:createSetCartesian,createSetDifference:createSetDifference,createSetDistinct:createSetDistinct,createSetIntersect:createSetIntersect,createSetIsSubset:createSetIsSubset,createSetMultiplicity:createSetMultiplicity,createSetPowerset:createSetPowerset,createSetSize:createSetSize,createSetSymDifference:createSetSymDifference,createSetUnion:createSetUnion,createAdd:createAdd,createHypot:createHypot,createNorm:createNorm,createDot:createDot,createTrace:createTrace,createIndex:createIndex,createNode:createNode,createAccessorNode:createAccessorNode,createArrayNode:createArrayNode,createAssignmentNode:createAssignmentNode,createBlockNode:createBlockNode,createConditionalNode:createConditionalNode,createConstantNode:createConstantNode,createFunctionAssignmentNode:createFunctionAssignmentNode,createIndexNode:createIndexNode,createObjectNode:createObjectNode,createOperatorNode:createOperatorNode,createParenthesisNode:createParenthesisNode,createRangeNode:createRangeNode,createRelationalNode:createRelationalNode,createSymbolNode:createSymbolNode,createFunctionNode:createFunctionNode,createParse:createParse,createCompile:createCompile,createEvaluate:createEvaluate,createParserClass:createParserClass,createParser:createParser,createLup:createLup,createQr:createQr,createSlu:createSlu,createLusolve:createLusolve,createHelpClass:createHelpClass,createChainClass:createChainClass,createHelp:createHelp,createChain:createChain,createDet:createDet,createInv:createInv,createPinv:createPinv,createEigs:createEigs,createExpm:createExpm,createSqrtm:createSqrtm,createDivide:createDivide,createDistance:createDistance,createIntersect:createIntersect,createSum:createSum,createCumSum:createCumSum,createMean:createMean,createMedian:createMedian,createMad:createMad,createVariance:createVariance,createQuantileSeq:createQuantileSeq,createStd:createStd,createCombinations:createCombinations,createCombinationsWithRep:createCombinationsWithRep,createGamma:createGamma,createLgamma:createLgamma,createFactorial:createFactorial,createKldivergence:createKldivergence,createMultinomial:createMultinomial,createPermutations:createPermutations,createPickRandom:createPickRandom,createRandom:createRandom,createRandomInt:createRandomInt,createStirlingS2:createStirlingS2,createBellNumbers:createBellNumbers,createCatalan:createCatalan,createComposition:createComposition,createLeafCount:createLeafCount,createSimplify:createSimplify,createSimplifyCore:createSimplifyCore,createResolve:createResolve,createSymbolicEqual:createSymbolicEqual,createDerivative:createDerivative,createRationalize:createRationalize,createReviver:createReviver,createReplacer:createReplacer,createE:createE,createUppercaseE:createUppercaseE,createFalse:createFalse,createI:createI,createInfinity:createInfinity,createLN10:createLN10,createLN2:createLN2,createLOG10E:createLOG10E,createLOG2E:createLOG2E,createNaN:createNaN,createNull:createNull,createPhi:createPhi,createPi:createPi,createUppercasePi:createUppercasePi,createSQRT1_2:createSQRT1_2,createSQRT2:createSQRT2,createTau:createTau,createTrue:createTrue,createVersion:createVersion,createAtomicMass:createAtomicMass,createAvogadro:createAvogadro,createBohrMagneton:createBohrMagneton,createBohrRadius:createBohrRadius,createBoltzmann:createBoltzmann,createClassicalElectronRadius:createClassicalElectronRadius,createConductanceQuantum:createConductanceQuantum,createCoulomb:createCoulomb,createDeuteronMass:createDeuteronMass,createEfimovFactor:createEfimovFactor,createElectricConstant:createElectricConstant,createElectronMass:createElectronMass,createElementaryCharge:createElementaryCharge,createFaraday:createFaraday,createFermiCoupling:createFermiCoupling,createFineStructure:createFineStructure,createFirstRadiation:createFirstRadiation,createGasConstant:createGasConstant,createGravitationConstant:createGravitationConstant,createGravity:createGravity,createHartreeEnergy:createHartreeEnergy,createInverseConductanceQuantum:createInverseConductanceQuantum,createKlitzing:createKlitzing,createLoschmidt:createLoschmidt,createMagneticConstant:createMagneticConstant,createMagneticFluxQuantum:createMagneticFluxQuantum,createMolarMass:createMolarMass,createMolarMassC12:createMolarMassC12,createMolarPlanckConstant:createMolarPlanckConstant,createMolarVolume:createMolarVolume,createNeutronMass:createNeutronMass,createNuclearMagneton:createNuclearMagneton,createPlanckCharge:createPlanckCharge,createPlanckConstant:createPlanckConstant,createPlanckLength:createPlanckLength,createPlanckMass:createPlanckMass,createPlanckTemperature:createPlanckTemperature,createPlanckTime:createPlanckTime,createProtonMass:createProtonMass,createQuantumOfCirculation:createQuantumOfCirculation,createReducedPlanckConstant:createReducedPlanckConstant,createRydberg:createRydberg,createSackurTetrode:createSackurTetrode,createSecondRadiation:createSecondRadiation,createSpeedOfLight:createSpeedOfLight,createStefanBoltzmann:createStefanBoltzmann,createThomsonCrossSection:createThomsonCrossSection,createVacuumImpedance:createVacuumImpedance,createWeakMixingAngle:createWeakMixingAngle,createWienDisplacement:createWienDisplacement,createApplyTransform:createApplyTransform,createColumnTransform:createColumnTransform,createFilterTransform:createFilterTransform,createForEachTransform:createForEachTransform,createIndexTransform:createIndexTransform,createMapTransform:createMapTransform,createMaxTransform:createMaxTransform,createMeanTransform:createMeanTransform,createMinTransform:createMinTransform,createRangeTransform:createRangeTransform,createRowTransform:createRowTransform,createSubsetTransform:createSubsetTransform,createConcatTransform:createConcatTransform,createDiffTransform:createDiffTransform,createStdTransform:createStdTransform,createSumTransform:createSumTransform,createCumSumTransform:createCumSumTransform,createVarianceTransform:createVarianceTransform}),BigNumber=createBigNumberClass({config:config$2}),Complex=createComplexClass({}),e=createE({BigNumber:BigNumber,config:config$2}),_false=createFalse({}),fineStructure=createFineStructure({BigNumber:BigNumber,config:config$2}),Fraction=createFractionClass({}),i=createI({Complex:Complex}),_Infinity=createInfinity({BigNumber:BigNumber,config:config$2}),LN10=createLN10({BigNumber:BigNumber,config:config$2}),LOG10E=createLOG10E({BigNumber:BigNumber,config:config$2}),Matrix=createMatrixClass({}),_NaN=createNaN({BigNumber:BigNumber,config:config$2}),_null=createNull({}),phi=createPhi({BigNumber:BigNumber,config:config$2}),Range=createRangeClass({}),ResultSet=createResultSet({}),SQRT1_2=createSQRT1_2({BigNumber:BigNumber,config:config$2}),sackurTetrode=createSackurTetrode({BigNumber:BigNumber,config:config$2}),tau=createTau({BigNumber:BigNumber,config:config$2}),_true=createTrue({}),version$1=createVersion({}),DenseMatrix=createDenseMatrixClass({Matrix:Matrix}),efimovFactor=createEfimovFactor({BigNumber:BigNumber,config:config$2}),LN2=createLN2({BigNumber:BigNumber,config:config$2}),pi=createPi({BigNumber:BigNumber,config:config$2}),replacer=createReplacer({}),SQRT2=createSQRT2({BigNumber:BigNumber,config:config$2}),typed=createTyped({BigNumber:BigNumber,Complex:Complex,DenseMatrix:DenseMatrix,Fraction:Fraction}),unaryPlus=createUnaryPlus({BigNumber:BigNumber,config:config$2,typed:typed}),weakMixingAngle=createWeakMixingAngle({BigNumber:BigNumber,config:config$2}),abs$1=createAbs({typed:typed}),acos$1=createAcos({Complex:Complex,config:config$2,typed:typed}),acot$1=createAcot({BigNumber:BigNumber,typed:typed}),acsc$1=createAcsc({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),addScalar=createAddScalar({typed:typed}),arg=createArg({typed:typed}),asech$1=createAsech({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),asinh$1=createAsinh({typed:typed}),atan$1=createAtan({typed:typed}),atanh$1=createAtanh({Complex:Complex,config:config$2,typed:typed}),bignumber=createBignumber({BigNumber:BigNumber,typed:typed}),bitNot=createBitNot({typed:typed}),boolean=createBoolean({typed:typed}),clone$1=createClone({typed:typed}),combinations=createCombinations({typed:typed}),complex=createComplex({Complex:Complex,typed:typed}),conj$1=createConj({typed:typed}),cosh$1=createCosh({typed:typed}),coth$1=createCoth({BigNumber:BigNumber,typed:typed}),csc$1=createCsc({BigNumber:BigNumber,typed:typed}),cube=createCube({typed:typed}),equalScalar=createEqualScalar({config:config$2,typed:typed}),erf$1=createErf({typed:typed}),exp$1=createExp({typed:typed}),expm1=createExpm1({Complex:Complex,typed:typed}),filter$1=createFilter({typed:typed}),forEach=createForEach({typed:typed}),format=createFormat({typed:typed}),getMatrixDataType=createGetMatrixDataType({typed:typed}),hex=createHex({format:format,typed:typed}),im$1=createIm({typed:typed}),isInteger=createIsInteger({typed:typed}),isNegative=createIsNegative({typed:typed}),isPositive=createIsPositive({typed:typed}),isZero=createIsZero({typed:typed}),LOG2E=createLOG2E({BigNumber:BigNumber,config:config$2}),lgamma=createLgamma({Complex:Complex,typed:typed}),log10$1=createLog10({Complex:Complex,config:config$2,typed:typed}),log2=createLog2({Complex:Complex,config:config$2,typed:typed}),map$1=createMap({typed:typed}),multiplyScalar=createMultiplyScalar({typed:typed}),not=createNot({typed:typed}),number=createNumber({typed:typed}),oct=createOct({format:format,typed:typed}),pickRandom=createPickRandom({config:config$2,typed:typed}),print=createPrint({typed:typed}),random$1=createRandom({config:config$2,typed:typed}),re$1=createRe({typed:typed}),sec$1=createSec({BigNumber:BigNumber,typed:typed}),sign$1=createSign({BigNumber:BigNumber,Fraction:Fraction,complex:complex,typed:typed}),sin$1=createSin({typed:typed}),SparseMatrix=createSparseMatrixClass({Matrix:Matrix,equalScalar:equalScalar,typed:typed}),splitUnit=createSplitUnit({typed:typed}),square=createSquare({typed:typed}),string=createString({typed:typed}),tan$1=createTan({typed:typed}),typeOf=createTypeOf({typed:typed}),acosh$1=createAcosh({Complex:Complex,config:config$2,typed:typed}),acsch$1=createAcsch({BigNumber:BigNumber,typed:typed}),apply=createApply({isInteger:isInteger,typed:typed}),asec$1=createAsec({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),bin=createBin({format:format,typed:typed}),combinationsWithRep=createCombinationsWithRep({typed:typed}),cos$1=createCos({typed:typed}),csch$1=createCsch({BigNumber:BigNumber,typed:typed}),isNaN$2=createIsNaN({typed:typed}),isPrime=createIsPrime({typed:typed}),randomInt=createRandomInt({config:config$2,typed:typed}),sech$1=createSech({BigNumber:BigNumber,typed:typed}),sinh$1=createSinh({typed:typed}),sparse=createSparse({SparseMatrix:SparseMatrix,typed:typed}),sqrt$1=createSqrt({Complex:Complex,config:config$2,typed:typed}),tanh$1=createTanh({typed:typed}),unaryMinus=createUnaryMinus({typed:typed}),acoth$1=createAcoth({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),cot$1=createCot({BigNumber:BigNumber,typed:typed}),fraction=createFraction({Fraction:Fraction,typed:typed}),isNumeric=createIsNumeric({typed:typed}),matrix$2=createMatrix({DenseMatrix:DenseMatrix,Matrix:Matrix,SparseMatrix:SparseMatrix,typed:typed}),matrixFromFunction=createMatrixFromFunction({isZero:isZero,matrix:matrix$2,typed:typed}),mod$1=createMod({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),nthRoot=createNthRoot({BigNumber:BigNumber,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),numeric=createNumeric({bignumber:bignumber,fraction:fraction,number:number}),or=createOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),prod=createProd({config:config$2,multiplyScalar:multiplyScalar,numeric:numeric,typed:typed}),reshape=createReshape({isInteger:isInteger,matrix:matrix$2,typed:typed}),size$1=createSize({matrix:matrix$2,config:config$2,typed:typed}),smaller=createSmaller({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),squeeze=createSqueeze({matrix:matrix$2,typed:typed}),subset=createSubset({matrix:matrix$2,typed:typed}),subtract$1=createSubtract({DenseMatrix:DenseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),to=createTo({matrix:matrix$2,typed:typed}),transpose=createTranspose({matrix:matrix$2,typed:typed}),xgcd=createXgcd({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),zeros=createZeros({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),and=createAnd({equalScalar:equalScalar,matrix:matrix$2,not:not,typed:typed,zeros:zeros}),bitAnd=createBitAnd({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitXor=createBitXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),cbrt=createCbrt({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,config:config$2,isNegative:isNegative,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),compare=createCompare({BigNumber:BigNumber,DenseMatrix:DenseMatrix,Fraction:Fraction,config:config$2,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),compareText=createCompareText({matrix:matrix$2,typed:typed}),concat=createConcat({isInteger:isInteger,matrix:matrix$2,typed:typed}),count=createCount({prod:prod,size:size$1,typed:typed}),ctranspose=createCtranspose({conj:conj$1,transpose:transpose,typed:typed}),diag=createDiag({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,matrix:matrix$2,typed:typed}),divideScalar=createDivideScalar({numeric:numeric,typed:typed}),dotDivide=createDotDivide({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),equal$1=createEqual({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),fft=createFft({addScalar:addScalar,divideScalar:divideScalar,exp:exp$1,i:i,matrix:matrix$2,multiplyScalar:multiplyScalar,tau:tau,typed:typed}),flatten$3=createFlatten({matrix:matrix$2,typed:typed}),gcd=createGcd({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),hasNumericValue=createHasNumericValue({isNumeric:isNumeric,typed:typed}),hypot=createHypot({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,isPositive:isPositive,multiplyScalar:multiplyScalar,smaller:smaller,sqrt:sqrt$1,typed:typed}),ifft=createIfft({conj:conj$1,dotDivide:dotDivide,fft:fft,typed:typed}),kron=createKron({matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),largerEq=createLargerEq({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),leftShift=createLeftShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),lsolve=createLsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromColumns=createMatrixFromColumns({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),min$1=createMin({config:config$2,numeric:numeric,smaller:smaller,typed:typed}),mode=createMode({isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),nthRoots=createNthRoots({Complex:Complex,config:config$2,divideScalar:divideScalar,typed:typed}),ones=createOnes({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),partitionSelect=createPartitionSelect({compare:compare,isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),resize=createResize({config:config$2,matrix:matrix$2}),rightArithShift=createRightArithShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),round$1=createRound({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),smallerEq=createSmallerEq({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),unequal=createUnequal({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),usolve=createUsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),xor=createXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),add$1=createAdd({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),atan2$1=createAtan2({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitOr=createBitOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),catalan=createCatalan({addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,isInteger:isInteger,isNegative:isNegative,multiplyScalar:multiplyScalar,typed:typed}),compareNatural=createCompareNatural({compare:compare,typed:typed}),cumsum=createCumSum({add:add$1,typed:typed,unaryPlus:unaryPlus}),deepEqual=createDeepEqual({equal:equal$1,typed:typed}),diff=createDiff({matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),dot=createDot({addScalar:addScalar,conj:conj$1,multiplyScalar:multiplyScalar,size:size$1,typed:typed}),equalText=createEqualText({compareText:compareText,isZero:isZero,typed:typed}),floor=createFloor({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),identity$1=createIdentity({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,config:config$2,matrix:matrix$2,typed:typed}),invmod=createInvmod({BigNumber:BigNumber,add:add$1,config:config$2,equal:equal$1,isInteger:isInteger,mod:mod$1,smaller:smaller,typed:typed,xgcd:xgcd}),larger=createLarger({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),log$1=createLog({Complex:Complex,config:config$2,divideScalar:divideScalar,typed:typed}),lsolveAll=createLsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromRows=createMatrixFromRows({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),multiply$1=createMultiply({addScalar:addScalar,dot:dot,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),qr=createQr({addScalar:addScalar,complex:complex,conj:conj$1,divideScalar:divideScalar,equal:equal$1,identity:identity$1,isZero:isZero,matrix:matrix$2,multiplyScalar:multiplyScalar,sign:sign$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus,zeros:zeros}),range$1=createRange({bignumber:bignumber,matrix:matrix$2,config:config$2,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),rightLogShift=createRightLogShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),setSize=createSetSize({compareNatural:compareNatural,typed:typed}),slu=createSlu({SparseMatrix:SparseMatrix,abs:abs$1,add:add$1,divideScalar:divideScalar,larger:larger,largerEq:largerEq,multiply:multiply$1,subtract:subtract$1,transpose:transpose,typed:typed}),sum=createSum({add:add$1,config:config$2,numeric:numeric,typed:typed}),trace=createTrace({add:add$1,matrix:matrix$2,typed:typed}),usolveAll=createUsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),asin$1=createAsin({Complex:Complex,config:config$2,typed:typed}),ceil=createCeil({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),composition=createComposition({addScalar:addScalar,combinations:combinations,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,larger:larger,typed:typed}),cross=createCross({matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),det=createDet({divideScalar:divideScalar,isZero:isZero,matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),distance=createDistance({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,multiplyScalar:multiplyScalar,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),dotMultiply=createDotMultiply({equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),FibonacciHeap=createFibonacciHeapClass({larger:larger,smaller:smaller}),fix=createFix({Complex:Complex,DenseMatrix:DenseMatrix,ceil:ceil,equalScalar:equalScalar,floor:floor,matrix:matrix$2,typed:typed,zeros:zeros}),ImmutableDenseMatrix=createImmutableDenseMatrixClass({DenseMatrix:DenseMatrix,smaller:smaller}),Index=createIndexClass({ImmutableDenseMatrix:ImmutableDenseMatrix}),intersect=createIntersect({abs:abs$1,add:add$1,addScalar:addScalar,config:config$2,divideScalar:divideScalar,equalScalar:equalScalar,flatten:flatten$3,isNumeric:isNumeric,isZero:isZero,matrix:matrix$2,multiply:multiply$1,multiplyScalar:multiplyScalar,smaller:smaller,subtract:subtract$1,typed:typed}),lcm=createLcm({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),log1p=createLog1p({Complex:Complex,config:config$2,divideScalar:divideScalar,log:log$1,typed:typed}),max$1=createMax({config:config$2,larger:larger,numeric:numeric,typed:typed}),quantileSeq=createQuantileSeq({add:add$1,compare:compare,multiply:multiply$1,partitionSelect:partitionSelect,typed:typed}),row=createRow({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),setCartesian=createSetCartesian({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setDistinct=createSetDistinct({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setIsSubset=createSetIsSubset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setPowerset=createSetPowerset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),sort=createSort({compare:compare,compareNatural:compareNatural,matrix:matrix$2,typed:typed}),column=createColumn({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index=createIndex({Index:Index,typed:typed}),inv=createInv({abs:abs$1,addScalar:addScalar,det:det,divideScalar:divideScalar,identity:identity$1,matrix:matrix$2,multiply:multiply$1,typed:typed,unaryMinus:unaryMinus}),pinv=createPinv({Complex:Complex,add:add$1,ctranspose:ctranspose,deepEqual:deepEqual,divideScalar:divideScalar,dot:dot,dotDivide:dotDivide,equal:equal$1,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),pow$1=createPow({Complex:Complex,config:config$2,fraction:fraction,identity:identity$1,inv:inv,matrix:matrix$2,multiply:multiply$1,number:number,typed:typed}),setDifference=createSetDifference({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setMultiplicity=createSetMultiplicity({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),Spa=createSpaClass({FibonacciHeap:FibonacciHeap,addScalar:addScalar,equalScalar:equalScalar}),sqrtm=createSqrtm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,max:max$1,multiply:multiply$1,size:size$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed}),Unit=createUnitClass({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,abs:abs$1,addScalar:addScalar,config:config$2,divideScalar:divideScalar,equal:equal$1,fix:fix,format:format,isNumeric:isNumeric,multiplyScalar:multiplyScalar,number:number,pow:pow$1,round:round$1,subtract:subtract$1}),vacuumImpedance=createVacuumImpedance({BigNumber:BigNumber,Unit:Unit,config:config$2}),wienDisplacement=createWienDisplacement({BigNumber:BigNumber,Unit:Unit,config:config$2}),atomicMass=createAtomicMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),bohrMagneton=createBohrMagneton({BigNumber:BigNumber,Unit:Unit,config:config$2}),boltzmann=createBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$2}),conductanceQuantum=createConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),createUnit=createCreateUnit({Unit:Unit,typed:typed}),deuteronMass=createDeuteronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),dotPow=createDotPow({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,pow:pow$1,typed:typed}),electricConstant=createElectricConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),elementaryCharge=createElementaryCharge({BigNumber:BigNumber,Unit:Unit,config:config$2}),expm=createExpm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,multiply:multiply$1,typed:typed}),faraday=createFaraday({BigNumber:BigNumber,Unit:Unit,config:config$2}),firstRadiation=createFirstRadiation({BigNumber:BigNumber,Unit:Unit,config:config$2}),gamma$1=createGamma({BigNumber:BigNumber,Complex:Complex,config:config$2,multiplyScalar:multiplyScalar,pow:pow$1,typed:typed}),gravitationConstant=createGravitationConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),hartreeEnergy=createHartreeEnergy({BigNumber:BigNumber,Unit:Unit,config:config$2}),klitzing=createKlitzing({BigNumber:BigNumber,Unit:Unit,config:config$2}),loschmidt=createLoschmidt({BigNumber:BigNumber,Unit:Unit,config:config$2}),magneticConstant=createMagneticConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarMass=createMolarMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarPlanckConstant=createMolarPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),neutronMass=createNeutronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),nuclearMagneton=createNuclearMagneton({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckCharge=createPlanckCharge({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckLength=createPlanckLength({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckTemperature=createPlanckTemperature({BigNumber:BigNumber,Unit:Unit,config:config$2}),protonMass=createProtonMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),reducedPlanckConstant=createReducedPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),rydberg=createRydberg({BigNumber:BigNumber,Unit:Unit,config:config$2}),setIntersect=createSetIntersect({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),speedOfLight=createSpeedOfLight({BigNumber:BigNumber,Unit:Unit,config:config$2}),stefanBoltzmann=createStefanBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$2}),thomsonCrossSection=createThomsonCrossSection({BigNumber:BigNumber,Unit:Unit,config:config$2}),avogadro=createAvogadro({BigNumber:BigNumber,Unit:Unit,config:config$2}),bohrRadius=createBohrRadius({BigNumber:BigNumber,Unit:Unit,config:config$2}),coulomb=createCoulomb({BigNumber:BigNumber,Unit:Unit,config:config$2}),divide$1=createDivide({divideScalar:divideScalar,equalScalar:equalScalar,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),electronMass=createElectronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),factorial$1=createFactorial({gamma:gamma$1,typed:typed}),gravity=createGravity({BigNumber:BigNumber,Unit:Unit,config:config$2}),inverseConductanceQuantum=createInverseConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),lup=createLup({DenseMatrix:DenseMatrix,Spa:Spa,SparseMatrix:SparseMatrix,abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),magneticFluxQuantum=createMagneticFluxQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarMassC12=createMolarMassC12({BigNumber:BigNumber,Unit:Unit,config:config$2}),multinomial=createMultinomial({add:add$1,divide:divide$1,factorial:factorial$1,isInteger:isInteger,isPositive:isPositive,multiply:multiply$1,typed:typed}),permutations=createPermutations({factorial:factorial$1,typed:typed}),planckMass=createPlanckMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),quantumOfCirculation=createQuantumOfCirculation({BigNumber:BigNumber,Unit:Unit,config:config$2}),secondRadiation=createSecondRadiation({BigNumber:BigNumber,Unit:Unit,config:config$2}),stirlingS2=createStirlingS2({bignumber:bignumber,addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,factorial:factorial$1,isInteger:isInteger,isNegative:isNegative,larger:larger,multiplyScalar:multiplyScalar,number:number,pow:pow$1,subtract:subtract$1,typed:typed}),unit=createUnitFunction({Unit:Unit,typed:typed}),bellNumbers=createBellNumbers({addScalar:addScalar,isInteger:isInteger,isNegative:isNegative,stirlingS2:stirlingS2,typed:typed}),eigs=createEigs({abs:abs$1,add:add$1,addScalar:addScalar,atan:atan$1,bignumber:bignumber,column:column,complex:complex,config:config$2,cos:cos$1,diag:diag,divideScalar:divideScalar,dot:dot,equal:equal$1,flatten:flatten$3,im:im$1,inv:inv,larger:larger,matrix:matrix$2,matrixFromColumns:matrixFromColumns,multiply:multiply$1,multiplyScalar:multiplyScalar,number:number,qr:qr,re:re$1,sin:sin$1,smaller:smaller,sqrt:sqrt$1,subtract:subtract$1,typed:typed,usolve:usolve,usolveAll:usolveAll}),fermiCoupling=createFermiCoupling({BigNumber:BigNumber,Unit:Unit,config:config$2}),mean=createMean({add:add$1,divide:divide$1,typed:typed}),molarVolume=createMolarVolume({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckConstant=createPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),setSymDifference=createSetSymDifference({Index:Index,concat:concat,setDifference:setDifference,size:size$1,subset:subset,typed:typed}),classicalElectronRadius=createClassicalElectronRadius({BigNumber:BigNumber,Unit:Unit,config:config$2}),lusolve=createLusolve({DenseMatrix:DenseMatrix,lsolve:lsolve,lup:lup,matrix:matrix$2,slu:slu,typed:typed,usolve:usolve}),median=createMedian({add:add$1,compare:compare,divide:divide$1,partitionSelect:partitionSelect,typed:typed}),setUnion=createSetUnion({Index:Index,concat:concat,setIntersect:setIntersect,setSymDifference:setSymDifference,size:size$1,subset:subset,typed:typed}),variance=createVariance({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),kldivergence=createKldivergence({divide:divide$1,dotDivide:dotDivide,isNumeric:isNumeric,log:log$1,matrix:matrix$2,multiply:multiply$1,sum:sum,typed:typed}),norm=createNorm({abs:abs$1,add:add$1,conj:conj$1,ctranspose:ctranspose,eigs:eigs,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiply:multiply$1,pow:pow$1,smaller:smaller,sqrt:sqrt$1,typed:typed}),planckTime=createPlanckTime({BigNumber:BigNumber,Unit:Unit,config:config$2}),rotationMatrix=createRotationMatrix({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,config:config$2,cos:cos$1,matrix:matrix$2,multiplyScalar:multiplyScalar,norm:norm,sin:sin$1,typed:typed,unaryMinus:unaryMinus}),gasConstant=createGasConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),std=createStd({sqrt:sqrt$1,typed:typed,variance:variance}),mad=createMad({abs:abs$1,map:map$1,median:median,subtract:subtract$1,typed:typed}),rotate=createRotate({multiply:multiply$1,rotationMatrix:rotationMatrix,typed:typed}),math$2={},mathWithTransform={},classes={},Chain=createChainClass({math:math$2}),Node=createNode({mathWithTransform:mathWithTransform}),ObjectNode=createObjectNode({Node:Node}),OperatorNode=createOperatorNode({Node:Node}),ParenthesisNode=createParenthesisNode({Node:Node}),RelationalNode=createRelationalNode({Node:Node}),ArrayNode=createArrayNode({Node:Node}),BlockNode=createBlockNode({Node:Node,ResultSet:ResultSet}),ConditionalNode=createConditionalNode({Node:Node}),ConstantNode=createConstantNode({Node:Node}),RangeNode=createRangeNode({Node:Node}),reviver=createReviver({classes:classes}),chain$1=createChain({Chain:Chain,typed:typed}),FunctionAssignmentNode=createFunctionAssignmentNode({Node:Node,typed:typed}),AccessorNode=createAccessorNode({Node:Node,subset:subset}),AssignmentNode=createAssignmentNode({matrix:matrix$2,Node:Node,subset:subset}),IndexNode=createIndexNode({Node:Node,size:size$1}),SymbolNode=createSymbolNode({Unit:Unit,Node:Node,math:math$2}),FunctionNode=createFunctionNode({Node:Node,SymbolNode:SymbolNode,math:math$2}),parse$2=createParse({AccessorNode:AccessorNode,ArrayNode:ArrayNode,AssignmentNode:AssignmentNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,FunctionAssignmentNode:FunctionAssignmentNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,RangeNode:RangeNode,RelationalNode:RelationalNode,SymbolNode:SymbolNode,config:config$2,numeric:numeric,typed:typed}),resolve=createResolve({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,parse:parse$2}),simplifyCore=createSimplifyCore({AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,divide:divide$1,equal:equal$1,isZero:isZero,multiply:multiply$1,pow:pow$1,subtract:subtract$1}),compile=createCompile({parse:parse$2,typed:typed}),Help=createHelpClass({parse:parse$2}),leafCount=createLeafCount({parse:parse$2,typed:typed}),simplify$2=createSimplify({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$2,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,resolve:resolve,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),symbolicEqual=createSymbolicEqual({OperatorNode:OperatorNode,parse:parse$2,simplify:simplify$2,typed:typed}),evaluate$1=createEvaluate({parse:parse$2,typed:typed}),help=createHelp({Help:Help,mathWithTransform:mathWithTransform,typed:typed}),Parser=createParserClass({evaluate:evaluate$1}),rationalize=createRationalize({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$2,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,simplify:simplify$2,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),derivative$1=createDerivative({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,config:config$2,equal:equal$1,isZero:isZero,numeric:numeric,parse:parse$2,simplify:simplify$2,typed:typed}),parser=createParser({Parser:Parser,typed:typed});_extends$1(math$2,{e:e,false:_false,fineStructure:fineStructure,i:i,Infinity:_Infinity,LN10:LN10,LOG10E:LOG10E,NaN:_NaN,null:_null,phi:phi,SQRT1_2:SQRT1_2,sackurTetrode:sackurTetrode,tau:tau,true:_true,E:e,version:version$1,efimovFactor:efimovFactor,LN2:LN2,pi:pi,replacer:replacer,reviver:reviver,SQRT2:SQRT2,typed:typed,unaryPlus:unaryPlus,PI:pi,weakMixingAngle:weakMixingAngle,abs:abs$1,acos:acos$1,acot:acot$1,acsc:acsc$1,addScalar:addScalar,arg:arg,asech:asech$1,asinh:asinh$1,atan:atan$1,atanh:atanh$1,bignumber:bignumber,bitNot:bitNot,boolean:boolean,chain:chain$1,clone:clone$1,combinations:combinations,complex:complex,conj:conj$1,cosh:cosh$1,coth:coth$1,csc:csc$1,cube:cube,equalScalar:equalScalar,erf:erf$1,exp:exp$1,expm1:expm1,filter:filter$1,forEach:forEach,format:format,getMatrixDataType:getMatrixDataType,hex:hex,im:im$1,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,isZero:isZero,LOG2E:LOG2E,lgamma:lgamma,log10:log10$1,log2:log2,map:map$1,multiplyScalar:multiplyScalar,not:not,number:number,oct:oct,pickRandom:pickRandom,print:print,random:random$1,re:re$1,sec:sec$1,sign:sign$1,sin:sin$1,splitUnit:splitUnit,square:square,string:string,tan:tan$1,typeOf:typeOf,acosh:acosh$1,acsch:acsch$1,apply:apply,asec:asec$1,bin:bin,combinationsWithRep:combinationsWithRep,cos:cos$1,csch:csch$1,isNaN:isNaN$2,isPrime:isPrime,randomInt:randomInt,sech:sech$1,sinh:sinh$1,sparse:sparse,sqrt:sqrt$1,tanh:tanh$1,unaryMinus:unaryMinus,acoth:acoth$1,cot:cot$1,fraction:fraction,isNumeric:isNumeric,matrix:matrix$2,matrixFromFunction:matrixFromFunction,mod:mod$1,nthRoot:nthRoot,numeric:numeric,or:or,prod:prod,reshape:reshape,size:size$1,smaller:smaller,squeeze:squeeze,subset:subset,subtract:subtract$1,to:to,transpose:transpose,xgcd:xgcd,zeros:zeros,and:and,bitAnd:bitAnd,bitXor:bitXor,cbrt:cbrt,compare:compare,compareText:compareText,concat:concat,count:count,ctranspose:ctranspose,diag:diag,divideScalar:divideScalar,dotDivide:dotDivide,equal:equal$1,fft:fft,flatten:flatten$3,gcd:gcd,hasNumericValue:hasNumericValue,hypot:hypot,ifft:ifft,kron:kron,largerEq:largerEq,leftShift:leftShift,lsolve:lsolve,matrixFromColumns:matrixFromColumns,min:min$1,mode:mode,nthRoots:nthRoots,ones:ones,partitionSelect:partitionSelect,resize:resize,rightArithShift:rightArithShift,round:round$1,smallerEq:smallerEq,unequal:unequal,usolve:usolve,xor:xor,add:add$1,atan2:atan2$1,bitOr:bitOr,catalan:catalan,compareNatural:compareNatural,cumsum:cumsum,deepEqual:deepEqual,diff:diff,dot:dot,equalText:equalText,floor:floor,identity:identity$1,invmod:invmod,larger:larger,log:log$1,lsolveAll:lsolveAll,matrixFromRows:matrixFromRows,multiply:multiply$1,qr:qr,range:range$1,rightLogShift:rightLogShift,setSize:setSize,slu:slu,sum:sum,trace:trace,usolveAll:usolveAll,asin:asin$1,ceil:ceil,composition:composition,cross:cross,det:det,distance:distance,dotMultiply:dotMultiply,fix:fix,intersect:intersect,lcm:lcm,log1p:log1p,max:max$1,quantileSeq:quantileSeq,row:row,setCartesian:setCartesian,setDistinct:setDistinct,setIsSubset:setIsSubset,setPowerset:setPowerset,sort:sort,column:column,index:index,inv:inv,pinv:pinv,pow:pow$1,setDifference:setDifference,setMultiplicity:setMultiplicity,sqrtm:sqrtm,vacuumImpedance:vacuumImpedance,wienDisplacement:wienDisplacement,atomicMass:atomicMass,bohrMagneton:bohrMagneton,boltzmann:boltzmann,conductanceQuantum:conductanceQuantum,createUnit:createUnit,deuteronMass:deuteronMass,dotPow:dotPow,electricConstant:electricConstant,elementaryCharge:elementaryCharge,expm:expm,faraday:faraday,firstRadiation:firstRadiation,gamma:gamma$1,gravitationConstant:gravitationConstant,hartreeEnergy:hartreeEnergy,klitzing:klitzing,loschmidt:loschmidt,magneticConstant:magneticConstant,molarMass:molarMass,molarPlanckConstant:molarPlanckConstant,neutronMass:neutronMass,nuclearMagneton:nuclearMagneton,planckCharge:planckCharge,planckLength:planckLength,planckTemperature:planckTemperature,protonMass:protonMass,reducedPlanckConstant:reducedPlanckConstant,rydberg:rydberg,setIntersect:setIntersect,speedOfLight:speedOfLight,stefanBoltzmann:stefanBoltzmann,thomsonCrossSection:thomsonCrossSection,avogadro:avogadro,bohrRadius:bohrRadius,coulomb:coulomb,divide:divide$1,electronMass:electronMass,factorial:factorial$1,gravity:gravity,inverseConductanceQuantum:inverseConductanceQuantum,lup:lup,magneticFluxQuantum:magneticFluxQuantum,molarMassC12:molarMassC12,multinomial:multinomial,parse:parse$2,permutations:permutations,planckMass:planckMass,quantumOfCirculation:quantumOfCirculation,resolve:resolve,secondRadiation:secondRadiation,simplifyCore:simplifyCore,stirlingS2:stirlingS2,unit:unit,bellNumbers:bellNumbers,compile:compile,eigs:eigs,fermiCoupling:fermiCoupling,leafCount:leafCount,mean:mean,molarVolume:molarVolume,planckConstant:planckConstant,setSymDifference:setSymDifference,simplify:simplify$2,symbolicEqual:symbolicEqual,classicalElectronRadius:classicalElectronRadius,evaluate:evaluate$1,help:help,lusolve:lusolve,median:median,rationalize:rationalize,setUnion:setUnion,variance:variance,derivative:derivative$1,kldivergence:kldivergence,norm:norm,planckTime:planckTime,rotationMatrix:rotationMatrix,gasConstant:gasConstant,parser:parser,std:std,mad:mad,rotate:rotate,config:config$2}),_extends$1(mathWithTransform,math$2,{filter:createFilterTransform({typed:typed}),forEach:createForEachTransform({typed:typed}),map:createMapTransform({typed:typed}),apply:createApplyTransform({isInteger:isInteger,typed:typed}),diff:createDiffTransform({bignumber:bignumber,matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),subset:createSubsetTransform({matrix:matrix$2,typed:typed}),concat:createConcatTransform({isInteger:isInteger,matrix:matrix$2,typed:typed}),max:createMaxTransform({config:config$2,larger:larger,numeric:numeric,typed:typed}),min:createMinTransform({config:config$2,numeric:numeric,smaller:smaller,typed:typed}),range:createRangeTransform({bignumber:bignumber,matrix:matrix$2,config:config$2,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),sum:createSumTransform({add:add$1,config:config$2,numeric:numeric,typed:typed}),cumsum:createCumSumTransform({add:add$1,typed:typed,unaryPlus:unaryPlus}),row:createRowTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),column:createColumnTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index:createIndexTransform({Index:Index}),mean:createMeanTransform({add:add$1,divide:divide$1,typed:typed}),variance:createVarianceTransform({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),std:createStdTransform({sqrt:sqrt$1,typed:typed,variance:variance})}),_extends$1(classes,{BigNumber:BigNumber,Chain:Chain,Complex:Complex,Fraction:Fraction,Matrix:Matrix,Node:Node,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,Range:Range,RelationalNode:RelationalNode,ResultSet:ResultSet,ArrayNode:ArrayNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,DenseMatrix:DenseMatrix,RangeNode:RangeNode,FunctionAssignmentNode:FunctionAssignmentNode,SparseMatrix:SparseMatrix,AccessorNode:AccessorNode,AssignmentNode:AssignmentNode,IndexNode:IndexNode,FibonacciHeap:FibonacciHeap,ImmutableDenseMatrix:ImmutableDenseMatrix,Index:Index,Spa:Spa,Unit:Unit,SymbolNode:SymbolNode,FunctionNode:FunctionNode,Help:Help,Parser:Parser}),Chain.createProxy(math$2);var all=allFactories;Number.isFinite=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Number.isNaN=Number.isNaN||function(e){return e!=e};var tinyEmitter={exports:{}};function E(){}function mixin$1(e){var t=new tinyEmitter.exports;return e.on=t.on.bind(t),e.off=t.off.bind(t),e.once=t.once.bind(t),e.emit=t.emit.bind(t),e}function importFactory(e,t,n,r){function a(t,a,s){var o;if(s.wrap&&"function"==typeof a&&(a=function(e){var t=function(){for(var t=[],r=0,a=arguments.length;r2&&void 0!==arguments[2]?arguments[2]:t.fn;if(contains$1(i,"."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(i));var o=d(t)?n.expression.transform:n,l=i in n.expression.transform,c=hasOwnProperty$2(o,i)?o[i]:void 0,m=function(){var r={};t.dependencies.map(stripOptionalNotation).forEach((e=>{if(contains$1(e,"."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(e));"math"===e?r.math=n:"mathWithTransform"===e?r.mathWithTransform=n.expression.mathWithTransform:"classes"===e?r.classes=n:r[e]=n[e]}));var s=t(r);if(s&&"function"==typeof s.transform)throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with exports.path="expression.transform"');if(void 0===c||a.override)return s;if(u(c)&&u(s))return e(c,s);if(a.silent)return c;throw new Error('Cannot import "'+i+'": already exists')};t.meta&&!1===t.meta.lazy?(o[i]=m(),c&&l?s(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>o[i]))):(lazy(o,i,m),c&&l?s(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>o[i]))),r[i]=t,n.emit("import",i,m)}function l(e){return"function"==typeof e||"number"==typeof e||"string"==typeof e||"boolean"==typeof e||null===e||isUnit(e)||isComplex(e)||isBigNumber(e)||isFraction(e)||isMatrix(e)||Array.isArray(e)}function u(e){return"function"==typeof e&&"object"==typeof e.signatures}function c(e){return!hasOwnProperty$2(m,e)}function p(e){return!(-1!==e.fn.indexOf(".")||hasOwnProperty$2(m,e.fn)||e.meta&&e.meta.isClass)}function d(e){return void 0!==e&&void 0!==e.meta&&!0===e.meta.isTransformFunction||!1}var m={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return function(e,t){var n=arguments.length;if(1!==n&&2!==n)throw new ArgumentsError("import",n,1,2);t||(t={});var r={};for(var i in function e(n,r,a){if(Array.isArray(r))r.forEach((t=>e(n,t)));else if("object"==typeof r)for(var i in r)hasOwnProperty$2(r,i)&&e(n,r[i],i);else if(isFactory(r)||void 0!==a){var s=isFactory(r)?d(r)?r.fn+".transform":r.fn:a;if(hasOwnProperty$2(n,s)&&n[s]!==r&&!t.silent)throw new Error('Cannot import "'+s+'" twice');n[s]=r}else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}(r,e),r)if(hasOwnProperty$2(r,i)){var s=r[i];if(isFactory(s))o(s,t);else if(l(s))a(i,s,t);else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}}}function create$1(e,t){var n=_extends$1({},DEFAULT_CONFIG,t);if("function"!=typeof Object.create)throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r=mixin$1({isNumber:isNumber$1,isComplex:isComplex,isBigNumber:isBigNumber,isFraction:isFraction,isUnit:isUnit,isString:isString$1,isArray:isArray$1,isMatrix:isMatrix,isCollection:isCollection,isDenseMatrix:isDenseMatrix,isSparseMatrix:isSparseMatrix,isRange:isRange,isIndex:isIndex,isBoolean:isBoolean$1,isResultSet:isResultSet,isHelp:isHelp,isFunction:isFunction$2,isDate:isDate$1,isRegExp:isRegExp$1,isObject:isObject$1,isNull:isNull$1,isUndefined:isUndefined$1,isAccessorNode:isAccessorNode,isArrayNode:isArrayNode,isAssignmentNode:isAssignmentNode,isBlockNode:isBlockNode,isConditionalNode:isConditionalNode,isConstantNode:isConstantNode,isFunctionAssignmentNode:isFunctionAssignmentNode,isFunctionNode:isFunctionNode,isIndexNode:isIndexNode,isNode:isNode,isObjectNode:isObjectNode,isOperatorNode:isOperatorNode,isParenthesisNode:isParenthesisNode,isRangeNode:isRangeNode,isSymbolNode:isSymbolNode,isChain:isChain});r.config=configFactory(n,r.emit),r.expression={transform:{},mathWithTransform:{config:r.config}};var a=[],i=[],s={},o=importFactory((function(){for(var e=arguments.length,t=new Array(e),n=0;n{values$1(s).forEach((e=>{e&&e.meta&&e.meta.recreateOnConfigChange&&o(e,{override:!0})}))})),r.create=create$1.bind(null,e),r.factory=factory,r.import(values$1(deepFlatten(e))),r.ArgumentsError=ArgumentsError,r.DimensionError=DimensionError,r.IndexError=IndexError,r}E.prototype={on:function(e,t,n){var r=this.e||(this.e={});return(r[e]||(r[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var r=this;function a(){r.off(e,a),t.apply(n,arguments)}return a._=t,this.on(e,a,n)},emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||(this.e={}))[e]||[]).slice(),r=0,a=n.length;r3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;if(new Date-n>t)break}for(a=r;a>3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;return 1e3*(3*r-1)/(new Date-n)},numeric._myIndexOf=function(e){var t,n=this.length;for(t=0;tnumeric.largeArray)return n.push("...Large Array..."),!0;for(u=!1,n.push("["),a=0;a0&&(n.push(","),u&&n.push("\n ")),u=e(r[a]);return n.push("]"),!0}for(a in n.push("{"),u=!1,r)r.hasOwnProperty(a)&&(u&&n.push(",\n"),u=!0,n.push(a),n.push(": \n"),e(r[a]));return n.push("}"),!0}(e),n.join("")},numeric.parseDate=function(e){return function e(t){if("string"==typeof t)return Date.parse(t.replace(/-/g,"/"));if(!(t instanceof Array))throw new Error("parseDate: parameter must be arrays of strings");var n,r=[];for(n=0;n0){for(i[l]=[],t=0;t>>8^a[255&(i^e[r])];return-1^i}var n,r,a,i,s,o,l,u,c,p,d=e[0].length,m=e[0][0].length,h=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,m>>24&255,m>>16&255,m>>8&255,255&m,d>>24&255,d>>16&255,d>>8&255,255&d,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];for(p=t(h,12,29),h[29]=p>>24&255,h[30]=p>>16&255,h[31]=p>>8&255,h[32]=255&p,n=1,r=0,l=0;l>8&255,h.push(s),h.push(o),h.push(255&~s),h.push(255&~o),0===l&&h.push(0),u=0;u255?255:s<0?0:Math.round(s)))%65521))%65521,h.push(s);h.push(0)}return c=(r<<16)+n,h.push(c>>24&255),h.push(c>>16&255),h.push(c>>8&255),h.push(255&c),i=h.length-41,h[33]=i>>24&255,h[34]=i>>16&255,h[35]=i>>8&255,h[36]=255&i,p=t(h,37),h.push(p>>24&255),h.push(p>>16&255),h.push(p>>8&255),h.push(255&p),h.push(0),h.push(0),h.push(0),h.push(0),h.push(73),h.push(69),h.push(78),h.push(68),h.push(174),h.push(66),h.push(96),h.push(130),"data:image/png;base64,"+function(e){var t,n,r,a,i,s,o,l=e.length,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="";for(t=0;t>4),s=((15&r)<<2)+((a=e[t+2])>>6),o=63&a,t+1>=l?s=o=64:t+2>=l&&(o=64),c+=u.charAt(n>>2)+u.charAt(i)+u.charAt(s)+u.charAt(o);return c}(h)},numeric._dim=function(e){for(var t=[];"object"==typeof e;)t.push(e.length),e=e[0];return t},numeric.dim=function(e){var t;return"object"==typeof e?"object"==typeof(t=e[0])?"object"==typeof t[0]?numeric._dim(e):[e.length,t.length]:[e.length]:[]},numeric.mapreduce=function(e,t){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+t+';\nif(typeof x === "number") { var xi = x; '+e+'; return accum; }\nif(typeof _s === "undefined") _s = numeric.dim(x);\nif(typeof _k === "undefined") _k = 0;\nvar _n = _s[_k];\nvar i,xi;\nif(_k < _s.length-1) {\n for(i=_n-1;i>=0;i--) {\n accum = arguments.callee(x[i],accum,_s,_k+1);\n } return accum;\n}\nfor(i=_n-1;i>=1;i-=2) { \n xi = x[i];\n '+e+";\n xi = x[i-1];\n "+e+";\n}\nif(i === 0) {\n xi = x[i];\n "+e+"\n}\nreturn accum;")},numeric.mapreduce2=function(e,t){return Function("x","var n = x.length;\nvar i,xi;\n"+t+";\nfor(i=n-1;i!==-1;--i) { \n xi = x[i];\n "+e+";\n}\nreturn accum;")},numeric.same=function e(t,n){var r,a;if(!(t instanceof Array&&n instanceof Array))return!1;if((a=t.length)!==n.length)return!1;for(r=0;r=0;r-=2)i[r+1]=t,i[r]=t;return-1===r&&(i[0]=t),i}for(r=a-1;r>=0;r--)i[r]=numeric.rep(e,t,n+1);return i},numeric.dotMMsmall=function(e,t){var n,r,a,i,s,o,l,u,c,p,d;for(i=e.length,s=t.length,o=t[0].length,l=Array(i),n=i-1;n>=0;n--){for(u=Array(o),c=e[n],a=o-1;a>=0;a--){for(p=c[s-1]*t[s-1][a],r=s-2;r>=1;r-=2)d=r-1,p+=c[r]*t[r][a]+c[d]*t[d][a];0===r&&(p+=c[0]*t[0][a]),u[a]=p}l[n]=u}return l},numeric._getCol=function(e,t,n){var r;for(r=e.length-1;r>0;--r)n[r]=e[r][t],n[--r]=e[r][t];0===r&&(n[0]=e[0][t])},numeric.dotMMbig=function(e,t){var n,r,a,i=numeric._getCol,s=t.length,o=Array(s),l=e.length,u=t[0].length,c=new Array(l),p=numeric.dotVV;for(--s,r=--l;-1!==r;--r)c[r]=Array(u);for(r=--u;-1!==r;--r)for(i(t,r,o),a=l;-1!==a;--a)n=e[a],c[a][r]=p(n,o);return c},numeric.dotMV=function(e,t){var n,r=e.length;t.length;var a=Array(r),i=numeric.dotVV;for(n=r-1;n>=0;n--)a[n]=i(e[n],t);return a},numeric.dotVM=function(e,t){var n,r,a,i,s,o,l;for(a=e.length,i=t[0].length,s=Array(i),r=i-1;r>=0;r--){for(o=e[a-1]*t[a-1][r],n=a-2;n>=1;n-=2)l=n-1,o+=e[n]*t[n][r]+e[l]*t[l][r];0===n&&(o+=e[0]*t[0][r]),s[r]=o}return s},numeric.dotVV=function(e,t){var n,r,a=e.length,i=e[a-1]*t[a-1];for(n=a-2;n>=1;n-=2)r=n-1,i+=e[n]*t[n]+e[r]*t[r];return 0===n&&(i+=e[0]*t[0]),i},numeric.dot=function(e,t){var n=numeric.dim;switch(1e3*n(e).length+n(t).length){case 2002:return t.length<10?numeric.dotMMsmall(e,t):numeric.dotMMbig(e,t);case 2001:return numeric.dotMV(e,t);case 1002:return numeric.dotVM(e,t);case 1001:return numeric.dotVV(e,t);case 1e3:return numeric.mulVS(e,t);case 1:return numeric.mulSV(e,t);case 0:return e*t;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(e){var t,n,r,a,i=e.length,s=Array(i);for(t=i-1;t>=0;t--){for(a=Array(i),n=t+2,r=i-1;r>=n;r-=2)a[r]=0,a[r-1]=0;for(r>t&&(a[r]=0),a[t]=e[t],r=t-1;r>=1;r-=2)a[r]=0,a[r-1]=0;0===r&&(a[0]=0),s[t]=a}return s},numeric.getDiag=function(e){var t,n=Math.min(e.length,e[0].length),r=Array(n);for(t=n-1;t>=1;--t)r[t]=e[t][t],r[--t]=e[t][t];return 0===t&&(r[0]=e[0][0]),r},numeric.identity=function(e){return numeric.diag(numeric.rep([e],1))},numeric.pointwise=function(e,t,n){void 0===n&&(n="");var r,a,i=[],s=/\[i\]$/,o="",l=!1;for(r=0;r=0;i--) ret[i] = arguments.callee("+e.join(",")+",_s,_k+1);\n return ret;\n}\n"+n+"\nfor(i=_n-1;i!==-1;--i) {\n "+t+"\n}\nreturn ret;",Function.apply(null,i)},numeric.pointwise2=function(e,t,n){void 0===n&&(n="");var r,a,i=[],s=/\[i\]$/,o="",l=!1;for(r=0;r=0;s--)e("object"==typeof t?t[s]:t,"object"==typeof n?n[s]:n,r,a+1,i);else i(t,n)},numeric._biforeach2=function e(t,n,r,a,i){if(a===r.length-1)return i(t,n);var s,o=r[a],l=Array(o);for(s=o-1;s>=0;--s)l[s]=e("object"==typeof t?t[s]:t,"object"==typeof n?n[s]:n,r,a+1,i);return l},numeric._foreach=function e(t,n,r,a){var i;if(r!==n.length-1)for(i=n[r]-1;i>=0;i--)e(t[i],n,r+1,a);else a(t)},numeric._foreach2=function e(t,n,r,a){if(r===n.length-1)return a(t);var i,s=n[r],o=Array(s);for(i=s-1;i>=0;i--)o[i]=e(t[i],n,r+1,a);return o},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var e,t;for(e=0;ef&&(h=i,f=o);for(n=d[h],d[h]=d[s],d[s]=n,a=m[h],m[h]=m[s],m[s]=a,e=n[s],o=s;o!==p;++o)n[o]/=e;for(o=p-1;-1!==o;--o)a[o]/=e;for(i=c-1;-1!==i;--i)if(i!==s){for(t=d[i],r=m[i],e=t[s],o=s+1;o!==p;++o)t[o]-=n[o]*e;for(o=p-1;o>0;--o)r[o]-=a[o]*e,r[--o]-=a[o]*e;0===o&&(r[0]-=a[0]*e)}}return m},numeric.det=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: det() only works on square matrices");var n,r,a,i,s,o,l,u,c=t[0],p=1,d=numeric.clone(e);for(r=0;rMath.abs(d[a][r])&&(a=n);for(a!==r&&(l=d[a],d[a]=d[r],d[r]=l,p*=-1),i=d[r],n=r+1;n=1;t-=2){for(a=e[t],r=e[t-1],n=o-1;n>=1;--n)(i=l[n])[t]=a[n],i[t-1]=r[n],(i=l[--n])[t]=a[n],i[t-1]=r[n];0===n&&((i=l[0])[t]=a[0],i[t-1]=r[0])}if(0===t){for(r=e[0],n=o-1;n>=1;--n)l[n][0]=r[n],l[--n][0]=r[n];0===n&&(l[0][0]=r[0])}return l},numeric.negtranspose=function(e){var t,n,r,a,i,s=e.length,o=e[0].length,l=Array(o);for(n=0;n=1;t-=2){for(a=e[t],r=e[t-1],n=o-1;n>=1;--n)(i=l[n])[t]=-a[n],i[t-1]=-r[n],(i=l[--n])[t]=-a[n],i[t-1]=-r[n];0===n&&((i=l[0])[t]=-a[0],i[t-1]=-r[0])}if(0===t){for(r=e[0],n=o-1;n>=1;--n)l[n][0]=-r[n],l[--n][0]=-r[n];0===n&&(l[0][0]=-r[0])}return l},numeric._random=function e(t,n){var r,a,i=t[n],s=Array(i);if(n===t.length-1){for(a=Math.random,r=i-1;r>=1;r-=2)s[r]=a(),s[r-1]=a();return 0===r&&(s[0]=a()),s}for(r=i-1;r>=0;r--)s[r]=e(t,n+1);return s},numeric.random=function(e){return numeric._random(e,0)},numeric.norm2=function(e){return Math.sqrt(numeric.norm2Squared(e))},numeric.linspace=function(e,t,n){if(void 0===n&&(n=Math.max(Math.round(t-e)+1,1)),n<2)return 1===n?[e]:[];var r,a=Array(n);for(r=--n;r>=0;r--)a[r]=(r*t+(n-r)*e)/n;return a},numeric.getBlock=function(e,t,n){var r=numeric.dim(e);return function e(a,i){var s,o=t[i],l=n[i]-o,u=Array(l);if(i===r.length-1){for(s=l;s>=0;s--)u[s]=a[s+o];return u}for(s=l;s>=0;s--)u[s]=e(a[s+o],i+1);return u}(e,0)},numeric.setBlock=function(e,t,n,r){var a=numeric.dim(e);return function e(r,i,s){var o,l=t[s],u=n[s]-l;if(s===a.length-1)for(o=u;o>=0;o--)r[o+l]=i[o];for(o=u;o>=0;o--)e(r[o+l],i[o],s+1)}(e,r,0),e},numeric.getRange=function(e,t,n){var r,a,i,s,o=t.length,l=n.length,u=Array(o);for(r=o-1;-1!==r;--r)for(u[r]=Array(l),i=u[r],s=e[t[r]],a=l-1;-1!==a;--a)i[a]=s[n[a]];return u},numeric.blockMatrix=function(e){var t=numeric.dim(e);if(t.length<4)return numeric.blockMatrix([e]);var n,r,a,i,s,o=t[0],l=t[1];for(n=0,r=0,a=0;a=0;i--){for(a=Array(u),o=e[i],s=u-1;s>=3;--s)a[s]=o*t[s],a[--s]=o*t[s],a[--s]=o*t[s],a[--s]=o*t[s];for(;s>=0;)a[s]=o*t[s],--s;c[i]=a}return c},numeric.T=function(e,t){this.x=e,this.y=t},numeric.t=function(e,t){return new numeric.T(e,t)},numeric.Tbinop=function(e,t,n,r,a){var i;if(numeric.indexOf,"string"!=typeof a)for(i in a="",numeric)numeric.hasOwnProperty(i)&&(e.indexOf(i)>=0||t.indexOf(i)>=0||n.indexOf(i)>=0||r.indexOf(i)>=0)&&i.length>1&&(a+="var "+i+" = numeric."+i+";\n");return Function(["y"],"var x = this;\nif(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n"+a+"\nif(x.y) { if(y.y) { return new numeric.T("+r+");\n }\n return new numeric.T("+n+");\n}\nif(y.y) {\n return new numeric.T("+t+");\n}\nreturn new numeric.T("+e+");\n")},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var e=numeric.mul,t=numeric.div;if(this.y){var n=numeric.add(e(this.x,this.x),e(this.y,this.y));return new numeric.T(t(this.x,n),t(numeric.neg(this.y),n))}return new T(t(1,this.x))},numeric.T.prototype.div=function(e){if(e instanceof numeric.T||(e=new numeric.T(e)),e.y)return this.mul(e.reciprocal());var t=numeric.div;return this.y?new numeric.T(t(this.x,e.x),t(this.y,e.x)):new numeric.T(t(this.x,e.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),e(n)):new numeric.T(e(t))},numeric.T.prototype.transjugate=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),numeric.negtranspose(n)):new numeric.T(e(t))},numeric.Tunop=function(e,t,n){return"string"!=typeof n&&(n=""),Function("var x = this;\n"+n+"\nif(x.y) { "+t+";\n}\n"+e+";\n")},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));","var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\nreturn new numeric.T(numeric.log(r.x),theta.x);"),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);","var f = numeric.norm2Squared;\nreturn Math.sqrt(f(x.x)+f(x.y));"),numeric.T.prototype.inv=function(){var e=this;if(void 0===e.y)return new numeric.T(numeric.inv(e.x));var t,n,r,a,i,s,o,l,u,c,p,d,m,h,f,y,g,b,v=e.x.length,N=numeric.identity(v),T=numeric.rep([v,v],0),C=numeric.clone(e.x),A=numeric.clone(e.y);for(u=0;ud&&(p=c,d=m);for(p!==u&&(b=C[u],C[u]=C[p],C[p]=b,b=A[u],A[u]=A[p],A[p]=b,b=N[u],N[u]=N[p],N[p]=b,b=T[u],T[u]=T[p],T[p]=b),t=C[u],n=A[u],i=N[u],s=T[u],h=t[u],f=n[u],c=u+1;c0;u--)for(i=N[u],s=T[u],c=u-1;c>=0;c--)for(o=N[c],l=T[c],h=C[c][u],f=A[c][u],p=v-1;p>=0;p--)y=i[p],g=s[p],o[p]-=h*y-f*g,l[p]-=h*g+f*y;return new numeric.T(N,T)},numeric.T.prototype.get=function(e){var t,n=this.x,r=this.y,a=0,i=e.length;if(r){for(;a=0?1:-1)*numeric.norm2(e);t[0]+=n;var r=numeric.norm2(t);if(0===r)throw new Error("eig: internal error");return numeric.div(t,r)},numeric.toUpperHessenberg=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var n,r,a,i,s,o,l,u,c,p,d=t[0],m=numeric.clone(e),h=numeric.identity(d);for(r=0;r0){for(s=numeric.house(i),o=numeric.getBlock(m,[r+1,r],[d-1,d-1]),l=numeric.tensor(s,numeric.dot(s,o)),n=r+1;n=4*l?(x=.5*(u+Math.sqrt(u*u-4*l)),S=.5*(u-Math.sqrt(u*u-4*l)),c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,x+S)),numeric.diag(numeric.rep([3],x*S)))):c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,u)),numeric.diag(numeric.rep([3],l))),n=[c[0][0],c[1][0],c[2][0]],r=numeric.house(n),m=[e[0],e[1],e[2]],h=numeric.tensor(r,numeric.dot(r,m)),y=0;y<3;y++)for(d=e[y],f=h[y],b=0;b=0?((y=(s-(d=c<0?-.5*(c-S(p)):-.5*(c+S(p))))*(s-d)+o*o)>(g=l*l+(u-d)*(u-d))?(h=(s-d)/(y=S(y)),f=o/y):(h=l/(g=S(g)),f=(u-d)/g),a=new N([[f,-h],[h,f]]),V.setRows(n,i,a.dot(V.getRows(n,i)))):(d=-.5*c,m=.5*S(-p),(y=(s-d)*(s-d)+o*o)>(g=l*l+(u-d)*(u-d))?(h=(s-d)/(y=S(y+m*m)),f=o/y,d=0,m/=y):(h=l/(g=S(g+m*m)),f=(u-d)/g,d=m/g,m=0),a=new N([[f,-h],[h,f]],[[d,m],[m,-d]]),V.setRows(n,i,a.dot(V.getRows(n,i))))}var w=V.dot(e).dot(V.transjugate()),E=(T=e.length,numeric.T.identity(T));for(i=0;i0)for(r=i-1;r>=0;r--){var D=w.get([r,r]),O=w.get([i,i]);numeric.neq(D.x,O.x)||numeric.neq(D.y,O.y)?(d=w.getRow(r).getBlock([r],[i-1]),m=E.getRow(i).getBlock([r],[i-1]),E.set([i,r],w.get([r,i]).neg().sub(d.dot(m)).div(D.sub(O)))):E.setRow(i,E.getRow(r))}for(i=0;i=i.length;)i[i.length]=0;0!==t[r]&&i[r]++}var s=i.length,o=Array(s+1);for(o[0]=0,n=0;n=l){if(a[c]=m[u],0===u)return;++c,o=p[--u],l=d[u]}else 0===r[s=i[n[o]]]?(r[s]=1,p[u]=o,m[++u]=s,o=t[s],d[u]=l=t[s+1]):++o},numeric.ccsLPSolve=function(e,t,n,r,a,i,s){var o=e[0],l=e[1],u=e[2];o.length;var c,p,d,m,h,f,y,g,b,v=t[0],N=t[1],T=t[2];for(p=v[a],d=v[a+1],r.length=0,c=p;ci&&(s=a,i=o);for(T(b[n])=u){if(a[p]=i[h[c]],0===c)return;++p,l=d[--c],u=m[c]}else 0===r[o=n[l]]?(r[o]=1,d[c]=l,h[++c]=o,l=t[o=i[o]],m[c]=u=t[o+1]):++l}},numeric.ccsLPSolve0=function(e,t,n,r,a,i,s,o){var l=e[0],u=e[1],c=e[2];l.length;var p,d,m,h,f,y,g,b,v,N=t[0],T=t[1],C=t[2];for(d=N[a],m=N[a+1],r.length=0,p=d;pi&&(s=a,i=o);for(T(b[C[n]])n[r]&&(n[r]=t.length),t)t.hasOwnProperty(a)&&e(t[a],n,r+1);return n},numeric.sclone=function e(t,n,r){void 0===n&&(n=0),void 0===r&&(r=numeric.sdim(t).length);var a,i=Array(t.length);if(n===r-1){for(a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);return i}for(a in t)t.hasOwnProperty(a)&&(i[a]=e(t[a],n+1,r));return i},numeric.sdiag=function(e){var t,n,r=e.length,a=Array(r);for(t=r-1;t>=1;t-=2)n=t-1,a[t]=[],a[t][t]=e[t],a[n]=[],a[n][n]=e[n];return 0===t&&(a[0]=[],a[0][0]=e[t]),a},numeric.sidentity=function(e){return numeric.sdiag(numeric.rep([e],1))},numeric.stranspose=function(e){var t,n,r,a=[];for(t in e.length,e)if(e.hasOwnProperty(t))for(n in r=e[t])r.hasOwnProperty(n)&&("object"!=typeof a[n]&&(a[n]=[]),a[n][t]=r[n]);return a},numeric.sLUP=function(e,t){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(e,t){var n=e.length;t.length;var r,a,i,s,o,l,u,c=numeric.stranspose(t),p=c.length,d=Array(n);for(i=n-1;i>=0;i--){for(u=[],r=e[i],o=p-1;o>=0;o--){for(s in l=0,a=c[o],r)r.hasOwnProperty(s)&&s in a&&(l+=r[s]*a[s]);l&&(u[o]=l)}d[i]=u}return d},numeric.sdotMV=function(e,t){var n,r,a,i,s=e.length,o=Array(s);for(r=s-1;r>=0;r--){for(a in i=0,n=e[r])n.hasOwnProperty(a)&&t[a]&&(i+=n[a]*t[a]);i&&(o[r]=i)}return o},numeric.sdotVM=function(e,t){var n,r,a,i,s=[];for(n in e)if(e.hasOwnProperty(n))for(r in a=t[n],i=e[n],a)a.hasOwnProperty(r)&&(s[r]||(s[r]=0),s[r]+=i*a[r]);return s},numeric.sdotVV=function(e,t){var n,r=0;for(n in e)e[n]&&t[n]&&(r+=e[n]*t[n]);return r},numeric.sdot=function(e,t){var n=numeric.sdim(e).length,r=numeric.sdim(t).length;switch(1e3*n+r){case 0:return e*t;case 1001:return numeric.sdotVV(e,t);case 2001:return numeric.sdotMV(e,t);case 1002:return numeric.sdotVM(e,t);case 2002:return numeric.sdotMM(e,t);default:throw new Error("numeric.sdot not implemented for tensors of order "+n+" and "+r)}},numeric.sscatter=function(e){var t,n,r,a,i=e[0].length,s=e.length,o=[];for(n=i-1;n>=0;--n)if(e[s-1][n]){for(a=o,r=0;r=0;--i)n[i]=[];for(i=a;i>=0;--i)n[i].push(r[i]);n[a+1].push(s)}}else e(s,n,r);return r.length>a&&r.pop(),n},numeric.cLU=function(e){var t,n,r,a,i,s,o=e[0],l=e[1],u=e[2],c=o.length,p=0;for(t=0;tp&&(p=o[t]);p++;var d,m=Array(p),h=Array(p),f=numeric.rep([p],1/0),y=numeric.rep([p],-1/0);for(r=0;ry[t]&&(y[t]=n);for(t=0;ty[t+1]&&(y[t+1]=y[t]);for(t=p-1;t>=1;t--)f[t]=0;d--){for(;u[m]>d;)a[d]-=c[m]*a[u[m]],m--;a[d]/=c[m],m--}return a},numeric.cgrid=function(e,t){"number"==typeof e&&(e=[e,e]);var n,r,a,i=numeric.rep(e,-1);for("function"!=typeof t&&(t="L"===t?function(t,n){return t>=e[0]/2||na&&(a=i[r]);for(a++,n=numeric.rep([a],0),r=0;r1;)a[r=s((t+n)/2)]<=e?t=r:n=r;return this._at(e,t)}i=e.length;var o,l=Array(i);for(o=i-1;-1!==o;--o)l[o]=this.at(e[o]);return l},numeric.Spline.prototype.diff=function(){var e,t,n,r=this.x,a=this.yl,i=this.yr,s=this.kl,o=this.kr,l=a.length,u=s,c=o,p=Array(l),d=Array(l),m=numeric.add,h=numeric.mul,f=numeric.div,y=numeric.sub;for(e=l-1;-1!==e;--e)t=r[e+1]-r[e],n=y(i[e+1],a[e]),p[e]=f(m(h(n,6),h(s[e],-4*t),h(o[e+1],-2*t)),t*t),d[e+1]=f(m(h(n,-6),h(s[e],2*t),h(o[e+1],4*t)),t*t);return new numeric.Spline(r,u,c,p,d)},numeric.Spline.prototype.roots=function(){function e(e){return e*e}var t=[],n=this.x,r=this.yl,a=this.yr,i=this.kl,s=this.kr;"number"==typeof r[0]&&(r=[r],a=[a],i=[i],s=[s]);var o,l,u,c,p,d,m,h,f,y,g,b,v,N,T,C,A,V,x,S,w,E,D,O=r.length,I=n.length-1,R=(t=Array(O),Math.sqrt);for(o=0;o!==O;++o){for(c=r[o],p=a[o],d=i[o],m=s[o],h=[],l=0;l!==I;l++){for(l>0&&p[l]*c[l]<0&&h.push(n[l]),C=n[l+1]-n[l],n[l],g=c[l],b=p[l+1],f=d[l]/C,v=(y=m[l+1]/C)+3*g+2*f-3*b,N=3*(y+f+2*(g-b)),(T=e(f-y+3*(g-b))+12*y*g)<=0?A=(V=v/N)>n[l]&&Vn[l]&&Vn[l]&&x0)w=E,V=x;else{for(var _=0;!((D=(V*E-x*w)/(V-x))<=w||D>=E);)if((S=this._at(D,l))*x>0)E=D,x=S,-1===_&&(V*=.5),_=-1;else{if(!(S*V>0))break;w=D,V=S,1===_&&(x*=.5),_=1}h.push(D),w=A[u+1],V=this._at(w,l)}else h.push(w),w=E,V=x;0===x&&h.push(E)}t[o]=h}return"number"==typeof this.yl[0]?t[0]:t},numeric.spline=function(e,t,n,r){var a,i=e.length,s=[],o=[],l=[],u=numeric.sub,c=numeric.mul,p=numeric.add;for(a=i-2;a>=0;a--)o[a]=e[a+1]-e[a],l[a]=u(t[a+1],t[a]);"string"!=typeof n&&"string"!=typeof r||(n=r="periodic");var d=[[],[],[]];switch(typeof n){case"undefined":s[0]=c(3/(o[0]*o[0]),l[0]),d[0].push(0,0),d[1].push(0,1),d[2].push(2/o[0],1/o[0]);break;case"string":s[0]=p(c(3/(o[i-2]*o[i-2]),l[i-2]),c(3/(o[0]*o[0]),l[0])),d[0].push(0,0,0),d[1].push(i-2,0,1),d[2].push(1/o[i-2],2/o[i-2]+2/o[0],1/o[0]);break;default:s[0]=n,d[0].push(0),d[1].push(0),d[2].push(1)}for(a=1;a20)throw new Error("Numerical gradient fails");if(l[a]=t[a]+v,i=e(l),l[a]=t[a]-v,s=e(l),l[a]=t[a],isNaN(i)||isNaN(s))v/=16;else{if(u[a]=(i-s)/(2*v),c=t[a]-v,p=t[a],d=t[a]+v,m=(i-r)/v,h=(r-s)/v,f=o(y(u[a]),y(r),y(i),y(s),y(c),y(p),y(d),1e-8),!(g(o(y(m-u[a]),y(h-u[a]),y(m-h))/f,v/f)>.001))break;v/=16}}return u},numeric.uncmin=function(e,t,n,r,a,i,s){var o=numeric.gradient;void 0===s&&(s={}),void 0===n&&(n=1e-8),void 0===r&&(r=function(t){return o(e,t)}),void 0===a&&(a=1e3);var l,u,c=(t=numeric.clone(t)).length,p=e(t);if(isNaN(p))throw new Error("uncmin: f(x0) is a NaN!");var d=Math.max,m=numeric.norm2;n=d(n,numeric.epsilon);var h,f,y,g=s.Hinv||numeric.identity(c),b=numeric.dot;numeric.inv;var v,N,T,C,A,V,x,S=numeric.sub,w=numeric.add,E=numeric.tensor,D=numeric.div,O=numeric.mul,I=numeric.all,R=numeric.isFinite,_=numeric.neg,M=0,P="";for(f=r(t);M=.1*V*u||isNaN(l));)V*=.5,++M;if(V*x1;)o[r=a(.5*(t+n))]<=e?t=r:n=r;return this._at(e,t)},numeric.dopri=function(e,t,n,r,a,i,s){void 0===a&&(a=1e-6),void 0===i&&(i=1e3);var o,l,u,c,p,d,m,h,f,y,g,b,v,N=[e],T=[n],C=[r(e,n)],A=[],V=[3/40,9/40],x=[44/45,-56/15,32/9],S=[19372/6561,-25360/2187,64448/6561,-212/729],w=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],E=[35/384,0,500/1113,125/192,-2187/6784,11/84],D=[.10013431883002395,0,.3918321794184259,-.02982460176594817,.05893268337240795,-.04497888809104361,5618549.5/235043384],O=[.2,.3,.8,8/9,1,1],I=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40],R=0,_=(t-e)/10,M=0,P=numeric.add,F=numeric.mul,k=Math.min,$=Math.abs,B=numeric.norminf,L=Math.pow,z=numeric.any,U=numeric.lt,j=numeric.and;numeric.sub;var q=new numeric.Dopri(N,T,C,A,-1,"");for("function"==typeof s&&(g=s(e,n));et&&(_=t-e),o=r(e+O[0]*_,P(n,F(.2*_,C[R]))),l=r(e+O[1]*_,P(P(n,F(V[0]*_,C[R])),F(V[1]*_,o))),u=r(e+O[2]*_,P(P(P(n,F(x[0]*_,C[R])),F(x[1]*_,o)),F(x[2]*_,l))),c=r(e+O[3]*_,P(P(P(P(n,F(S[0]*_,C[R])),F(S[1]*_,o)),F(S[2]*_,l)),F(S[3]*_,u))),p=r(e+O[4]*_,P(P(P(P(P(n,F(w[0]*_,C[R])),F(w[1]*_,o)),F(w[2]*_,l)),F(w[3]*_,u)),F(w[4]*_,c))),d=r(e+_,f=P(P(P(P(P(n,F(C[R],_*E[0])),F(l,_*E[2])),F(u,_*E[3])),F(c,_*E[4])),F(p,_*E[5]))),(y="number"==typeof(m=P(P(P(P(P(F(C[R],_*I[0]),F(l,_*I[2])),F(u,_*I[3])),F(c,_*I[4])),F(p,_*I[5])),F(d,_*I[6])))?$(m):B(m))>a){if(e+(_=.2*_*L(a/y,.25))===e){q.msg="Step size became too small";break}}else{if(A[R]=P(P(P(P(P(P(n,F(C[R],_*D[0])),F(l,_*D[2])),F(u,_*D[3])),F(c,_*D[4])),F(p,_*D[5])),F(d,_*D[6])),N[++R]=e+_,T[R]=f,C[R]=d,"function"==typeof s){var G,H,W=e,K=e+.5*_;if(b=s(K,A[R-1]),z(v=j(U(g,0),U(0,b)))||(W=K,g=b,b=s(K=e+_,f),v=j(U(g,0),U(0,b))),z(v)){for(var Z,X,Y=0,Q=1,J=1;;){if("number"==typeof g)H=(J*b*W-Q*g*K)/(J*b-Q*g);else for(H=K,h=g.length-1;-1!==h;--h)g[h]<0&&b[h]>0&&(H=k(H,(J*b[h]*W-Q*g[h]*K)/(J*b[h]-Q*g[h])));if(H<=W||H>=K)break;X=s(H,G=q._at(H,R-1)),z(Z=j(U(g,0),U(0,X)))?(K=H,b=X,v=Z,J=1,-1===Y?Q*=.5:Q=1,Y=-1):(W=H,g=X,Q=1,1===Y?J*=.5:J=1,Y=1)}return f=q._at(.5*(e+H),R-1),q.f[R]=r(H,G),q.x[R]=H,q.y[R]=G,q.ymid[R-1]=f,q.events=v,q.iterations=M,q}}e+=_,n=f,g=b,_=k(.8*_*L(a/y,.25),4*_)}return q.iterations=M,q},numeric.LU=function(e,t){t=t||!1;var n,r,a,i,s,o,l,u,c,p=Math.abs,d=e.length,m=d-1,h=new Array(d);for(t||(e=numeric.clone(e)),a=0;a=0;--n){for(i=o[n],r=n+1;rP)&&(g=P),E=m(e,u(g,x)),T=p(M,S),R=h-1;-1!==R;--R)T[R][R]+=1;_=D(T,d(E,g),!0);var F=d(O,p(t,_)),k=1;for(R=f-1;-1!==R;--R)F[R]<0&&(k=C(k,-.999*F[R]));if(l=c(i,u(_,k)),!A(V(O=c(n,p(t,l)),0)))return{solution:i,message:"",iterations:w};if(i=l,g=0);if(y)return{solution:l,message:"Unbounded",iterations:w}}return{solution:i,message:"maximum iteration count exceeded",iterations:w}},numeric._solveLP=function(e,t,n,r,a){var i=e.length,s=n.length;numeric.sum,numeric.log,numeric.mul;var o=numeric.sub,l=numeric.dot;numeric.div,numeric.add;var u=numeric.rep([i],0).concat([1]),c=numeric.rep([s,1],-1),p=numeric.blockMatrix([[t,c]]),d=n,m=numeric.rep([i],0).concat(Math.max(0,numeric.sup(numeric.neg(n)))+1),h=numeric.__solveLP(u,p,d,r,a,m,!1),f=numeric.clone(h.solution);if(f.length=i,numeric.inf(o(n,l(t,f)))<0)return{solution:NaN,message:"Infeasible",iterations:h.iterations};var y=numeric.__solveLP(e,t,n,r,a-h.iterations,f,!0);return y.iterations+=h.iterations,y},numeric.solveLP=function(e,t,n,r,a,i,s){if(void 0===s&&(s=1e3),void 0===i&&(i=numeric.epsilon),void 0===r)return numeric._solveLP(e,t,n,i,s);var o,l=r.length,u=r[0].length,c=t.length,p=numeric.echelonize(r),d=numeric.rep([u],0),m=p.P,h=[];for(o=m.length-1;-1!==o;--o)d[m[o]]=1;for(o=u-1;-1!==o;--o)0===d[o]&&h.push(o);var f=numeric.getRange,y=numeric.linspace(0,l-1),g=numeric.linspace(0,c-1),b=f(r,y,h),v=f(t,g,m),N=f(t,g,h),T=numeric.dot,C=numeric.sub,A=T(v,p.I),V=C(N,T(A,b)),x=C(n,T(A,a)),S=Array(m.length),w=Array(h.length);for(o=m.length-1;-1!==o;--o)S[o]=e[m[o]];for(o=h.length-1;-1!==o;--o)w[o]=e[h[o]];var E=C(w,T(S,T(p.I,b))),D=numeric._solveLP(E,V,x,i,s),O=D.solution;if(O!=O)return D;var I=T(p.I,C(a,T(b,O))),R=Array(e.length);for(o=m.length-1;-1!==o;--o)R[m[o]]=I[o];for(o=h.length-1;-1!==o;--o)R[h[o]]=O[o];return{solution:R,message:D.message,iterations:D.iterations}},numeric.MPStoLP=function(e){e instanceof String&&e.split("\n");var t,n,r,a,i=0,s=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],o=e.length,l=0,u={},c=[],p=0,d={},m=0,h=[],f=[],y=[];function g(n){throw new Error("MPStoLP: "+n+"\nLine "+t+": "+e[t]+"\nCurrent state: "+s[i]+"\n")}for(t=0;t=i;)e/=2,t/=2,r>>>=1;return(e+r)/t},r},s=t.pow(n,6),a=t.pow(2,a),i=2*a,u(t.random(),e)}([],numeric.seedrandom,256,0,52),function(e){function t(e){if("object"!=typeof e)return e;var n,r=[],a=e.length;for(n=0;nc)h[b]=I;else if(h[b]=-Math.abs(I),I>0){for(g=1;g<=r;g+=1)s[g][y]=-s[g][y];o[y]=-o[y]}}for(y=1;y<=d;y+=1)h[x+p[y]]=0;for(w=0,O=0,y=1;y<=u;y+=1)h[x+y]=1;y-=1){for(I=h[y],v=(b=V+y*(y+3)/2)-y,g=y+1;g<=d;g+=1)I-=h[b]*h[A+g],b+=g;if(I/=h[v],h[A+y]=I,p[y]c)h[x+w]=I;else if(h[x+w]=-Math.abs(I),I>0){for(g=1;g<=r;g+=1)s[g][w]=-s[g][w];o[w]=-o[w]}return 700}for(p[d+=1]=w,b=V+(d-1)*d/2+1,y=1;y<=d-1;y+=1)h[b]=h[y],b+=1;if(d===r)h[b]=h[r];else{for(y=r;y>=d+1&&0!==h[y]&&(M=Math.max(Math.abs(h[y-1]),Math.abs(h[y])),P=Math.min(Math.abs(h[y-1]),Math.abs(h[y])),O=h[y-1]>=0?Math.abs(M*Math.sqrt(1+P*P/(M*M))):-Math.abs(M*Math.sqrt(1+P*P/(M*M))),M=h[y-1]/O,P=h[y]/O,1!==M);y-=1)if(0===M)for(h[y-1]=P*O,g=1;g<=r;g+=1)O=e[g][y-1],e[g][y-1]=e[g][y],e[g][y]=O;else for(h[y-1]=O,F=P/(1+M),g=1;g<=r;g+=1)O=M*e[g][y-1]+P*e[g][y],e[g][y]=F*(e[g][y-1]+O)-e[g][y],e[g][y-1]=O;h[b]=h[d]}return 0}function G(){if(0===h[v=(b=V+T*(T+1)/2+1)+T])return 798;if(M=Math.max(Math.abs(h[v-1]),Math.abs(h[v])),P=Math.min(Math.abs(h[v-1]),Math.abs(h[v])),O=h[v-1]>=0?Math.abs(M*Math.sqrt(1+P*P/(M*M))):-Math.abs(M*Math.sqrt(1+P*P/(M*M))),M=h[v-1]/O,P=h[v]/O,1===M)return 798;if(0===M){for(y=T+1;y<=d;y+=1)O=h[v-1],h[v-1]=h[v],h[v]=O,v+=y;for(y=1;y<=r;y+=1)O=e[y][T],e[y][T]=e[y][T+1],e[y][T+1]=O}else{for(F=P/(1+M),y=T+1;y<=d;y+=1)O=M*h[v-1]+P*h[v],h[v]=F*(h[v-1]+O)-h[v],h[v-1]=O,v+=y;for(y=1;y<=r;y+=1)O=M*e[y][T]+P*e[y][T+1],e[y][T+1]=F*(e[y][T]+O)-e[y][T+1],e[y][T]=O}return 0}function H(){for(v=b-T,y=1;y<=T;y+=1)h[v]=h[b],b+=1,v+=1;return h[S+T]=h[S+T+1],p[T]=p[T+1],(T+=1)(t=Math.abs(t))?e*Math.sqrt(1+t*t/e/e):0==t?e:t*Math.sqrt(1+e*e/t/t)}var y=0,g=0,b=0,v=0,N=0,T=0,C=0;for(i=0;i=0&&(g=-g),b=y*g-C,u[i][i]=y-g,s=l;s=0&&(g=-g),b=y*g-C,u[i][i+1]=y-g,s=l;sv&&(v=N)}for(i=p-1;-1!=i;i+=-1){if(0!=g){for(b=g*u[i][i+1],s=l;s=49)throw"Error: no convergence.";for(v=m[l],g=f(y=(((N=m[o-1])-T)*(N+T)+((g=d[o-1])-(b=d[o]))*(g+b))/(2*b*N),1),y=y<0?((v-T)*(v+T)+b*(N/(y-g)-b))/v:((v-T)*(v+T)+b*(N/(y+g)-b))/v,a=1,C=1,i=l+1;i=0;s--)if(m[s]=0&&n<=MAX_ARRAY_INDEX}}function shallowProperty(e){return function(t){return null==t?void 0:t[e]}}var getByteLength=shallowProperty("byteLength"),isBufferLike=createSizePropertyCheck(getByteLength),typedArrayPattern=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;function isTypedArray(e){return nativeIsView?nativeIsView(e)&&!isDataView$1(e):isBufferLike(e)&&typedArrayPattern.test(toString$1.call(e))}var isTypedArray$1=supportsArrayBuffer?isTypedArray:constant(!1),getLength=shallowProperty("length");function emulatedSet(e){for(var t={},n=e.length,r=0;r":">",'"':""","'":"'","`":"`"},escape=createEscaper(escapeMap),unescapeMap=invert(escapeMap),unescape=createEscaper(unescapeMap),templateSettings=_$1.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},noMatch=/(.)^/,escapes={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},escapeRegExp=/\\|'|\r|\n|\u2028|\u2029/g;function escapeChar(e){return"\\"+escapes[e]}var bareIdentifier=/^\s*(\w|\$)+\s*$/;function template(e,t,n){!t&&n&&(t=n),t=defaults({},t,_$1.templateSettings);var r=RegExp([(t.escape||noMatch).source,(t.interpolate||noMatch).source,(t.evaluate||noMatch).source].join("|")+"|$","g"),a=0,i="__p+='";e.replace(r,(function(t,n,r,s,o){return i+=e.slice(a,o).replace(escapeRegExp,escapeChar),a=o+t.length,n?i+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?i+="'+\n((__t=("+r+"))==null?'':__t)+\n'":s&&(i+="';\n"+s+"\n__p+='"),t})),i+="';\n";var s,o=t.variable;if(o){if(!bareIdentifier.test(o))throw new Error("variable is not a bare identifier: "+o)}else i="with(obj||{}){\n"+i+"}\n",o="obj";i="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{s=new Function(o,"_",i)}catch(e){throw e.source=i,e}var l=function(e){return s.call(this,e,_$1)};return l.source="function("+o+"){\n"+i+"}",l}function result(e,t,n){var r=(t=toPath(t)).length;if(!r)return isFunction$1(n)?n.call(e):n;for(var a=0;a1)flatten$2(o,t-1,n,r),a=r.length;else for(var l=0,u=o.length;lt?(r&&(clearTimeout(r),r=null),o=u,s=e.apply(a,i),r||(a=i=null)):r||!1===n.trailing||(r=setTimeout(l,c)),s};return u.cancel=function(){clearTimeout(r),o=0,r=a=i=null},u}function debounce(e,t,n){var r,a,i,s,o,l=function(){var u=now()-a;t>u?r=setTimeout(l,t-u):(r=null,n||(s=e.apply(o,i)),r||(i=o=null))},u=restArguments((function(u){return o=this,i=u,a=now(),r||(r=setTimeout(l,t),n&&(s=e.apply(o,i))),s}));return u.cancel=function(){clearTimeout(r),r=i=o=null},u}function wrap(e,t){return partial(t,e)}function negate(e){return function(){return!e.apply(this,arguments)}}function compose(){var e=arguments,t=e.length-1;return function(){for(var n=t,r=e[t].apply(this,arguments);n--;)r=e[n].call(this,r);return r}}function after(e,t){return function(){if(--e<1)return t.apply(this,arguments)}}function before(e,t){var n;return function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=null),n}}var once$1=partial(before,2);function findKey(e,t,n){t=cb(t,n);for(var r,a=keys(e),i=0,s=a.length;i0?0:a-1;i>=0&&i0?s=i>=0?i:Math.max(i+o,s):o=i>=0?Math.min(i+1,o):i+o+1;else if(n&&i&&o)return r[i=n(r,a)]===a?i:-1;if(a!=a)return(i=t(slice.call(r,s,o),isNaN$1))>=0?i+s:-1;for(i=e>0?s:o-1;i>=0&&i0?0:s-1;for(a||(r=t[i?i[o]:o],o+=e);o>=0&&o=3;return t(e,optimizeCb(n,a,4),r,i)}}var reduce$1=createReduce(1),reduceRight=createReduce(-1);function filter(e,t,n){var r=[];return t=cb(t,n),each(e,(function(e,n,a){t(e,n,a)&&r.push(e)})),r}function reject(e,t,n){return filter(e,negate(cb(t)),n)}function every(e,t,n){t=cb(t,n);for(var r=!isArrayLike(e)&&keys(e),a=(r||e).length,i=0;i=0}var invoke=restArguments((function(e,t,n){var r,a;return isFunction$1(t)?a=t:(t=toPath(t),r=t.slice(0,-1),t=t[t.length-1]),map(e,(function(e){var i=a;if(!i){if(r&&r.length&&(e=deepGet(e,r)),null==e)return;i=e[t]}return null==i?i:i.apply(e,n)}))}));function pluck(e,t){return map(e,property(t))}function where(e,t){return filter(e,matcher(t))}function max(e,t,n){var r,a,i=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var o=0,l=(e=isArrayLike(e)?e:values(e)).length;oi&&(i=r);else t=cb(t,n),each(e,(function(e,n,r){((a=t(e,n,r))>s||a===-1/0&&i===-1/0)&&(i=e,s=a)}));return i}function min(e,t,n){var r,a,i=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var o=0,l=(e=isArrayLike(e)?e:values(e)).length;or||void 0===n)return 1;if(n1&&(r=optimizeCb(r,t[1])),t=allKeys(e)):(r=keyInObj,t=flatten$2(t,!1,!1),e=Object(e));for(var a=0,i=t.length;a1&&(n=t[1])):(t=map(flatten$2(t,!1,!1),String),r=function(e,n){return!contains(t,n)}),pick(e,r,n)}));function initial(e,t,n){return slice.call(e,0,Math.max(0,e.length-(null==t||n?1:t)))}function first(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[0]:initial(e,e.length-t)}function rest(e,t,n){return slice.call(e,null==t||n?1:t)}function last(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[e.length-1]:rest(e,Math.max(0,e.length-t))}function compact(e){return filter(e,Boolean)}function flatten$1(e,t){return flatten$2(e,t,!1)}var difference=restArguments((function(e,t){return t=flatten$2(t,!0,!0),filter(e,(function(e){return!contains(t,e)}))})),without=restArguments((function(e,t){return difference(e,t)}));function uniq(e,t,n,r){isBoolean(t)||(r=n,n=t,t=!1),null!=n&&(n=cb(n,r));for(var a=[],i=[],s=0,o=getLength(e);sr&&(r=n)):(n>r&&(r=n),r*=i),Math.abs(e-t)<=r}return e===t}var i=e[0],s=e.slice(1),o=t[0],l=t.slice(1);return i===o&&(s.length===l.length&&(n>0&&!r&&"^"===i?!!equal(s[0],l[0],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})&&equal(s[1],l[1]):_.every(_.zip(s,l),(function(e){return equal(e[0],e[1],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})}))))},match$2=function(e,t,n){var r=!1;void 0===n?n={}:n.allow_extended_match&&(r=!0,delete(n=Object.assign({},n)).allow_extended_match);var a=n.variables;if(void 0===a){a={};let e=variables(t);for(let t=0;tObject())),s=n.length,o=!1;function l(u,c,p){let d,m=1,h=1;if((is_associative$1[e]||["tuple","vector","altvector"].includes(e))&&(m=u.length-(s-c-1),h=u.length),void 0!==r.max_group&&(m=r.max_group1?[e].concat(s):s[0],o=match$2(s,n[c],r),i[c][a]=o}if(!o)continue;if(!_.every(_.intersection(Object.keys(p),Object.keys(o)),(function(e){return equal(p[e],o[e])})))continue;let d=Object.assign({},o);Object.assign(d,p);let m=u.filter((e=>!a.includes(e)));if(c===s-1)return{matches:d,skipped:m.reduce((function(e,n){return e.concat([t[n]])}),[])};let h=l(m,c+1,d);if(h)return h}return!1}r.allow_permutations&&("*"===e?o=![...t,...n].some((e=>["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e[0]))):"+"!==e&&"="!==e&&"and"!==e&&"or"!==e&&"ne"!==e&&"union"!==e&&"intersect"!==e||(o=!0));var u={},c=[...Array(t.length).keys()];if(o){let e=l(c,0,{});return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),u)}{let e,n=a?t.length-s:0,r=[];for(let a=0;a<=n&&(e=l(c,0,{}),!e);a++)c=c.slice(1),r.push(t[a]);return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),r.length>0&&(u._skipped_before=r),u)}}function matchImplicitIdentity(e,t,n){var r=t[0],a=t.slice(1);if("+"!==r&&"*"!==r&&"^"!==r)return!1;var i=[];for(let e=0;e0;n--){r=a;for(let e=0;e0||a.length>0)&&(Array.isArray(e)&&(e=e[0]===n[0]?e.slice(1):[e]),e=[n[0]].concat(s,e,a)),i.evaluate_numbers&&(e=evaluate_numbers(e,{max_digits:i.max_digits})),e}return e}))}if(equal(r,a))return a}return a};var math=math$1;const operators$2={"+":function(e){return 1===e.length?e[0]:new math.OperatorNode("+","add",e)},"*":function(e){return new math.OperatorNode("*","multiply",e)},"/":function(e){return new math.OperatorNode("/","divide",e)},"-":function(e){return new math.OperatorNode("-","unaryMinus",[e[0]])},"^":function(e){return new math.OperatorNode("^","pow",e)},vector:function(e){return new math.ArrayNode(e)},altvector:function(e){return new math.ArrayNode(e)},and:function(e){return new math.OperatorNode("and","and",e)},or:function(e){return new math.OperatorNode("or","or",e)},not:function(e){return new math.OperatorNode("not","not",[e[0]])},"<":function(e){return new math.OperatorNode("<","smaller",e)},">":function(e){return new math.OperatorNode(">","larger",e)},le:function(e){return new math.OperatorNode("<=","smallerEq",e)},ge:function(e){return new math.OperatorNode(">=","largerEq",e)},ne:function(e){return new math.OperatorNode("!=","unequal",e)},binom:function(e){const t=new math.SymbolNode("combinations");return new math.FunctionNode(t,e)}},functionConverstions={nCr:"combinations",nPr:"permutations",binom:"combinations"};class astToMathjs$1{constructor({mathjs:e=null}={}){e&&(math=e)}convert(e){if("number"==typeof e)return Number.isFinite(e)?new math.ConstantNode(e):Number.isNaN(e)?new math.SymbolNode("NaN"):e<0?operators$2["-"]([new math.SymbolNode("Infinity")]):new math.SymbolNode("Infinity");if("string"==typeof e)return new math.SymbolNode(e);if("boolean"==typeof e)throw Error("no support for boolean");if(!Array.isArray(e))throw Error("Invalid ast");const t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to mathjs");if("factorial"===n[0])return new math.OperatorNode("!","factorial",[this.convert(n[1])]);let e=functionConverstions[n[0]];e||(e=n[0]);const t=new math.SymbolNode(e),r=n[1];let a;return a="tuple"===r[0]?r.slice(1).map(function(e,t){return this.convert(e)}.bind(this)):[this.convert(r)],new math.FunctionNode(t,a)}if("lts"===t||"gts"===t){const e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");const a=e.slice(1).map(function(e,t){return this.convert(e)}.bind(this));let i=[];for(let n=1;n","larger",a.slice(n-1,n+1))):"lts"===t?i.push(new math.OperatorNode("<=","smallerEq",a.slice(n-1,n+1))):i.push(new math.OperatorNode(">=","largerEq",a.slice(n-1,n+1)));let s=new math.OperatorNode("and","and",i.slice(0,2));for(let e=2;e=","largerEq",[e,s])):l.push(new math.OperatorNode(">","larger",[e,s])),i[2]?l.push(new math.OperatorNode("<=","smallerEq",[e,o])):l.push(new math.OperatorNode("<","smaller",[e,o]));let u=new math.OperatorNode("and","and",l);return"notin"!==t&&"notni"!==t||(u=new math.OperatorNode("not","not",[u])),u}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let e,r;if("subset"===t||"notsubset"===t?(r=n[0],e=n[1]):(r=n[1],e=n[0]),"interval"!==r[0]||"interval"!==e[0])throw Error("Set containment of non-intervals not implemented for conversion to mathjs");let a=r[1],i=r[2],s=e[1],o=e[2];if("tuple"!==a[0]||"tuple"!==i[0]||"tuple"!==s[0]||"tuple"!==o[0])throw Error("Badly formed ast");let l=this.convert(a[1]),u=this.convert(a[2]),c=this.convert(s[1]),p=this.convert(s[2]),d=[];i[1]&&!o[1]?d.push(new math.OperatorNode(">","larger",[l,c])):d.push(new math.OperatorNode(">=","largerEq",[l,c])),i[2]&&!o[2]?d.push(new math.OperatorNode("<","smaller",[u,p])):d.push(new math.OperatorNode("<=","smallerEq",[u,p]));let m=new math.OperatorNode("and","and",d);return"notsubset"!==t&&"notsuperset"!==t||(m=new math.OperatorNode("not","not",[m])),m}if("matrix"===t){let e=n[0],t=e[1],r=e[2],a=n[1];if(!Number.isInteger(t)||!Number.isInteger(r))throw Error("Matrix must have integer dimensions");let i=[];for(let e=1;e<=t;e++){let t=[];for(let n=1;n<=r;n++)t.push(this.convert(a[e][n]));i.push(new math.ArrayNode(t))}return new math.ArrayNode(i)}if(t in operators$2)return operators$2[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var function_normalizations={ln:"log",arccos:"acos",arccosh:"acosh",arcsin:"asin",arcsinh:"asinh",arctan:"atan",arctanh:"atanh",arcsec:"asec",arcsech:"asech",arccsc:"acsc",arccsch:"acsch",arccot:"acot",arccoth:"acoth",cosec:"csc"},create_trig_inverses_for=["cos","cosh","sin","sinh","tan","tanh","sec","sech","csc","csch","cot","coth"],move_exponents_outside_for=["cos","cosh","sin","sinh","tan","tanh","sec","sech","csc","csch","cot","coth"];function normalize_function_names(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){if("sqrt"===r[0])return["^",normalize_function_names(r[1]),.5];var a=normalize_function_names_sub(r[0]);a=["apply",a];var i=r.slice(1).map((function(e){return normalize_function_names(e)}));return i=i.length>1?["tuple"].concat(i):i[0],a.push(i),a}return"^"===n&&"e"===r[0]&&math$1.define_e?["apply","exp",normalize_function_names(r[1])]:"binom"===n?["apply","nCr",["tuple",normalize_function_names(r[0]),normalize_function_names(r[1])]]:[n].concat(r.map((function(e){return normalize_function_names(e)})))}function normalize_function_names_sub(e){if("string"==typeof e)return e in function_normalizations?function_normalizations[e]:e;if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if("^"===t&&2===n.length&&-1===n[1]){let e=normalize_function_names_sub(n[0]);if(create_trig_inverses_for.includes(e))return"a"+e}return[t].concat(n.map((function(e){return normalize_function_names_sub(e)})))}function normalize_applied_functions(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){let e=r[0];if("^"===e[0]){let t=e[1],n=e[2];return-1!==n&&move_exponents_outside_for.includes(t)?["^",["apply",t,normalize_applied_functions(r[1])],n]:["apply",e,normalize_applied_functions(r[1])]}let t=0;for(;"prime"===e[0];)t+=1,e=e[1];let n=["apply",e,normalize_applied_functions(r[1])];for(let e=0;e2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_integer_ast(e,s[0],n),is_integer_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_integer_ast(i[0],r,n);if("*"===a)return!!i.every((function(e){return is_integer_ast(e,r,n)}))||void 0;if("^"===a){let e=is_nonzero_ast(i[0],r,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!is_positive_ast(i[1],r,!0,n))return;if(!1===e)return!0}let t=is_integer_ast(i[0],r,n),a=is_integer_ast(i[1],r,n);if(!t)return t;if(!a)return;return!!is_positive_ast(i[1],r,!1,n)||void 0}if("+"===a){let e=0;for(let t=0;t0)return;e+=1}if(void 0===a)return}return 0===e}if("apply"===a)return!!(functions.C.Z&&functions.C.Z.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.Z&&functions.R.Z.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.Z&&functions.nonzeroC.Z.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.Z&&functions.nonneg.Z.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.Z&&functions.pos.Z.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("/"===a||"prime"===a)return;return!1}return!1}function is_real_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e,!1);if(null!==r)return"number"==typeof r&&Number.isFinite(r);if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}if("in"===i&&s[0]===e&&"R"===s[1])return negate_adjust(!0,o);if("notin"===i&&s[0]===e&&"R"===s[1])return negate_adjust(!1,o);if(!1===o){if("in"===i&&s[0]===e&&"Z"===s[1])return!0}else if("notin"===i&&s[0]===e&&"Z"===s[1])return!0;if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!o||"ne"===i&&o){let t=narrow_assumptions(a,n);if(s[0]===e)return is_real_ast(s[1],t);if(s[1]===e)return is_real_ast(s[0],t)}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_real_ast(e,s[0],n),is_real_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_real_ast(i[0],r,n);if("*"===a||"+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),"*"===a&&(!1===is_nonzero_ast(i[0],r,n)||!1===is_nonzero_ast(i[1],r,n)))return!0;let t=is_real_ast(i[0],r,n),s=is_real_ast(i[1],r,n);return!(!t||!s)||!(t&&!1===s||s&&!1===t)&&void 0}if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_real_ast(i[0],r,n),s=is_real_ast(i[1],r,n);if(!a||!s)return;return is_positive_ast(i[0],r,!1,n)?!!is_positive_ast(i[0],r,!0,n)||!!t||void 0:!!is_integer_ast(i[1],r,n)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_real_ast(i[0],r,n)||!is_real_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.R&&functions.C.R.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.R&&functions.R.R.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.R&&functions.nonzeroC.R.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.R&&functions.nonneg.R.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.R&&functions.pos.R.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_complex_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e,!1);if(null!==r)return"number"==typeof r?Number.isFinite(r):!(void 0===r.re||!Number.isFinite(r.re)||void 0===r.im||!Number.isFinite(r.im));if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}if("in"===i&&s[0]===e&&"C"===s[1])return negate_adjust(!0,o);if("notin"===i&&s[0]===e&&"C"===s[1])return negate_adjust(!1,o);if(!1===o){if("in"===i){if(s[0]===e&&"Z"===s[1])return!0;if(s[0]===e&&"R"===s[1])return!0}}else if("notin"===i){if(s[0]===e&&"Z"===s[1])return!0;if(s[0]===e&&"R"===s[1])return!0}if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!o||"ne"===i&&o){let t=narrow_assumptions(a,n);if(s[0]===e)return is_complex_ast(s[1],t);if(s[1]===e)return is_complex_ast(s[0],t)}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_complex_ast(e,s[0],n),is_complex_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_complex_ast(i[0],r,n);if("*"===a||"+"===a)return"*"===a&&!i.every((e=>!1!==is_nonzero_ast(e,r,n)))||(!!i.every((e=>is_complex_ast(e,r,n)))||void 0);if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_complex_ast(i[0],r,n),s=is_complex_ast(i[1],r,n);return!(!a||!s)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_complex_ast(i[0],r,n)||!is_complex_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.C&&functions.C.C.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.C&&functions.R.C.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.C&&functions.nonzeroC.C.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.C&&functions.nonneg.C.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.C&&functions.pos.C.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_nonzero_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e){if(Number.isFinite(e))return 0!==e;if(Number.isNaN(e))return;return!0}var r=evaluate_to_constant(e,!1);if(null!==r){if("number"==typeof r){if(Number.isFinite(r))return 0!==r;if(Number.isNaN(r))return;return!0}return void 0!==r.re&&void 0!==r.im&&(0!==r.re||0!==r.im)||void 0}if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}let l=narrow_assumptions(a,n);if("="===i&&!o||"ne"===i&&o){if(s[0]===e)return is_nonzero_ast(s[1],l);if(s[1]===e)return is_nonzero_ast(s[0],l)}if("ne"===i&&!o||"="===i&&o){if(s[0]===e&&!1===is_nonzero_ast(s[1],l))return!0;if(s[1]===e&&!1===is_nonzero_ast(s[0],l))return!0}if("<"===i)if(o){if(s[0]===e&&is_positive_ast(s[1],l,!0))return!0;if(s[1]===e&&is_negative_ast(s[0],l,!0))return!0}else{if(s[0]===e&&is_negative_ast(s[1],l,!1))return!0;if(s[1]===e&&is_positive_ast(s[0],l,!1))return!0}if("le"===i)if(o){if(s[0]===e&&is_positive_ast(s[1],l,!1))return!0;if(s[1]===e&&is_negative_ast(s[0],l,!1))return!0}else{if(s[0]===e&&is_negative_ast(s[1],l,!0))return!0;if(s[1]===e&&is_positive_ast(s[0],l,!0))return!0}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_nonzero_ast(e,s[0],n),is_nonzero_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_nonzero_ast(i[0],r,n);if("+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),equal(i[0],simplify(["-",i[1]],n)))return!1;let t=is_nonzero_ast(i[0],r,n),a=is_nonzero_ast(i[1],r,n);if(!1===t)return a;if(!1===a)return t;let s=is_real_ast(i[0],r,n),o=is_real_ast(i[1],r,n);if(!s||!o)return!0===s?!1===o||void 0:!0===o&&!1===s||void 0;let l=is_positive_ast(i[0],r,!1,n),u=is_positive_ast(i[1],r,!1,n),c=is_positive_ast(i[0],r,!0,n),p=is_positive_ast(i[1],r,!0,n);return!!(l&&p||c&&u)||!1===l&&!1===p||!1===c&&!1===u||void 0}if("*"===a){let e=!0;for(let t=0;t0:e>=0);var a=is_real_ast(e,t,r);if(!a)return a;var i=evaluate_to_constant(e,!1);if(null!==i)return"number"==typeof i&&!!Number.isFinite(i)&&(n?i>0:i>=0);if("string"==typeof e){let a;if(a=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(a))return;let i=a,s=a[0],o=a.slice(1),l=!1;for(;"not"===s;){if(l=!l,a=o[0],!Array.isArray(a))return;s=a[0],o=a.slice(1)}let u=narrow_assumptions(i,r);if("="===s&&!l||"ne"===s&&l){if(o[0]===e)return is_positive_ast(o[1],u,n);if(o[1]===e)return is_positive_ast(o[0],u,n)}if("<"===s)if(l){if(o[0]===e&&is_positive_ast(o[1],u,n))return!0;if(o[1]===e&&is_negative_ast(o[0],u,!n))return!1}else{if(o[0]===e&&is_negative_ast(o[1],u,!1))return!1;if(o[1]===e&&is_positive_ast(o[0],u,!1))return!0}if("le"===s)if(l){if(o[0]===e&&is_positive_ast(o[1],u,!1))return!0;if(o[1]===e&&is_negative_ast(o[0],u,!1))return!1}else{if(o[0]===e&&is_negative_ast(o[1],u,!n))return!1;if(o[1]===e&&is_positive_ast(o[0],u,n))return!0}if("and"!==s&&"or"!==s)return;if(l)return;return o.length>2&&(a=unflattenRight(a),o=a.slice(1)),simple_assumption_combination(s,is_positive_ast(e,o[0],n,r),is_positive_ast(e,o[1],n,r))}if(Array.isArray(e)){let a;a=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let i=e[0],s=e.slice(1);if("-"===i)return is_negative_ast(s[0],a,n,r);if("+"===i){s.length>2&&(s=(e=unflattenRight(e)).slice(1));let t=is_positive_ast(s[0],a,!1,r),i=is_positive_ast(s[1],a,!1,r),o=is_positive_ast(s[0],a,!0,r),l=is_positive_ast(s[1],a,!0,r);if(n){if(t&&l||o&&i)return!0}else if(t&&i)return!0;if(n){if(!1===o&&!1===l)return!1}else if(!1===t&&!1===l||!1===o&&!1===i)return!1;return}if("*"===i){if(!s.every((e=>!1!==is_nonzero_ast(e,a,r))))return!n;s.length>2&&(s=(e=unflattenRight(e)).slice(1));let t=is_real_ast(s[0],a,r),i=is_real_ast(s[1],a,r);if(void 0===t||void 0===i)return;if(!1===t)return!1===i&&void 0;if(!1===i)return!1;let o=is_positive_ast(s[0],a,!1,r),l=is_positive_ast(s[1],a,!1,r),u=is_positive_ast(s[0],a,!0,r),c=is_positive_ast(s[1],a,!0,r);if(n){if(u&&c||!1===o&&!1===l)return!0;if(!1===u&&l||o&&!1===c)return!1}else{if(o&&l||!1===u&&!1===c)return!0;if(u&&!1===l||!1===o&&c)return!1}return}if("/"===i){if(!is_nonzero_ast(s[1],a,r))return;if(!1===is_nonzero_ast(s[0],a,r))return!n;let e=is_positive_ast(s[1],a,!0,r);if(void 0===e)return;let t=e?n:!n,i=is_positive_ast(s[0],a,t,r);if(void 0===i)return;return!0===i?!0===e:!0!==e}if("^"===i){let e=is_nonzero_ast(s[0],a,r);if(e){if(!1===is_nonzero_ast(s[1],a,r)){if(s[0]===1/0||s[0]===-1/0)return;return!0}}else{if(!is_positive_ast(s[1],a,!0,r))return;if(!1===e)return!n;if(n)return}if(!0!==is_real_ast(s[0],a,r))return;return is_positive_ast(s[0],a,n,r)?!!is_real_ast(s[1],a,r)||void 0:!!is_integer_ast(simplify(["/",s[1],2],r),a,r)||void 0}if("apply"===i&&!n)return!!(functions.C.nonneg&&functions.C.nonneg.includes(s[0])&&is_complex_ast(s[1],a,r))||!!(functions.R.nonneg&&functions.R.nonneg.includes(s[0])&&is_real_ast(s[1],a,r))||!!(functions.nonzeroC.nonneg&&functions.nonzeroC.nonneg.includes(s[0])&&is_nonzero_ast(s[1],a,r)&&is_complex_ast(s[1],a,r))||!!(functions.nonneg.nonneg&&functions.nonneg.nonneg.includes(s[0])&&is_positive_ast(s[1],a,!1,r))||!!(functions.pos.nonneg&&functions.pos.nonneg.includes(s[0])&&is_positive_ast(s[1],a,!0,r))||void 0;if("apply"===i&&n)return!!(functions.C.pos&&functions.C.pos.includes(s[0])&&is_complex_ast(s[1],a,r))||!!(functions.R.pos&&functions.R.pos.includes(s[0])&&is_real_ast(s[1],a,r))||!!(functions.nonzeroC.pos&&functions.nonzeroC.pos.includes(s[0])&&is_nonzero_ast(s[1],a,r)&&is_complex_ast(s[1],a,r))||!!(functions.nonneg.pos&&functions.nonneg.pos.includes(s[0])&&is_positive_ast(s[1],a,!1,r))||!!(functions.pos.pos&&functions.pos.pos.includes(s[0])&&is_positive_ast(s[1],a,!0,r))||void 0;if("prime"===i)return;return!1}return!1}function is_negative_ast(e,t,n,r){void 0===n&&(n=!0);var a=is_real_ast(e,t,r);if(!0===a){let a=is_positive_ast(e,t,!n,r);return!1===a||!0!==a&&void 0}return a}function tuples_to_vectors(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n)return["vector"].concat(r.map((function(e,t){return tuples_to_vectors(e)})));if("apply"===n){if("tuple"===r[1][0]){let e=tuples_to_vectors(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return tuples_to_vectors(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return tuples_to_vectors(e)}))),t]}return[n].concat(r.map((function(e,t){return tuples_to_vectors(e)})))}function to_intervals(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!1,!1]],e}if("array"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!0,!0]],e}if("apply"===n){if("tuple"===r[1][0]){let e=to_intervals(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return to_intervals(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return to_intervals(e)}))),t]}return[n].concat(r.map((function(e,t){return to_intervals(e)})))}function altvectors_to_vectors(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);return"altvector"===n?["vector"].concat(r.map((function(e,t){return altvectors_to_vectors(e)}))):[n].concat(r.map((function(e,t){return altvectors_to_vectors(e)})))}function ParseError(e,t){this.name="ParseError",this.message=e||"Error parsing input",this.stack=(new Error).stack,this.location=t}functions.C.nonneg=["abs"],functions.C.nonzero=["exp"],functions.C.R=["abs","arg"],functions.C.C=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf","sqrt","log","ln","log10"],functions.R.pos=["exp"],functions.R.nonneg=["abs","exp","arg"],functions.R.R=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf"],functions.R.Z=["sign"],functions.nonzeroC.pos=["abs"],functions.nonneg.nonneg=["abs","exp","arg","sqrt","erf"],functions.nonzeroC.nonzero=["abs"],functions.nonneg.R=[...new Set(functions.R.R.concat(functions.nonneg.nonneg))],functions.pos.pos=["abs","exp","sqrt","erf"],functions.pos.nonneg=functions.pos.pos,functions.pos.nonzero=["abs","exp","sqrt","erf"],functions.pos.R=functions.nonneg.R.concat(["log","ln","log10"]),ParseError.prototype=Object.create(Error.prototype),ParseError.prototype.constructor=ParseError;class lexer{constructor(e,t="\\s"){this.input="",this.location=0,this.token_rules=[],this.initial_whitespace=new RegExp("^("+t+")+");for(let t of e)this.token_rules.push([new RegExp("^"+t[0])].concat(t.slice(1)))}set_input(e){if("string"!=typeof e)throw new Error("Input must be a string");this.input=e,this.location=0}return_state(){return{input:this.input,location:this.location}}set_state({input:e=null,location:t=0}={}){null!==e&&(this.input=e,this.location=t)}advance({remove_initial_space:e=!0}={}){let t=this.initial_whitespace.exec(this.input);if(t){let n=t[0].length;if(this.input=this.input.slice(n),this.location+=n,!e)return{token_type:"SPACE",token_text:t[0],original_text:t[0]}}if(0===this.input.length)return{token_type:"EOF",token_text:"",original_text:""};for(var n of(t=null,this.token_rules))if(t=n[0].exec(this.input),t){let e=t[0].length;this.input=this.input.slice(e),this.location+=e;break}return null===t?{token_type:"INVALID",token_text:this.input[0],original_text:this.input[0]}:n.length>2?{token_type:n[1],token_text:n[2],original_text:t[0]}:{token_type:n[1],token_text:t[0],original_text:t[0]}}unput(e){if("string"!=typeof e)throw new Error("Input must be a string");this.location-=e.length,this.input=e+this.input}}var is_associative={"+":!0,"*":!0,and:!0,or:!0,union:!0,intersect:!0};function flatten(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if(n=n.map((function(e,t){return flatten(e)})),is_associative[t]){for(var r=[],a=0;a2?r=r.concat(n[a].slice(1)):r.push(n[a]);n=r}return[t].concat(n)}const sci_notat_exp_regex$1="(E[+\\-]?[0-9]+\\s*($|(?=\\,|\\||\\)|\\}|\\])))?",number_rules_sci$1=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex$1,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex$1,"NUMBER"]],number_rules_non_sci$1=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_text_rules=[["\\*\\*","^"],["\\*","*"],["\\xB7","*"],["·","*"],["•","*"],["⋅","*"],["×","*"],["/","/"],["-","-"],["֊","-"],["־","-"],["᠆","-"],["‐","-"],["‑","-"],["‒","-"],["–","-"],["—","-"],["―","-"],["⁻","-"],["₋","-"],["−","-"],["⸺","-"],["⸻","-"],["﹘","-"],["﹣","-"],["-","-"],["\\+","+"],["\\^","^"],["‸","^"],["ʌ","^"],["\\|","|"],["\\(","("],["\\)",")"],["\\[","["],["\\]","]"],["\\{","{"],["\\}","}"],["⟨","LANGLE"],["⟩","RANGLE"],["〈","LANGLE"],["〉","RANGLE"],[",",","],[":",":"],["α","VARMULTICHAR","alpha"],["β","VARMULTICHAR","beta"],["ϐ","VARMULTICHAR","beta"],["Γ","VARMULTICHAR","Gamma"],["γ","VARMULTICHAR","gamma"],["Δ","VARMULTICHAR","Delta"],["δ","VARMULTICHAR","delta"],["ε","VARMULTICHAR","epsilon"],["ϵ","VARMULTICHAR","epsilon"],["ζ","VARMULTICHAR","zeta"],["η","VARMULTICHAR","eta"],["Θ","VARMULTICHAR","Theta"],["ϴ","VARMULTICHAR","Theta"],["θ","VARMULTICHAR","theta"],["ᶿ","VARMULTICHAR","theta"],["ϑ","VARMULTICHAR","theta"],["ι","VARMULTICHAR","iota"],["κ","VARMULTICHAR","kappa"],["Λ","VARMULTICHAR","Lambda"],["λ","VARMULTICHAR","lambda"],["μ","VARMULTICHAR","mu"],["µ","VARMULTICHAR","mu"],["ν","VARMULTICHAR","nu"],["Ξ","VARMULTICHAR","Xi"],["ξ","VARMULTICHAR","xi"],["Π","VARMULTICHAR","Pi"],["π","VARMULTICHAR","pi"],["ϖ","VARMULTICHAR","pi"],["ρ","VARMULTICHAR","rho"],["ϱ","VARMULTICHAR","rho"],["Σ","VARMULTICHAR","Sigma"],["σ","VARMULTICHAR","sigma"],["ς","VARMULTICHAR","sigma"],["τ","VARMULTICHAR","tau"],["Υ","VARMULTICHAR","Upsilon"],["υ","VARMULTICHAR","upsilon"],["Φ","VARMULTICHAR","Phi"],["φ","VARMULTICHAR","phi"],["ϕ","VARMULTICHAR","phi"],["Ψ","VARMULTICHAR","Psi"],["ψ","VARMULTICHAR","psi"],["Ω","VARMULTICHAR","Omega"],["ω","VARMULTICHAR","omega"],["oo(?![a-zA-Z0-9])","INFINITY"],["OO(?![a-zA-Z0-9])","INFINITY"],["infty(?![a-zA-Z0-9])","INFINITY"],["infinity(?![a-zA-Z0-9])","INFINITY"],["Infinity(?![a-zA-Z0-9])","INFINITY"],["∞","INFINITY"],["ℯ","VAR","e"],["♠","VARMULTICHAR","spade"],["♡","VARMULTICHAR","heart"],["♢","VARMULTICHAR","diamond"],["♣","VARMULTICHAR","club"],["★","VARMULTICHAR","bigstar"],["◯","VARMULTICHAR","bigcirc"],["◊","VARMULTICHAR","lozenge"],["△","VARMULTICHAR","bigtriangleup"],["▽","VARMULTICHAR","bigtriangledown"],["⧫","VARMULTICHAR","blacklozenge"],["■","VARMULTICHAR","blacksquare"],["▲","VARMULTICHAR","blacktriangle"],["▼","VARMULTICHAR","blacktriangledown"],["◀","VARMULTICHAR","blacktriangleleft"],["▶","VARMULTICHAR","blacktriangleright"],["□","VARMULTICHAR","Box"],["∘","VARMULTICHAR","circ"],["⋆","VARMULTICHAR","star"],["and(?![a-zA-Z0-9])","AND"],["\\&\\&?","AND"],["∧","AND"],["or(?![a-zA-Z0-9])","OR"],["∨","OR"],["not(?![a-zA-Z0-9])","NOT"],["¬","NOT"],["=","="],["᐀","="],["゠","="],["!=","NE"],["≠","NE"],["<=","LE"],["≤","LE"],[">=","GE"],["≥","GE"],["<","<"],[">",">"],["elementof(?![a-zA-Z0-9])","IN"],["∈","IN"],["notelementof(?![a-zA-Z0-9])","NOTIN"],["∉","NOTIN"],["containselement(?![a-zA-Z0-9])","NI"],["∋","NI"],["notcontainselement(?![a-zA-Z0-9])","NOTNI"],["∌","NOTNI"],["subset(?![a-zA-Z0-9])","SUBSET"],["⊂","SUBSET"],["subseteq(?![a-zA-Z0-9])","SUBSETEQ"],["⊆","SUBSETEQ"],["notsubset(?![a-zA-Z0-9])","NOTSUBSET"],["⊄","NOTSUBSET"],["notsubseteq(?![a-zA-Z0-9])","NOTSUBSETEQ"],["⊈","NOTSUBSETEQ"],["superset(?![a-zA-Z0-9])","SUPERSET"],["⊃","SUPERSET"],["superseteq(?![a-zA-Z0-9])","SUPERSETEQ"],["⊇","SUPERSETEQ"],["notsuperset(?![a-zA-Z0-9])","NOTSUPERSET"],["⊅","NOTSUPERSET"],["notsuperseteq(?![a-zA-Z0-9])","NOTSUPERSETEQ"],["⊉","NOTSUPERSETEQ"],["union(?![a-zA-Z0-9])","UNION"],["∪","UNION"],["intersect(?![a-zA-Z0-9])","INTERSECT"],["∩","INTERSECT"],["perp(?![a-zA-Z0-9])","PERP"],["⟂","PERP"],["parallel(?![a-zA-Z0-9])","PARALLEL"],["∥","PARALLEL"],["angle(?![a-zA-Z0-9])","ANGLE"],["∠","ANGLE"],["int(?![a-zA-Z0-9])","INT"],["∫","INT"],["!","!"],["'","'"],["_","_"],["\\.\\.\\.","LDOTS"],["[a-zA-Z∂][a-zA-Z∂0-9]*","VAR"],["[_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault$1=!0,splitSymbolsDefault=!0,unsplitSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","angle","deg"],appliedFunctionSymbolsDefault$1=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","re","im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault$1=["f","g"],operatorSymbolsDefault$1=["binom","vec","linesegment"],unitsDefault$1=get_all_units(),parseLeibnizNotationDefault$1=!0;class textToAst$4{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault$1,splitSymbols:t=splitSymbolsDefault,unsplitSymbols:n=unsplitSymbolsDefault,appliedFunctionSymbols:r=appliedFunctionSymbolsDefault$1,functionSymbols:a=functionSymbolsDefault$1,operatorSymbols:i=operatorSymbolsDefault$1,units:s=unitsDefault$1,parseLeibnizNotation:o=parseLeibnizNotationDefault$1,parseScientificNotation:l=!0}={}){this.allowSimplifiedFunctionApplication=e,this.splitSymbols=t,this.unsplitSymbols=n,this.appliedFunctionSymbols=r,this.functionSymbols=a,this.operatorSymbols=i,this.units=s,this.parseLeibnizNotation=o;let u=base_text_rules;u=l?[...number_rules_sci$1,...u]:[...number_rules_non_sci$1,...u],this.lexer=new lexer(u)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});return":"!==this.token.token_type?n:(this.advance(),[":",n,this.statement_a()])}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type)throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let t=n.length;for(let[e,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&e0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===e?["unit",n[0],s]:["unit",["*",...n.slice(0,e)],s],e===t-1?i:this.convert_units_in_term(["*",i,...n.slice(e+1)])}}}return e}return"/"===t?["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])]:e}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_subsuperscript({parse_absolute_value:e}){if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("NUMBER"===this.token.token_type)a=parseFloat(this.token.token_text),this.advance();else if("INFINITY"===this.token.token_type)a=1/0,this.advance();else if("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type){if(a=this.token.token_text,this.appliedFunctionSymbols.includes(a)||this.functionSymbols.includes(a)){let e=!1;if(this.appliedFunctionSymbols.includes(a)&&(e=!0),this.advance(),"_"===this.token.token_type){this.advance();let e=this.get_subsuperscript({parse_absolute_value:t});a="log"===a&&10===e?"log10":["_",a,e]}if(r)e&&(a=["apply",a,"_"]);else{for(;"'"===this.token.token_type;)a=["prime",a],this.advance();for(;"^"===this.token.token_type;)this.advance(),a=["^",a,this.get_subsuperscript({parse_absolute_value:t})];if("("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),"list"===e[0]&&(e[0]="tuple"),a=["apply",a,e]}else if(e){if(!this.allowSimplifiedFunctionApplication)throw new ParseError("Expecting ( after function",this.lexer.location);let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),a=["apply",a,e]}}return a}if(this.operatorSymbols.includes(a))if(this.advance(),"("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),a="list"===e[0]?[a,...e.slice(1)]:[a,e]}else{let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),a=[a,e]}else{if(this.parseLeibnizNotation){let e=this.return_state(),t=this.leibniz_notation();if(t)return t;this.set_state(e)}let r=this.splitSymbols;if(r&&("VARMULTICHAR"===this.token.token_type||this.unsplitSymbols.includes(a)||1===a.length||a.match(/[\d]/g))&&(r=!1),r){for(let e=a.length-1;e>=0;e--)this.lexer.unput(" "),this.lexer.unput(a[e]);return this.advance(),this.baseFactor({inside_absolute_value:e,parse_absolute_value:t,allow_absolute_value_closing:n})}this.advance()}}else if("("===this.token.token_type||"["===this.token.token_type||"{"===this.token.token_type||"LANGLE"===this.token.token_type){let e,t,n=this.token.token_type;"("===this.token.token_type?(e=")",t="]"):"["===this.token.token_type?(e="]",t=")"):"{"===this.token.token_type?(e="}",t=null):(e="RANGLE",t=null),this.advance();let r=1;if("list"===(a=this.statement_list())[0]&&(r=a.length-1),this.token.token_type!==e){if(2!==r||null===t)throw new ParseError("Expecting "+e,this.lexer.location);if(this.token.token_type!==t)throw new ParseError("Expecting ) or ]",this.lexer.location);let i;a[0]="tuple",i="("===n?["tuple",!1,!0]:["tuple",!0,!1],(a=["interval",a]).push(i)}else r>=2?a[0]="("===n?"tuple":"["===n?"array":"{"===n?"set":"altvector":"{"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type||!t||0!==e&&n){if("ANGLE"===this.token.token_type)if(this.advance(),"("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),"list"===e[0]?a=["angle",...e.slice(1)]:"*"===e[0]&&(a=["angle",e])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;t2&&(this.lexer.unput(this.token.token_text.slice(2)),this.token.token_text=this.token.token_text.slice(0,2));let o=this.token.token_text;if(2===o.length){if(!/[a-zA-Z]/.exec(o[1]))return!1;a.push(o[1])}else{if(this.advance(),("VAR"!==this.token.token_type||this.token.token_text.includes("∂"))&&"VARMULTICHAR"!==this.token.token_type)return!1;a.push(this.token.token_text)}let l=1,u=!1;if(this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance()),"^"===this.token.token_type){if(this.advance(),"NUMBER"!==this.token.token_type)return!1;if(l=parseFloat(this.token.token_text),!Number.isInteger(l))return!1;u=!1,this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance())}if(i.push(l),s+=l,s>n)return!1;if(s===n){if(!u&&("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type))return!1;"SPACE"===this.token.token_type&&this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;et[e+1]));if(t.length!==r||a.length!==r)return subtree;let i=["+",...t.map(((e,t)=>["*",e,a[t]]))];n.push(i)}o.push(n)}return{success:!0,newMatrix:["matrix",["tuple",n,a],o]}}function i(e,t){let n=e[1][1],r=e[1][2],a=e[2],i=["tuple"];for(let e=0;e=0;t--){let r=n[t][0];if("matrix"===r){let r=a(n[t],e);if(!r.success)break;e=r.newMatrix,n.pop()}else{if(["tuple","list","vector","altvector","interval","set","array"].includes(r))break;1!==n[t]&&(e=i(e,n[t])),n.pop()}}for(;r.length>0;){let t=r[0][0];if("matrix"===t){let t=a(e,r[0]);if(!t.success)break;e=t.newMatrix,r.splice(0,1)}else{if(["tuple","list","vector","altvector","interval","set","array"].includes(t))break;1!==r[0]&&(e=i(e,r[0])),r.splice(0,1)}}return n.length>0||r.length>0?["*",...n,e,...r]:e}return e})),(t||n)&&(s=["*",["matrix",["tuple","m","n"],"matrixData"],"b"],o={variables:{n:Number.isInteger,m:Number.isInteger,matrixData:!0,b:!0}},r=transform(r,(function(e){let r=match$2(e,s,o);if(r){let a,i=r.m,s=r.n,o=r.b,l=r.matrixData,u=[];t&&(u.push("vector"),u.push("altvector")),n&&u.push("tuple");let c=[];if(u.includes(o[0]))a=o;else{if(!Array.isArray(o)||"*"!==o[0]||!u.includes(o[1][0]))return e;a=o[1],c=o.slice(2)}let p=a.slice(1);if(p.length!==s)return e;let d=[a[0]];for(let e=0;e["*",e,p[t]]))];d.push(t)}return c.length>0?["*",d,...c]:d}return e}))),r}function perform_vector_scalar_multiplications(e,t=!0){var n=get_tree(e);let r=function(e,t){let n=["*","a",[t,"vectorData"],"b"],r={allow_implicit_identities:["a","b"]};return e=transform(e,(function(e){let a=match$2(e,n,r);if(a){if(1===a.a&&1===a.b)return e;let n=a.vectorData;n=Array.isArray(n)&&n[0]===t?n.slice(1):[n];let r=[],i=[];Array.isArray(a.a)&&"*"===a.a[0]?r.push(...a.a.slice(1)):r.push(a.a),Array.isArray(a.b)&&"*"===a.b[0]?i.push(...a.b.slice(1)):i.push(a.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>["*",t,r[e]]))),r.pop()}for(;i.length>0;){let e=i[0][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e))break;1!==i[0]&&(n=n.map((e=>["*",e,i[0]]))),i.splice(0,1)}let s=[t,...n];return r.length>0||i.length>0?["*",...r,s,...i]:s}return e})),e};return n=r(n,"vector"),n=r(n,"altvector"),t&&(n=r(n,"tuple")),n}function perform_matrix_scalar_multiplications(e){var t=get_tree(e);let n=["*","a",["matrix","size","matrixData"],"b"],r={allow_implicit_identities:["a","b"]};return t=transform(t,(function(e){let t=match$2(e,n,r);if(t){if(1===t.a&&1===t.b)return e;let n=t.matrixData,r=[],a=[];Array.isArray(t.a)&&"*"===t.a[0]?r.push(...t.a.slice(1)):r.push(t.a),Array.isArray(t.b)&&"*"===t.b[0]?a.push(...t.b.slice(1)):a.push(t.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>"tuple"===t?t:t.map((t=>"tuple"===t?t:["*",t,r[e]]))))),r.pop()}for(;a.length>0;){let e=a[0][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e))break;1!==a[0]&&(n=n.map((e=>"tuple"===e?e:e.map((e=>"tuple"===e?e:["*",e,a[0]]))))),a.splice(0,1)}let i=["matrix",t.size,n];return r.length>0||a.length>0?["*",...r,i,...a]:i}return e})),t}function expand_relations(e){var t=get_tree(e);return transform(t,expand_relations_transform)}function expand_relations_transform(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if("="===t){if(n.length<=2)return e;let t=["and"];for(let e=0;e":"lts"===t?"le":"ge",a.push([i,e[n],e[n+1]])}let i=["and",a[0],a[1]];for(let e=2;e",r,u]),o[2]?i?p.push([">",r,c]):p.push(["le",r,c]):i?p.push(["ge",r,c]):p.push(["<",r,c]),l=i?["or"].concat(p):["and"].concat(p),l}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let r,a,i=!1;if("notsubset"!==t&&"notsuperset"!==t||(i=!0),"subset"===t||"notsubset"===t?(r=n[0],a=n[1]):(r=n[1],a=n[0]),r=to_intervals(r),a=to_intervals(a),"interval"!==r[0]||"interval"!==a[0])return e;let s=r[1],o=r[2],l=a[1],u=a[2];if("tuple"!==s[0]||"tuple"!==o[0]||"tuple"!==l[0]||"tuple"!==u[0])throw new Error("Badly formed ast");let c,p=s[1],d=s[2],m=l[1],h=l[2],f=[];return o[1]&&!u[1]?i?f.push(["le",p,m]):f.push([">",p,m]):i?f.push(["<",p,m]):f.push(["ge",p,m]),o[2]&&!u[2]?i?f.push(["ge",d,h]):f.push(["<",d,h]):i?f.push([">",d,h]):f.push(["le",d,h]),c=i?["or"].concat(f):["and"].concat(f),c}return e}function substitute(e,t){var n=get_tree(e),r={};for(let e in t)r[e]=get_tree(t[e]);return substitute$1(n,r)}function substitute_component(e,t,n){let r=get_tree(e);if(get_tree(n),"number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid substitute_component: "+t);let a=["list","tuple","vector","altvector","array"];return function e(t,r,i){if(0===r.length)return n;if(!Array.isArray(t))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let s=t[0],o=t.slice(1);if(!a.includes(s))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let l=r[0];if(l<0||l>o.length-1)throw Error("Invalid substitute_component: component out of range");let u=r.slice(1),c=e(o[l],u);return[s,...o.slice(0,l),c,...o.slice(l+1)]}(r,t)}function get_component(e,t){let n=get_tree(e);if("number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid get_component: "+t);let r=["list","tuple","vector","altvector","array"];return function e(t,n){if(0===n.length)return t;if(!Array.isArray(t))throw Error("Invalid get_component: expected list, tuple, vector, or array");let a=t[0],i=t.slice(1);if(!r.includes(a))throw Error("Invalid get_component: expected list, tuple, vector, or array");let s=n[0];if(s<0||s>i.length-1)throw Error("Invalid get_component: component out of range");let o=n.slice(1);return e(i[s],o)}(n,t)}var transformation=Object.freeze({__proto__:null,expand:expand,expand_relations:expand_relations,substitute:substitute,substitute_component:substitute_component,get_component:get_component,perform_vector_scalar_multiplications:perform_vector_scalar_multiplications,perform_matrix_scalar_multiplications:perform_matrix_scalar_multiplications,perform_matrix_multiplications:perform_matrix_multiplications});function clean(e){return flatten$5(get_tree(e))}function evalf(e,t){return parseFloat(math$1.format(e,{notation:"exponential",precision:t}))}function collapse_unary_minus(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if(r=r.map((e=>collapse_unary_minus(e))),"-"===n){if("number"==typeof r[0])return-r[0];if(Array.isArray(r[0])&&"*"===r[0][0]&&"number"==typeof r[0][1])return["*",-r[0][1]].concat(r[0].slice(2));if(Array.isArray(r[0])&&"/"===r[0][0]){if("number"==typeof r[0][1])return["/",-r[0][1],r[0][2]];if(Array.isArray(r[0][1])&&"*"===r[0][1][0]&&"number"==typeof r[0][1][1])return["/",["*",-r[0][1][1]].concat(r[0][1].slice(2)),r[0][2]]}}return[n].concat(r)}function simplify(e,t,n){var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r=evaluate_numbers(r,{assumptions:t,max_digits:n,evaluate_functions:!0}),Array.isArray(r)?r=collect_like_terms_factors(r=perform_vector_matrix_additions_scalar_multiplications(r=simplify_logical(r,t)),t,n):r)}function simplify_logical(e,t){var n=get_tree(e);if(contains_blank(n))return n;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),n=evaluate_numbers(n,{assumptions:t}),n=unflattenRight(n);var r=[];return r.push([["not",["not","a"]],"a"]),r.push([["not",["and","a","b"]],["or",["not","a"],["not","b"]]]),r.push([["not",["or","a","b"]],["and",["not","a"],["not","b"]]]),r.push([["not",["=","a","b"]],["ne","a","b"]]),r.push([["not",["ne","a","b"]],["=","a","b"]]),r.push([["not",["<","a","b"]],["le","b","a"]]),r.push([["not",["le","a","b"]],["not",["le","a","b"]]]),r.push([["not",["in","a","b"]],["notin","a","b"]]),r.push([["not",["subset","a","b"]],["notsubset","a","b"]]),flatten$5(n=applyAllTransformations(n,r,20))}function perform_vector_matrix_additions_scalar_multiplications(e,t=!0){var n=get_tree(e);n=perform_vector_scalar_multiplications(n=perform_matrix_scalar_multiplications(n),t);let r=["+","a","b"];return n=transform(n,(function(e){let n=match$2(e,r,{allow_permutations:!0});if(n){let r=["vector","altvector"];t&&r.push("tuple");let a={},i={},s=[];if(r.includes(n.a[0])){let e=n.a.length-1;a[e]||(a[e]=[]),a[e].push(n.a)}else if("matrix"===n.a[0]){let e=n.a[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.a)}else s.push(n.a);if(r.includes(n.b[0])){let e=n.b.length-1;a[e]||(a[e]=[]),a[e].push(n.b)}else if("matrix"===n.b[0]){let e=n.b[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.b)}else if("+"===n.b[0])for(let e of n.b.slice(1))if(r.includes(e[0])){let t=e.length-1;a[t]||(a[t]=[]),a[t].push(e)}else if("matrix"===e[0]){let t=e[1].slice(1).toString();i[t]||(i[t]=[]),i[t].push(e)}else s.push(e);else s.push(n.b);if(Object.values(a).every((e=>e.length<2))&&Object.values(i).every((e=>e.length<2)))return e;let o=s;for(let e in a)if(a[e].length<2)o.push(...a[e]);else{let t,n=a[e].some((e=>"vector"===e[0])),r=a[e].some((e=>"tuple"===e[0])),i=a[e].some((e=>"altvector"===e[0]));t=n||r&&i?["vector"]:i?["altvector"]:["tuple"];for(let n=0;ne[n+1]))]);o.push(t)}for(let e in i)if(i[e].length<2)o.push(...i[e]);else{let[t,n]=e.split(",").map(Number),r=["tuple"];for(let a=0;ae[2][a+1][r+1]))]);r.push(t)}let a=["matrix",["tuple",t,n],r];o.push(a)}return 1===o.length?o[0]:["+",...o]}return e})),n}function contains_decimal_number(e){return"string"!=typeof e&&("number"==typeof e?!(!Number.isFinite(e)||Number.isInteger(e)):!!Array.isArray(e)&&e.slice(1).some((e=>contains_decimal_number(e))))}function contains_only_numbers(e,{include_number_symbols:t=!1,evaluate_functions:n=!1}={}){if("string"==typeof e){if(t){if("e"===e&&math$1.define_e)return!0;if("pi"===e&&math$1.define_pi)return!0}return!("i"!==e||!math$1.define_i)}return"number"==typeof e||!!Array.isArray(e)&&(n&&"apply"===e[0]?e.slice(2).every((e=>contains_only_numbers(e,{include_number_symbols:t}))):e.slice(1).every((e=>contains_only_numbers(e,{include_number_symbols:t}))))}function try_evaluate_sum_of_numbers(e,t,n){if("number"==typeof e){if(0===e)return t;if("number"==typeof t)return e+t;if(Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[1])return["+",e+t[1],t[2]];if(!n&&Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[2])return["+",e+t[2],t[1]]}return"number"==typeof t&&0===t?e:null}function try_evaluate_negate_number(e){if("number"==typeof e)return-e;if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1])return["*",-e[1]].concat(e.slice(2));if(Array.isArray(e)&&"/"===e[0]){if("number"==typeof e[1])return["/",-e[1],e[2]];if(Array.isArray(e[1])&&"*"===e[1][0]&&"number"==typeof e[1][1])return["/",["*",-e[1][1]].concat(e[1].slice(2)),e[2]]}return null}function try_evaluate_product_of_numbers(e,t){if("number"==typeof e){if(isNaN(e))return NaN;if("number"==typeof t)return e*t;if(!isFinite(e))return e===1/0&&is_negative_ast(t)||e===-1/0&&is_positive_ast(t)?-1/0:!1===is_nonzero_ast(t)?NaN:1/0;if(0===e)return 0;if(1===e)return t;if(-1===e)return["-",t];if(Array.isArray(t)&&"*"===t[0]&&"number"==typeof t[1])return e*=t[1],t=t[2],1===e?t:-1===e?["-",t]:["*",e,t]}if("number"==typeof t){if(isNaN(t))return NaN;if(!isFinite(t))return t===1/0&&is_negative_ast(e)||t===-1/0&&is_positive_ast(e)?-1/0:!1===is_nonzero_ast(e)?NaN:1/0;if(0===t)return 0;if(1===t)return e;if(-1===t)return["-",e];if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1])return t*=e[1],e=e[2],1===t?e:-1===t?["-",e]:["*",e,t]}if(math$1.define_i&&"i"===e){if("i"===t)return-1;if(Array.isArray(t)&&"*"===t[0]&&"i"===t[1])return["-",t[2]]}else if(math$1.define_i&&"i"===t&&Array.isArray(e)&&"*"===e[0]&&"i"===e[1])return["-",e[2]];return null}function try_evaluate_quotient_of_numbers(e,t,n,r){if("number"==typeof e){if(0===e){let e=is_nonzero_ast(t,n);if(e)return 0;if(!1===e)return NaN}if("number"==typeof t){let n=e/t;if(r===1/0||math$1.round(n,r)===n)return n;if(t<0)return["/",-e,-t]}if(Array.isArray(t)&&"*"===t[0]&&"number"==typeof t[1]){let n=e/t[1];if(r===1/0||math$1.round(n,r)===n)return["/",n,t[2]]}}else if("number"==typeof t){if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1]){let n=e[1]/t;if(r===1/0||math$1.round(n,r)===n)return 1===n?e[2]:["*",n,e[2]];if(t<0)return["/",["*",-e[1],e[2]],-t]}let n=1/t;if(r===1/0||math$1.round(n,r)===n)return["*",n,e];if(t<0)return Array.isArray(e)&&"-"===e[0]?["/",e[1],-t]:["-",["/",e,-t]]}return null}function evaluate_numbers_sub(e,t,n,r,a,i){if(void 0===e)return e;if("number"==typeof e)return i>0&&math$1.abs(e)0&&math$1.abs(t)evaluate_numbers_sub(e,t,n,r,a,i)));if("+"===o){let e=l[0],t=l[1];if(void 0===t)return e;let n=try_evaluate_sum_of_numbers(e,t,r);if(null!==n)return n;if("unit"===e[0]&&"unit"===t[0]){let n=get_unit_of_tree(e),a=get_unit_of_tree(t);if(n&&n===a){let a=try_evaluate_sum_of_numbers(remove_units(e,!1),remove_units(t,!1),r);if(null!==a)return add_unit(a,n)}}return[o].concat(l)}if("-"===o){let e=try_evaluate_negate_number(l[0]);if(null!==e)return e;if("unit"===l[0][0]){let e=get_unit_of_tree(l[0]);if(e){let t=try_evaluate_negate_number(remove_units(l[0],!1));if(null!==t)return add_unit(t,e)}}return[o].concat(l)}if("*"===o){let e=l[0],t=l[1];if(void 0===t)return e;let n=try_evaluate_product_of_numbers(e,t);if(null!==n)return n;if("unit"===e[0]&&"unit"!==t[0]){let n=get_unit_of_tree(e);if(n){let r=try_evaluate_product_of_numbers(remove_units(e,!1),t);if(null!==r)return add_unit(r,n)}}if("unit"!==e[0]&&"unit"===t[0]){let n=get_unit_of_tree(t);if(n){let r=try_evaluate_product_of_numbers(e,remove_units(t,!1));if(null!==r)return add_unit(r,n)}}return[o].concat(l)}if("/"===o){let e=l[0],r=l[1],a=try_evaluate_quotient_of_numbers(e,r,t,n);if(null!==a)return a;if("unit"===e[0]&&"unit"!==r[0]){let a=get_unit_of_tree(e);if(a){let i=try_evaluate_quotient_of_numbers(remove_units(e,!1),r,t,n);if(null!==i)return add_unit(i,a)}}return[o].concat(l)}if("^"===o){let e=l[0],r=l[1];if("number"==typeof r)if(0===r){if(!math$1.pow_strict)return 1;let n=is_nonzero_ast(e,t);if(n&&e!==1/0&&e!==-1/0)return 1;if(!1===n)return NaN}else{if(1===r)return e;if("number"==typeof e){let t=math$1.pow(e,r);if(n===1/0||math$1.round(t,n)===t)return t}}else if(1===e)return 1;return[o].concat(l)}return[o].concat(l)}function evaluate_numbers(e,{assumptions:t,max_digits:n,skip_ordering:r=!1,evaluate_functions:a=!1,set_small_zero:i=0}={}){(void 0===n||!Number.isInteger(n)&&n!==1/0)&&(n=0),!0===i&&(i=1e-14);var s,o=get_tree(e);return contains_blank(o)?o:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r?s=evaluate_numbers_sub(o=unflattenRight(flatten$5(o)),t,n,r,a,i):(o=move_units_outside_products(o),o=unflattenRight(default_order(flatten$5(o))),s=default_order(evaluate_numbers_sub(o,t,n,r,a,i)),s=default_order(evaluate_numbers_sub(unflattenRight(s),t,n,r,a,i))),flatten$5(s=set_negative_zeros_to_zero(s)))}function set_negative_zeros_to_zero(e){return 0===e?0:Array.isArray(e)?[e[0],...e.slice(1).map(set_negative_zeros_to_zero)]:e}function collect_like_terms_factors(e,t,n){function r(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function a(e){return"number"==typeof e&&e<0||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function i(e){if("number"==typeof e)return!0;if(Array.isArray(e)&&"-"===e[0]&&"number"==typeof e[1])return!0;let t=evaluate_to_constant(e,!1);return!("number"!=typeof t||!Number.isFinite(t))}var s=get_tree(e);if(contains_blank(s))return s;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),s=evaluate_numbers(s,{assumptions:t,max_digits:n,evaluate_functions:!0});var o=[];o.push([["/","x",["^","y","a"]],["*","x",["^","y",["-","a"]]],{evaluate_numbers:!0,max_digits:n}]),o.push([["/","x",["apply","exp","a"]],["*","x",["apply","exp",["-","a"]]],{evaluate_numbers:!0,max_digits:n,variables:{x:!0,a:!0}}]),o.push([["/","x","y"],["*","x",["^","y",["-",1]]],{evaluate_numbers:!0,max_digits:n}]),s=applyAllTransformations(s,o,40),o=[];for(let e in all_units)all_units[e].prefix?(o.push([["+",["unit",e,"x"],["unit",e,"y"]],["unit",e,["+","x","y"]],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["unit",e,"x"],["-",["unit",e,"y"]]],["unit",e,["+","x",["-","y"]]],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}])):(o.push([["+",["unit","x",e],["unit","y",e]],["unit",["+","x","y"],e],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["unit","x",e],["-",["unit","y",e]]],["unit",["+","x",["-","y"]],e],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]));return o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:e=>is_nonzero_ast(e,t),n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_positive_ast(e,t),m:e=>r(e)&&is_positive_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_negative_ast(e,t),m:e=>r(e)&&is_negative_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["apply","exp","n"],["apply","exp","m"]],["apply","exp",["+","n","m"]],{variables:{n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n","x"],["*","m","x"]],["*",["+","n","m"],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n1","x"],["*",["/","n2","m2"],"x"]],["*",["+","n1",["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n1","x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+","n1",["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*",["/","n1","m1"],"x"],["*",["/","n2","m2"],"x"]],["*",["+",["/","n1","m1"],["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*",["/","n1","m1"],"x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+",["/","n1","m1"],["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n","x"],["-",["*","m","x"]]],["*",["+","n",["-","m"]],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["^",["*","x","y"],"a"],["*",["^","x","a"],["^","y","a"]],{allow_permutations:!0}]),o.push([["^",["^","x","n"],"m"],["^","x",["*","n","m"]],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_permutations:!0}]),o.push([["-",["+","a","b"]],["+",["-","a"],["-","b"]]]),o.push([["*","x","y"],["*","x","y"],{variables:{x:i,y:i},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s=applyAllTransformations(s,o,40),(o=[]).push([["*","x",["^","y",["-","a"]]],["/","x",["^","y","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1}]),o.push([["*","x",["apply","exp",["-","a"]]],["/","x",["apply","exp","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1,variables:{x:!0,a:!0}}]),o.push([["*","x",["^","y","n"]],["/","x",["^","y",["-","n"]]],{variables:{x:!0,y:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*","x",["apply","exp","n"]],["/","x",["apply","exp",["-","n"]]],{variables:{x:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s=applyAllTransformations(s,o,40),(o=[]).push([["^","y","n"],["/",1,["^","y",["-","n"]]],{variables:{y:!0,n:a},evaluate_numbers:!0,max_digits:n}]),o.push([["apply","exp","n"],["/",1,["apply","exp",["-","n"]]],{variables:{n:a},evaluate_numbers:!0,max_digits:n}]),s=applyAllTransformations(s,o,40),(o=[]).push([["*","x",["/","y","z"]],["/",["*","x","y"],"z"],{allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["/",["/","x","y"],"z"],["/","x",["*","y","z"]],{allow_extended_match:!0,allow_permutations:!0}]),o.push([["/","x",["/","y","z"]],["/",["*","x","z"],"y"],{allow_extended_match:!0,allow_permutations:!0}]),evaluate_numbers(s=applyAllTransformations(s,o,40),{assumptions:t,max_digits:n})}function simplify_ratios(e,t){function n(e){var t=1;return e=e.map((function(e){if("number"==typeof e)return e<0?(t*=-1,-e):e;if(!Array.isArray(e))return e;if("-"===e[0])return t*=-1,e[1];if("+"!==e[0])return e;var n=!1;if(("number"==typeof e[1]&&e[1]<0||Array.isArray(e[1])&&"-"===e[1][0]||Array.isArray(e[1])&&"*"===e[1][0]&&Number(e[1][1])<0)&&(n=!0),n){t*=-1;var r=e.slice(1).map((e=>["-",e]));return evaluate_numbers(["+"].concat(r))}return e})),{factors:e,sign_change:t}}var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),function e(t,r){if(!Array.isArray(t))return r?["-",t]:t;var a=t[0];if("-"===a)return e(t[1],r=!0);var i=t.slice(1).map((t=>e(t)));if("/"!==a)return r?["-",[a,...i]]:[a,...i];var s,o=i[0],l=i[1];o=default_order(o,{ignore_negatives:!0});var u,c=n(s=Array.isArray(o)&&"*"===o[0]?o.slice(1):[o]);s=c.factors,r&&(c.sign_change*=-1),l=default_order(l,{ignore_negatives:!0});var p=n(Array.isArray(l)&&"*"===l[0]?l.slice(1):[l]);return u=p.factors,c.sign_change*p.sign_change<0&&(s[0]=["-",s[0]]),["/",o=1===s.length?s[0]:["*"].concat(s),l=1===u.length?u[0]:["*"].concat(u)]}(r))}function contains_blank(e){return"_"===e||!!Array.isArray(e)&&e.some(contains_blank)}let all_units=get_all_units();function remove_units(e,t=!0){var n=get_tree(e);if(!Array.isArray(n))return n;let r=n[0],a=n.slice(1);if("unit"===r){let e=all_units[get_unit_of_tree(n)];if(!e)return n;let r=remove_units(e.prefix?a[1]:a[0],t);return t?e.scale(r):r}return[r,...a.map((e=>remove_units(e,t)))]}function remove_scaling_units(e){var t=get_tree(e);if(!Array.isArray(t))return t;let n=t[0],r=t.slice(1);if("unit"===n){let e=all_units[get_unit_of_tree(t)];if(!e||!e.only_scales)return t;let n=remove_scaling_units(e.prefix?r[1]:r[0]);return e.scale(n)}return[n,...r.map((e=>remove_scaling_units(e)))]}function add_unit(e,t){var n=get_tree(e);let r=all_units[t];return r?r.prefix?["unit",t,n]:["unit",n,t]:n}function move_units_outside_products(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=[],t=[];for(let r of n){let n=get_unit_value_of_tree(r);n?(e.push(n[0]),t.push(n[1])):t.push(r)}let r=["*",...t];for(let t of e)r=add_unit(r,t);return r}return[t,...n.map(move_units_outside_products)]}var simplify$1=Object.freeze({__proto__:null,clean:clean,simplify:simplify,simplify_logical:simplify_logical,evaluate_numbers:evaluate_numbers,collect_like_terms_factors:collect_like_terms_factors,collapse_unary_minus:collapse_unary_minus,simplify_ratios:simplify_ratios,default_order:default_order,perform_vector_matrix_additions_scalar_multiplications:perform_vector_matrix_additions_scalar_multiplications,remove_units:remove_units,add_unit:add_unit,remove_scaling_units:remove_scaling_units});function solve_linear(e,t,n){if("string"==typeof t){void 0===n&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(n=e.context.get_assumptions([e.variables()]));var r=simplify(get_tree(e),n);if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("="===a||"ne"===a||"<"===a||"le"===a||">"===a||"ge"===a){var s=simplify(["+",i[0],["-",i[1]]],n),o=e=>!variables(e).includes(t);if(variables(s=simplify(applyAllTransformations(s,[[["+",["*","_a",t],["*","_b",t]],["*",["+","_a","_b"],t],{variables:{_a:o,_b:o},allow_permutations:!0,allow_extended_match:!0,allow_implicit_identities:["_a","_b"],evaluate_numbers:!0}]],20))).includes(t)){var l=match$2(s,["+",["*","_a",t],"_b"],{variables:{_a:o,_b:o},allow_permutations:!0,allow_implicit_identities:["_a","_b"]});if(l){var u=simplify(l._a),c=simplify(l._b);if(is_nonzero_ast(u,n)){if("="===a||"ne"===a||is_positive_ast(u,n)){let e=simplify(["/",["-",c],u]);return[a,t,e]}if(is_negative_ast(u,n)){var p=simplify(["/",["-",c],u]);return[a="<"===a?">":"le"===a?"ge":">"===a?"<":"le",t,p]}}}}}}}}var solve=Object.freeze({__proto__:null,solve_linear:solve_linear});function clean_assumptions(e,t){if(!Array.isArray(e)||0===e.length)return e;var n=(e=flatten$5(default_order(simplify_logical(expand_relations(e)))))[0],r=e.slice(1);if("and"===n||"or"===n){if(r=r.reduce((function(e,t){return e.every((function(e){return!equal(e,t)}))&&e.push(t),e}),[]),"and"===n&&t&&Array.isArray(t)){let e;e="and"===t[0]?t.slice(1):[t],r=r.filter((t=>e.every((e=>!equal(e,t)))))}e=1===r.length?r[0]:[n].concat(r)}if("and"!==n&&t&&Array.isArray(t)){let n;if(n="and"===t[0]?t.slice(1):[t],!n.every((t=>!equal(t,e))))return}return e}function calculate_derived_assumptions(e,t){if(void 0===t){t=[];for(let n in e.byvar){let r=e.byvar[n];r.length>0&&t.push(r)}if(0===t.length)return{};t=clean_assumptions(t=1===t.length?t[0]:["and"].concat(t))}if(!Array.isArray(t)||0===t.length)return{};var n=t[0],r=t.slice(1);if("and"===n||"or"===n){let t=r.map((function(t){return calculate_derived_assumptions(e,t)})),a=[...new Set(t.reduce(((e,t)=>[...e,...Object.keys(t)]),[]))],i={};for(let r of a){let a=t.reduce((function(e,t){return void 0!==t[r]&&e.push(t[r]),e}),[]);if("and"===n||a.length===t.length){let t=i[r];t=void 0===t?a.length>1?[n].concat(a):a[0]:a.length>1?["and",t,[n].concat(a)]:["and",t,a[0]],i[r]=clean_assumptions(t,get_assumptions(e,r,{omit_derived:!0}))}}return i}let a={};if("="===n||"ne"===n||"<"===n||"le"===n||"in"===n||"subset"===n||"notin"===n||"notsubset"===n){var i=!1;for(let t=0;t<2;t++){let o=r[t],l=r[1-t],u=variables(l);if("string"!=typeof o||0===u.length||u.includes(o))continue;i=!0;var s=n;1===t&&("<"===n?s=">":"le"===n?s="ge":"in"===n?s="ni":"subset"===n?s="superset":"notin"===n?s="notni":"notsubset"===n&&(s="notsuperset"));let c=get_assumptions_for_expr(e,l,[o]);if(c=combine_assumptions(o,s,l,c),void 0!==c){let t=a[o];t=void 0===t?c:["and",t,c],a[o]=clean_assumptions(t,get_assumptions(e,o,{omit_derived:!0}))}}if(i)return a}let o=[];for(let t of r){let n=get_assumptions_for_expr(e,t,[]);void 0!==n&&o.push(n)}if(0===o.length)return{};o=1===o.length?o[0]:["and"].concat(o);for(let n of variables(t))a[n]=clean_assumptions(o,get_assumptions(e,n,{omit_derived:!0}));return a}function get_assumptions_for_expr(e,t,n){let r=variables(t);if(r=r.filter((e=>!n.includes(e))),0===r.length)return;function a(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}var i=["_b"],s=["_b"],o={_b:a},l={};for(let e=0;evoid 0!==e));if(0===e.length)return;return"or"===s?e.length===o.length?["or"].concat(e):void 0:1===e.length?e[0]:["and"].concat(e)}if(!(["=","ne","<","le"].includes(s)||["in","notin","subset","notsubset"].includes(s)&&c)){let r=n.concat(variables(t)),a=[];for(let t of variables(i)){if(r.includes(t))continue;let n=get_assumptions_for_expr(e,t,r);void 0!==n&&a.push(n)}return 0===a.length?i:1===a.length?["and",i,a[0]]:["and",i].concat(a)}let u=[];for(let a=0;a<=1;a++){let i=o[a],c=o[1-a];if("string"==typeof i&&r.includes(i)){var p={};p[i]=c;var d=simplify(substitute$1(t,p)),m=!1,h=s;(1===a&&l[i]>0||0===a&&l[i]<0)&&("<"===s?(m=!0,h=">"):"le"===s?(m=!0,h="ge"):"in"===s?(m=!0,h="ni"):"subset"===s?(m=!0,h="superset"):"notin"===s?(m=!0,h="notni"):"notsubset"===s&&(m=!0,h="notsuperset")),m?u.push([s,d,t]):u.push([s,t,d]);let r=n.concat([i]),o=get_assumptions_for_expr(e,d,r);o=combine_assumptions(t,h,d,o),void 0!==o&&u.push(o)}}if(1===u.length)return u[0];if(u.length>1)return["and"].concat(u);let f=n.concat(variables(t));u=[];for(let t of variables(i)){if(f.includes(t))continue;let n=get_assumptions_for_expr(e,t,f);void 0!==n&&u.push(n)}return 0===u.length?i:1===u.length?["and",i,u[0]]:["and",i].concat(u)}(p)):void 0}function combine_assumptions(e,t,n,r){if(!["=","ne","<","le",">","ge","in","notin","ni","notni","subset","notsubset","superset","notsuperset"].includes(t))return r;if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("and"===a||"or"===a){let r=i.map((r=>combine_assumptions(e,t,n,r))).filter((e=>void 0!==e));if(0===r.length)return;return"or"===a?r.length===i.length?[["or"].concat(r)]:void 0:1===r.length?r[0]:["and"].concat(r)}if(!["=","ne","<","le","in","notin","subset","notsubset"].includes(a))return r;var s,o,l=a;if(equal(i[0],n))s=i[1];else{if(!equal(i[1],n))return r;s=i[0],"<"===a?l=">":"le"===a?l="ge":"in"===a?l="ni":"notin"===a?l="notni":"subset"===a?l="superset":"notsubset"===a&&(l="notsuperset")}if("="===t)o=l;else if("="===l)o=t;else if("<"===t){if("<"!==l&&"le"!==l)return"in"===l||"notin"===l?r:void 0;o="<"}else if("le"===t)if("<"===l)o="<";else{if("le"!==l)return"in"===l||"notin"===l?r:void 0;o="le"}else if(">"===t){if(">"!==l&&"ge"!==l)return"in"===l||"notin"===l?r:void 0;o=">"}else if("ge"===t)if(">"===l)o=">";else{if("ge"!==l)return"in"===l||"notin"===l?r:void 0;o="ge"}else if("in"===t){if("subset"!==l)return;o="in"}else if("notin"===t){if("superset"!==l)return;o="notin"}else if("ni"===t){if("notin"!==l)return;o="notsubset"}else if("notni"===t){if("in"!==l)return;o="notsuperset"}else if("subset"===t)if("subset"===l)o="subset";else if("notni"===l)o="notni";else{if("notsuperset"!==l)return;o="notsuperset"}else if("notsubset"===t){if("superset"!==l)return;o="notsubset"}else if("superset"===t)if("superset"===l)o="superset";else if("ni"===l)o="ni";else{if("notsubset"!==l)return;o="notsubset"}else{if("notsuperset"!==t)return;if("subset"!==l)return;o="notsuperset"}return">"===o?["<",s,e]:"ge"===o?["le",s,e]:"ni"===o?["in",s,e]:"notni"===o?["notin",s,e]:"superset"===o?["subset",s,e]:"notsuperset"===o?["notsubset",s,e]:[o,e,s]}}function filter_assumptions_from_tree(e,t){if(Array.isArray(e)&&0!==e.length){Array.isArray(t)||(t=[t]);var n=e[0],r=e.slice(1);if("and"===n){var a=r.map((function(e){return filter_assumptions_from_tree(e,t)}));return 0===(a=a.filter((e=>void 0!==e))).length?void 0:1===a.length?a[0]:["and"].concat(a)}var i=variables(e);return t.filter((e=>i.includes(e))).length>0?void 0:e}}function get_assumptions_sub(e,t,n,r){Array.isArray(t)||(t=[t]);var a=[];return t.forEach((function(t){if(e.byvar[t]||e.derived[t]){if(e.byvar[t]&&e.byvar[t].length>0){var i=filter_assumptions_from_tree(e.byvar[t],n);void 0!==i&&a.push(i)}if(e.derived[t]&&e.derived[t].length>0&&!r){var s=filter_assumptions_from_tree(e.derived[t],n);void 0!==s&&a.push(s)}}else e.generic.length>0&&("x"!==t&&variables(e.generic).includes(t)||a.push(substitute$1(e.generic,{x:t})))})),1===a.length?a=a[0]:a.length>1&&(a=["and"].concat(a)),a.length>0?clean_assumptions(a):void 0}function get_assumptions(e,t,n){void 0===n&&(n={});var r,a=n.exclude_variables;void 0===a?a=[]:Array.isArray(a)||(a=[a]);var i=get_tree(t);if("string"==typeof i)r=[i];else{if(!Array.isArray(i))return;Array.isArray(i[0])&&(r=i[0])}return r?get_assumptions_sub(e,r,a,n.omit_derived):get_assumptions_for_expr(e,i,a)}function add_assumption(e,t,n){var r=get_tree(t);if(!Array.isArray(r))return 0;var a=add_assumption_sub(e,r=clean_assumptions(simplify(r,e)),n);return a&&(e.derived=calculate_derived_assumptions(e)),a}function add_assumption_sub(e,t,n){if("and"===t[0])return t.slice(1).map((t=>add_assumption_sub(e,t,n))).reduce((function(e,t){return e+t}));var r=variables(t);if(0===r.length)return 0;let a=0;!n&&e.generic.length>0&&r.forEach((function(t){void 0===e.byvar[t]&&("x"!==t&&variables(e.generic).includes(t)||(add_assumption_sub(e,substitute$1(e.generic,{x:t}),!0),a+=1))}));for(let n of r){let r=solve_linear(t,n,e),i=t;r&&(i=r);let s=e.byvar[n];void 0!==s&&0!==s.length&&(i=["and",s,i]),i=clean_assumptions(i),equal(i,s)||(e.byvar[n]=i,a+=1)}return a}function add_generic_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=add_generic_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function add_generic_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>add_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;let n=solve_linear(t,"x",e),r=t;n&&(r=n);let a=e.generic;return 0!==a.length&&(r=["and",a,r]),r=clean_assumptions(r),equal(r,a)?0:(e.generic=r,1)}function remove_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=remove_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function remove_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>remove_assumption_sub(e,t))).reduce((function(e,t){return e+t}));var n=variables(t);if(0===n.length)return 0;var r=0;for(let a of n){let n=solve_linear(t,a,e),i=e.byvar[a];if(!i||0===i.length)continue;let s,o=i[0],l=i.slice(1),u=l.length;if("and"===o)if(l=l.filter((e=>!(equal(e,t)||equal(e,n)))),0===l.length)s=[];else if(1===l.length)s=l[0];else{if(!(l.lengthremove_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;var n=e.generic;if(0===n.length)return 0;let r=solve_linear(t,"x",e);var a,i=n[0],s=n.slice(1),o=s.length;if("and"===i)if(0===(s=s.filter((e=>!(equal(e,t)||equal(e,r))))).length)a=[];else if(1===s.length)a=s[0];else{if(!(s.length0)if(e.includes(".")){if("0"!==e[0]?n++:n+=e.match(/^0\.0*/)[0].length,e.length0)if(e.includes(".")){let t=e.match(/\.\d*$/)[0].length-1;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" \\le ")},ge:function(e){return e.join(" \\ge ")},ne:function(e){return e.join(" \\ne ")},in:function(e){return e[0]+" \\in "+e[1]},notin:function(e){return e[0]+" \\notin "+e[1]},ni:function(e){return e[0]+" \\ni "+e[1]},notni:function(e){return e[0]+" \\not\\ni "+e[1]},subset:function(e){return e[0]+" \\subset "+e[1]},subseteq:function(e){return e[0]+" \\subseteq "+e[1]},notsubset:function(e){return e[0]+" \\not\\subset "+e[1]},notsubseteq:function(e){return e[0]+" \\not\\subseteq "+e[1]},superset:function(e){return e[0]+" \\supset "+e[1]},superseteq:function(e){return e[0]+" \\supseteq "+e[1]},notsuperset:function(e){return e[0]+" \\not\\supset "+e[1]},notsuperseteq:function(e){return e[0]+" \\not\\supseteq "+e[1]},union:function(e){return e.join(" \\cup ")},intersect:function(e){return e.join(" \\cap ")},perp:function(e){return e.join(" \\perp ")},parallel:function(e){return e.join(" \\parallel ")},derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},partial_derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},"|":function(e){return e[0]+" \\mid "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"\\binom{"+e[0]+"}{"+e[1]+"}"},vec:function(e){return"\\vec{"+e[0]+"}"},linesegment:function(e){return"\\overline{"+e.join(" ")+"}"},angle:function(e,t){return t?"\\angle "+e.join(""):"\\angle\\left( "+e.join(", ")+" \\right)"},unit:function(e){return"\\circ"===e[1]?e[0]+"^{\\circ}":e[0]+" "+e[1]}},allowedLatexSymbolsDefault$1=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","arg","Re","Im","det","angle","perp","circ","%","$","int"],convertLatexSymbolsDefault={acos:"arccos",acosh:"arccosh",acot:"arccot",acoth:"arccoth",acsc:"arccsc",acsch:"arccsch",asec:"arcsec",asech:"arcsech",asin:"arcsin",asinh:"arcsinh",atan:"arctan",atanh:"arctanh",deg:"circ"},matrixEnvironmentDefault="bmatrix";class astToLatex$1{constructor({allowedLatexSymbols:e=allowedLatexSymbolsDefault$1,convertLatexSymbols:t=convertLatexSymbolsDefault,matrixEnvironment:n=matrixEnvironmentDefault,padToDigits:r=null,padToDecimals:a=null,showBlanks:i=!0}={}){this.allowedLatexSymbols=e,this.convertLatexSymbols=t,this.matrixEnvironment=n,this.padToDigits=r,this.padToDecimals=a,this.showBlanks=i}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);var t=e[0],n=e.slice(1);if("ldots"===t)return"\\ldots";if(!(t in operators$1)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);var t=e[0],n=e.slice(1);if("not"===t)return operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this)));if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"subseteq"===t||"notsubseteq"===t||"superset"===t||"notsuperset"===t||"superseteq"===t||"notsuperseteq"===t)return operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":a+="lts"===t?" \\le ":" \\ge ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t?1===n.length?"+"+this.term(n[0]):operators$1[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):["union","intersect","perp","parallel"].includes(t)?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"-"===t?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):"*"===t?operators$1[t](n.map(function(e,t){let r;return t>0?(r=this.factorWithParenthesesIfNegatedOrExplicitPlus(e),r.match(/^[0-9]/)?"\\cdot "+r:"angle"===e[0]&&n.length>1?"\\left( "+r+" \\right)":r):(r=this.factor(e),"angle"===e[0]&&n.length>1?"\\left( "+r+" \\right)":r)}.bind(this))):"/"===t||"unit"===t?operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this))):this.factor(e)}simple_factor_or_function_or_parens(e){var t=this.factor(e);return!!(t.length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]&&"sqrt"!==e[1]||t.match(/^\\left\(.*\\right\)$/)||t.match(/^\\left\\langle.*\\right\\rangle$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}stringConvert(e){return e.length>1?(this.convertLatexSymbols[e]&&(e=this.convertLatexSymbols[e]),this.allowedLatexSymbols.includes(e)?"\\"+e:"\\operatorname{"+e+"}"):this.allowedLatexSymbols.includes(e)?"\\"+e:"_"!==e||this.showBlanks?e:""}factor(e){if("string"==typeof e)return this.stringConvert(e);if("number"==typeof e){if(e===1/0)return"\\infty";if(e===-1/0)return"-\\infty";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if("+"===a[0]&&(a=a.slice(1)),null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return r+" \\cdot 10^{"+a+"}"}}if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1]))return n[0]<0?"\\left("+n[0].toString()+"\\right)^{"+n[1].toString()+"}":n[0].toString()+"^{"+n[1].toString()+"}";let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];return this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="\\left("+e.toString()+"\\right)"),e+"^{"+this.statement(n[1])+"}"}if("_"===t){let e=this.factor(n[0]);return this.simple_factor_or_function_or_parens(n[0])||(e="\\left("+e.toString()+"\\right)"),e+"_{"+this.statement(n[1])+"}"}if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="\\left("+r+"\\right)");for(let e=0;e1?o=o.trimRight()+"^{"+i+"}"+this.stringConvert(s):o+=this.stringConvert(s),o="\\frac{ "+o+" }{ ";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,o=o+e+this.stringConvert(i),r>1&&(o=o+"^{"+r+"}"),o+=" "}return o+="}",o}if("apply"===t){if("abs"===n[0])return"\\left|"+this.statement(n[1])+"\\right|";if("floor"===n[0])return"\\left\\lfloor "+this.statement(n[1])+" \\right\\rfloor";if("ceil"===n[0])return"\\left\\lceil "+this.statement(n[1])+" \\right\\rceil";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"\\left("+e+"\\right)!"}if("sqrt"===n[0])return"\\sqrt{"+this.statement(n[1])+"}";let e,t=n[0];if("^"===t[0]&&(t=t[1]),"_"===t[0]&&(t=t[1]),"int"===t){let e,t=this.factor(n[0]),r=n[1];if(Array.isArray(r)&&"*"===r[0]){let t=[],n=["*"];for(let e=1;e0&&(e[e.length-1].match(/[a-zA-Z]/)&&(e+="\\,"),e+=t.map((e=>"d"+this.factor(e[1]))).join("\\,"))}return e||(e=this.term(n[1])),t+" "+e}e="log10"===n[0]?"\\log_{10}":"re"===n[0]?"\\Re":"im"===n[0]?"\\Im":this.factor(n[0]);let r=this.statement(n[1]);return"tuple"!==n[1][0]&&(r="\\left("+r+"\\right)"),e+r}if("angle"===t){let e=n.every((e=>{if("string"==typeof e&&1===e.length)return!0;if(!Array.isArray(e))return!1;let t=e[0];return"_"===t||"^"===t||"prime"===t}));return operators$1[t](n.map(function(e,t){return this.statement(e)}.bind(this)),e)}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"\\left("+this.statement(e)+"\\right)"}factorWithParenthesesIfNegatedOrExplicitPlus(e){var t=this.factor(e);return t.match(/^-/)||t.match(/^\+/)?"\\left("+t+"\\right)":t}termWithPlusIfNotNegated(e){var t=this.term(e);return t.match(/^-/)?t.match(/^-[^ ]/)?"- "+t.slice(1):t:"+ "+t}}const textToAst$2=new textToAst$4,astToLatex=new astToLatex$1;var derivatives={sin:textToAst$2.convert("cos x"),cos:textToAst$2.convert("-(sin x)"),tan:textToAst$2.convert("(sec x)^2"),cot:textToAst$2.convert("-((csc x)^2)"),sec:textToAst$2.convert("(sec x)*(tan x)"),csc:textToAst$2.convert("-(csc x)*(cot x)"),sqrt:textToAst$2.convert("1/(2*sqrt(x))"),log:textToAst$2.convert("1/x"),ln:textToAst$2.convert("1/x"),exp:textToAst$2.convert("exp(x)"),arcsin:textToAst$2.convert("1/sqrt(1 - x^2)"),arccos:textToAst$2.convert("-1/sqrt(1 - x^2)"),arctan:textToAst$2.convert("1/(1 + x^2)"),arccsc:textToAst$2.convert("-1/(sqrt(-1/x^2 + 1)*x^2)"),arcsec:textToAst$2.convert("1/(sqrt(-1/x^2 + 1)*x^2)"),arccot:textToAst$2.convert("-1/(1 + x^2)"),abs:textToAst$2.convert("abs(x)/x")};function derivative(e,t,n=[]){var r=get_tree(e),a="\\frac{d}{d"+t+"} ";if("number"==typeof r)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if(variables(r).indexOf(t)<0)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if("string"==typeof r)return t===r?(n.push("We know the derivative of the identity function is one, that is, \\("+a+astToLatex.convert(r)+" = 1\\)."),1):(n.push("As far as \\("+astToLatex.convert(t)+"\\) is concerned, \\("+astToLatex.convert(r)+"\\) is constant, so "+a+astToLatex.convert(r)+" = 0\\)."),0);if(!Array.isArray(r))return null;var i=r[0],s=r.slice(1);if("+"===i||"-"===i||"~"===i){n.push("Using the sum rule, \\("+a+astToLatex.convert(r)+" = "+s.map((function(e,t){return a+astToLatex.convert(e)})).join(" + ")+"\\).");let e=[i].concat(s.map((function(e,r){return derivative(e,t,n)})));return e=simplify(e),n.push("So using the sum rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("*"===i){let e=[],i=[];for(let n=0;n0){if(0===e.length)return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = 0.\\)"),0;let s=["*"].concat(e);if(1===e.length&&(s=e[0]),s===t){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+"\\).");let e=["*"].concat(i);return e=simplify(e),e}n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+" \\cdot "+a+"\\left("+astToLatex.convert(s)+"\\right)\\).");let o=derivative(s,t,n),l=["*"].concat(i.concat([o]));return l=simplify(l),n.push("And so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the product rule, \\("+a+astToLatex.convert(r)+" = "+s.map((function(e,t){return s.map((function(n,r){return t===r?a+"\\left("+astToLatex.convert(e)+"\\right)":astToLatex.convert(n)})).join(" \\cdot ")})).join(" + ")+"\\).");let o=s.slice(),l=["+"].concat(s.map((function(e,r){return["*"].concat(o.map((function(e,a){if(r===a){let r=derivative(e,t,n);return 1===r?null:r}return e})).filter((function(e){return null!=e})))})));return l=simplify(l),n.push("So using the product rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("/"===i){let e=s[0],i=s[1];if(variables(i).indexOf(t)<0){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(["/",1,i])+" \\cdot "+a+"\\left("+astToLatex.convert(e)+"\\right)\\).");let s=derivative(e,t,n),o=textToAst$2.convert("(1/g)*d"),l=substitute$1(o,{d:s,g:i});return l=simplify(l),n.push("So \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if(variables(e).indexOf(t)<0){1!==e&&n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+" \\cdot "+a+"\\left("+astToLatex.convert(["/",1,i])+"\\right)\\)."),n.push("Since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\cdot \\frac{-1}{ "+astToLatex.convert(i)+"^2} \\cdot "+a+astToLatex.convert(i)+"\\).");let s=derivative(i,t,n),o=textToAst$2.convert("f * (-a/(g^2))"),l=substitute$1(o,{f:e,a:s,g:i});return l=simplify(l),n.push("So since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the quotient rule, \\("+a+astToLatex.convert(r)+" = \\frac{"+a+"\\left("+astToLatex.convert(e)+"\\right) \\cdot "+astToLatex.convert(i)+" - "+astToLatex.convert(e)+"\\cdot "+a+"\\left("+astToLatex.convert(i)+"\\right)}{ \\left( "+astToLatex.convert(i)+" \\right)^2} \\).");let o=derivative(e,t,n),l=derivative(i,t,n),u=textToAst$2.convert("(a * g - f * b)/(g^2)"),c=substitute$1(u,{a:o,b:l,f:e,g:i});return c=simplify(c),n.push("So using the quotient rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}if("^"===i){let e=s[0],i=s[1];if(variables(i).indexOf(t)<0){if("string"==typeof e&&"x"===e){if("number"==typeof i){let t=textToAst$2.convert("n * (f^m)"),s=substitute$1(t,{n:i,m:i-1,f:e});return s=simplify(s),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),s}let t=textToAst$2.convert("n * (f^(n-1))"),s=substitute$1(t,{n:i,f:e});return s=simplify(s),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),s}1!==i&&n.push("By the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"} \\cdot "+a+astToLatex.convert(e)+"\\).");let s=derivative(e,t,n);if(1===i)return s;if("number"==typeof i){let t=textToAst$2.convert("n * (f^m) * a"),o=substitute$1(t,{n:i,m:i-1,f:e,a:s});return o=simplify(o),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}let o=textToAst$2.convert("n * (f^(n-1)) * a"),l=substitute$1(o,{n:i,f:e,a:s});return l=simplify(l),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("e"===e&&math$1.define_e){if("string"==typeof i&&i===t){let e=textToAst$2.convert("e^(f)"),s=substitute$1(e,{f:i});return s=simplify(s),n.push("The derivative of \\(e^"+astToLatex.convert(t)+"\\) is itself, that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+"\\)."),s}n.push("Using the rule for \\(e^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let e=textToAst$2.convert("e^(f)*d"),s=derivative(i,t,n),o=substitute$1(e,{f:i,d:s});return o=simplify(o),n.push("So using the rule for \\(e^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}if("number"==typeof e){if("string"==typeof i&&i===t){let s=textToAst$2.convert("a^(f) * log(a)"),o=substitute$1(s,{a:e,f:i});return o=simplify(o),n.push("The derivative of \\(a^"+astToLatex.convert(t)+"\\) is \\(a^{"+astToLatex.convert(t)+"} \\, \\log a\\), that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}let s=textToAst$2.convert("a^(f) * log(a)"),o=substitute$1(s,{a:e,f:i});n.push("Using the rule for \\(a^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let l=textToAst$2.convert("a^(b)*log(a)*d"),u=derivative(i,t,n),c=substitute$1(l,{a:e,b:i,d:u});return c=simplify(c),n.push("So using the rule for \\(a^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}let o=e,l=i;n.push("Recall the general rule for exponents, namely that \\(\\frac{d}{dx} u(x)^{v(x)} = u(x)^{v(x)} \\cdot \\left( v'(x) \\cdot \\log u(x) + \\frac{v(x) \\cdot u'(x)}{u(x)} \\right)\\). In this case, \\(u(x) = "+astToLatex.convert(o)+"\\) and \\(v(x) = "+astToLatex.convert(l)+"\\).");let u=derivative(o,t,n),c=derivative(l,t,n),p=textToAst$2.convert("(f^g)*(b * log(f) + (g * a)/f)"),d=substitute$1(p,{a:u,b:c,f:o,g:l});return d=simplify(d),n.push("So by the general rule for exponents, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(d)+"\\)."),d}if("apply"===i&&!(s[0]in derivatives)){let e=s[1];n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(["apply",s[0]+"'","x"],{x:e}))+" \\cdot "+a+astToLatex.convert(e)+"\\).");let i=["*",substitute$1(["apply",s[0]+"'","x"],{x:e}),derivative(e,t,n)];return i=simplify(i),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+"\\)."),i}if("apply"===i&&s[0]in derivatives||i in derivatives){let e=!1;"apply"===i&&(i=s[0],s=s.slice(1),e=!0);let o=s[0];if("number"==typeof o){let e=0;return n.push("The derivative of a constant is zero so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof o&&o===t){let e=["*",substitute$1(derivatives[i],{x:o})];return e=simplify(e),n.push("It is the case that \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof o&&o!==t){let e=0;return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}{let s=[i,"u"];e&&(s=["apply"].concat(s)),n.push("Recall \\(\\frac{d}{du}"+astToLatex.convert(s)+" = "+astToLatex.convert(derivative(s,"u",[]))+"\\)."),n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(derivatives[i],{x:o}))+" \\cdot "+a+astToLatex.convert(o)+"\\).");let l=["*",substitute$1(derivatives[i],{x:o}),derivative(o,t,n)];return l=simplify(l),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}}return 0}function lowercaseFirstLetter(e){return e.charAt(0).toLowerCase()+e.slice(1)}function simplify_story(e){for(let t=e.length-1;t>=1;t--)e[t]===e[t-1]&&e.splice(t,1);for(let t=0;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" ≤ ")},ge:function(e){return e.join(" ≥ ")},ne:function(e){return e.join(" ≠ ")},in:function(e){return e[0]+" ∈ "+e[1]},notin:function(e){return e[0]+" ∉ "+e[1]},ni:function(e){return e[0]+" ∋ "+e[1]},notni:function(e){return e[0]+" ∌ "+e[1]},subset:function(e){return e[0]+" ⊂ "+e[1]},subseteq:function(e){return e[0]+" ⊆ "+e[1]},notsubset:function(e){return e[0]+" ⊄ "+e[1]},notsubseteq:function(e){return e[0]+" ⊈ "+e[1]},superset:function(e){return e[0]+" ⊃ "+e[1]},superseteq:function(e){return e[0]+" ⊇ "+e[1]},notsuperset:function(e){return e[0]+" ⊅ "+e[1]},notsuperseteq:function(e){return e[0]+" ⊉ "+e[1]},union:function(e){return e.join(" ∪ ")},intersect:function(e){return e.join(" ∩ ")},perp:function(e){return e.join(" ⟂ ")},parallel:function(e){return e.join(" ∥ ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"binom( "+e[0]+", "+e[1]+" )"},vec:function(e){return"vec("+e[0]+")"},linesegment:function(e){return"linesegment( "+e.join(", ")+" )"},angle:function(e,t){return t?"∠"+e.join(""):"∠( "+e.join(", ")+" )"},unit:function(e){return e[0]+" "+e[1]}},nonunicode_operators={"+":function(e){return e.join(" ")},"-":function(e){return"-"+e[0]},"*":function(e){return e.join(" ")},"/":function(e){return e[0]+"/"+e[1]},_:function(e){return e[0]+"_"+e[1]},"^":function(e){return e[0]+"^"+e[1]},prime:function(e){return e[0]+"'"},tuple:function(e){return"( "+e.join(", ")+" )"},array:function(e){return"[ "+e.join(", ")+" ]"},list:function(e){return e.join(", ")},set:function(e){return"{ "+e.join(", ")+" }"},vector:function(e){return"( "+e.join(", ")+" )"},altvector:function(e){return"( "+e.join(", ")+" )"},interval:function(e){return"( "+e.join(", ")+" )"},matrix:function(e){return"( "+e.join(", ")+" )"},and:function(e){return e.join(" and ")},or:function(e){return e.join(" or ")},not:function(e){return"not "+e[0]},"=":function(e){return e.join(" = ")},"<":function(e){return e.join(" < ")},">":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" <= ")},ge:function(e){return e.join(" >= ")},ne:function(e){return e.join(" ne ")},in:function(e){return e[0]+" elementof "+e[1]},notin:function(e){return e[0]+" notelementof "+e[1]},ni:function(e){return e[0]+" containselement "+e[1]},notni:function(e){return e[0]+" notcontainselement "+e[1]},subset:function(e){return e[0]+" subset "+e[1]},subseteq:function(e){return e[0]+" subseteq "+e[1]},notsubset:function(e){return e[0]+" notsubset "+e[1]},notsubseteq:function(e){return e[0]+" notsubseteq "+e[1]},superset:function(e){return e[0]+" superset "+e[1]},superseteq:function(e){return e[0]+" superseteq "+e[1]},notsuperset:function(e){return e[0]+" notsuperset "+e[1]},notsuperseteq:function(e){return e[0]+" notsuperseteq "+e[1]},union:function(e){return e.join(" union ")},intersect:function(e){return e.join(" intersect ")},perp:function(e){return e.join(" perp ")},parallel:function(e){return e.join(" parallel ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"binom( "+e[0]+", "+e[1]+" )"},vec:function(e){return"vec("+e[0]+")"},linesegment:function(e){return"linesegment( "+e.join(", ")+" )"},angle:function(e,t){return t?"angle "+e.join(""):"angle( "+e.join(", ")+" )"},unit:function(e){return e[0]+" "+e[1]}},output_unicodeDefault=!0;class astToText$2{constructor({output_unicode:e=output_unicodeDefault,padToDigits:t=null,padToDecimals:n=null,showBlanks:r=!0}={}){this.output_unicode=e,this.operators=unicode_operators,e||(this.operators=nonunicode_operators),this.padToDigits=t,this.padToDecimals=n,this.showBlanks=r}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);let t=e[0],n=e.slice(1);if("ldots"===t)return"...";if(!(t in this.operators)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\(.*\)$/)?"("+n+")":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);let t=e[0],n=e.slice(1);if("not"===t)return this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\(.*\)$/)?"("+n+")":n}.bind(this)));if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"subseteq"===t||"notsubseteq"===t||"superset"===t||"notsuperset"===t||"superseteq"===t||"notsuperseteq"===t)return this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":"lts"===t?this.output_unicode?a+=" ≤ ":a+=" <= ":this.output_unicode?a+=" ≥ ":a+=" >= ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);let t=e[0],n=e.slice(1);return"+"===t?1===n.length?"+"+this.term(n[0]):this.operators[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):["union","intersect","perp","parallel"].includes(t)?this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);let t=e[0],n=e.slice(1);if("-"===t)return this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this)));if("*"===t)return this.operators[t](n.map(function(e,t){let r;return t>0?(r=this.factorWithParenthesesIfNegatedOrExplicitPlus(e),r.match(/^[0-9]/)?"* "+r:"angle"===e[0]&&n.length>1?"( "+r+" )":r):(r=this.factor(e),"angle"===e[0]&&n.length>1?"( "+r+" )":r)}.bind(this)));if("/"===t){let e=this.factor(n[0]),r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[0])||(e="("+e+")"),this.simple_factor_or_function_or_parens(n[1])||(r="("+r+")"),this.operators[t]([e,r])}return"unit"===t?this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this))):this.factor(e)}symbolConvert(e){let t={alpha:"α",beta:"β",Gamma:"Γ",gamma:"γ",Delta:"Δ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",Theta:"ϴ",theta:"θ",iota:"ι",kappa:"κ",Lambda:"Λ",lambda:"λ",mu:"μ",nu:"ν",Xi:"Ξ",xi:"ξ",Pi:"Π",pi:"π",rho:"ρ",Sigma:"Σ",sigma:"σ",tau:"τ",Upsilon:"Υ",upsilon:"υ",Phi:"Φ",phi:"ϕ",Psi:"Ψ",psi:"ψ",Omega:"Ω",omega:"ω",perp:"⟂",int:"∫"};return this.output_unicode&&e in t?t[e]:this.showBlanks||"_"!==e?e:""}simple_factor_or_function_or_parens(e){let t=this.factor(e);return!!(t.length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]||t.match(/^\(.*\)$/)||t.match(/^⟨.*⟩$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}factor(e){if("string"==typeof e)return this.symbolConvert(e);if("number"==typeof e){if(e===1/0)return this.output_unicode?"∞":"infinity";if(e===-1/0)return this.output_unicode?"-∞":"-infinity";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if(null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return"+"===a[0]?r+" * 10^"+a.substring(1):r+" * 10^("+a+")"}}if(!Array.isArray(e))return"";let t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1])){let e;return e=n[0]<0?"("+n[0].toString()+")":n[0].toString(),n[1]<0?e+"^("+n[1].toString()+")":e+"^"+n[1].toString()}let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="("+e.toString()+")");let r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||(r="("+r.toString()+")"),e+"^"+r}if("_"===t)return this.operators[t](n.map(function(e,t){let n=this.factor(e);return this.simple_factor_or_function_or_parens(e)?n:"("+n+")"}.bind(this)));if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="("+r+")");for(let e=0;e1&&(o=o+"^"+i),o=o+this.symbolConvert(s)+"/";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,o=o+e+this.symbolConvert(i),r>1&&(o=o+"^"+r)}return o}if("apply"===t){if("abs"===n[0])return"|"+this.statement(n[1])+"|";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"("+e+")!"}let e=n[0];if("^"===e[0]&&(e=e[1]),"_"===e[0]&&(e=e[1]),"int"===e){let e,t=this.factor(n[0]),r=n[1];if(Array.isArray(r)&&"*"===r[0]){let t=[],n=["*"];for(let e=1;e0&&(e+=" "+t.map((e=>"d"+this.factor(e[1]))).join(" "))}return e||(e=this.term(n[1])),t+" "+e}let t=this.factor(n[0]),r=this.statement(n[1]);return"tuple"!==n[1][0]&&(r="("+r+")"),t+r}if("angle"===t){let e=n.every((e=>{if("string"==typeof e&&1===e.length)return!0;if(!Array.isArray(e))return!1;let t=e[0];return"_"===t||"^"===t||"prime"===t}));return this.operators[t](n.map(function(e,t){return this.statement(e)}.bind(this)),e)}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"("+this.statement(e)+")"}factorWithParenthesesIfNegatedOrExplicitPlus(e){var t=this.factor(e);return t.match(/^-/)||t.match(/^\+/)?"("+t+")":t}termWithPlusIfNotNegated(e){let t=this.term(e);return t.match(/^-/)?t.match(/^-[^ ]/)?"- "+t.slice(1):t:"+ "+t}}var astToText$1=new astToText$2;function subscripts_to_strings(e,t=!1){var n=get_tree(e);if(!Array.isArray(n))return n;let r=n[0],a=n.slice(1);return"_"===r&&(t||a.every((e=>["number","string"].includes(typeof e))))?astToText$1.convert(n):[r].concat(a.map((e=>subscripts_to_strings(e,t))))}function strings_to_subscripts(e){var t=get_tree(e);if("string"==typeof t){let e=t.match(/^([0-9a-zA-Z]+)_([a-zA-Z]+|[0-9]+)$/);if(e){let t=Number(e[1]);isNaN(t)&&(t=e[1]);let n=Number(e[2]);return isNaN(n)&&(n=e[2]),["_",t,n]}return t}if(!Array.isArray(t))return t;let n=t[0],r=t.slice(1);return[n].concat(r.map(strings_to_subscripts))}var normalization=Object.freeze({__proto__:null,normalize_function_names:normalize_function_names,normalize_applied_functions:normalize_applied_functions,log_subscript_to_two_arg_log:log_subscript_to_two_arg_log,substitute_abs:substitute_abs,default_order:default_order,constants_to_floats:constants_to_floats,normalize_angle_linesegment_arg_order:normalize_angle_linesegment_arg_order,tuples_to_vectors:tuples_to_vectors,to_intervals:to_intervals,altvectors_to_vectors:altvectors_to_vectors,subscripts_to_strings:subscripts_to_strings,strings_to_subscripts:strings_to_subscripts}),astToText=new astToText$2;function generate_random_integer(e,t,n){return e=math$1.ceil(e),t=math$1.floor(t),math$1.floor(n()*(t-e+1))+e}const equals$5=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i=1e-12,absolute_tolerance:s=0,tolerance_for_zero:o=1e-15,allowed_error_in_numbers:l=0,include_error_in_number_exponents:u=!1,allowed_error_is_absolute:c=!1,rng:p}){if(Array.isArray(e.tree)&&Array.isArray(t.tree)){let d=e.tree[0],m=e.tree.slice(1),h=t.tree[0],f=t.tree.slice(1);if("tuple"===d||"vector"===d||"altvector"===d||"list"===d||"array"===d||"matrix"===d||"interval"===d){if(h!==d)return!1;if(f.length!==m.length)return!1;for(let e=0;e","<","ge","le"].includes(d)){if(2!==f.length)return!1;if(">"===d?(d="<",m=[m[1],m[0]]):"ge"===d&&(d="le",m=[m[1],m[0]]),">"===h?(h="<",f=[f[1],f[0]]):"ge"===h&&(h="le",f=[f[1],f[0]]),d!==h)return!1;let e=["+",m[0],["-",m[1]]],t=["+",f[0],["-",f[1]]],y="="!==d;return component_equals({expr:r.fromAst(e),other:a.fromAst(t),randomBindings:n,expr_context:r,other_context:a,allow_proportional:!0,require_positive_proportion:y,relative_tolerance:i,absolute_tolerance:s,tolerance_for_zero:o,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})}}return component_equals({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i,absolute_tolerance:s,tolerance_for_zero:o,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})},component_equals=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,allow_proportional:i=!1,require_positive_proportion:s=!1,relative_tolerance:o,absolute_tolerance:l,tolerance_for_zero:u,allowed_error_in_numbers:c,include_error_in_number_exponents:p,allowed_error_is_absolute:d,rng:m}){var h=1e-20*Number.MAX_VALUE;e=e.normalize_function_names(),t=t.normalize_function_names(),e=e.log_subscript_to_two_arg_log(),t=t.log_subscript_to_two_arg_log(),e=e.subscripts_to_strings(),t=t.subscripts_to_strings(),e=e.normalize_applied_functions(),t=t.normalize_applied_functions();let f=rename_functions_with_exponents(e.tree),y=rename_functions_with_exponents(t.tree);e=r.fromAst(rename_vecs(f)),t=a.fromAst(rename_vecs(y));var g=[...new Set([...e.variables(),...t.variables()])];math$1.define_pi&&(g=g.filter((function(e){return"pi"!==e}))),math$1.define_i&&(g=g.filter((function(e){return"i"!==e}))),math$1.define_e&&(g=g.filter((function(e){return"e"!==e})));var b=[];for(let e=0;e1===e.length||e.includes("_")||e.includes("^"))),N=v.filter((e=>g.includes(e)));if(v=v.filter((e=>!g.includes(e))),N.length>0){let n=e.tree,i=t.tree,s="x1";for(;[...v,...g].includes(s);)s+="x1";let o="x2";for(;[...v,...g].includes(o);)o+="x2";for(let e of N){let t=e+e;for(;[...v,...g].includes(t);)t+=e;let r=[[["apply",e,s],["apply",t,s],{variables:{[s]:!0}}]];n=applyAllTransformations(n,r),i=applyAllTransformations(i,r),v.push(t)}e=r.fromAst(n),t=a.fromAst(i)}try{var T=e.f(),C=t.f()}catch(n){return e.equalsViaSyntax(t,{allow_blanks:!0})}let A,V,x;if(c>0){let t=replace_numbers_with_parameters({expr:e,variables:g,include_exponents:p});A=r.fromAst(t.expr_with_params),V=t.parameters;let n=Object.keys(V);if(n.length>0){let t=A.derivative(n[0]);if(d||(t=t.multiply(V[n[0]])),n.length>1)for(let e of n.slice(1)){let n=A.derivative(e);d||(n=n.multiply(V[e])),t=t.add(n)}let r=t.multiply(c);try{x=r.f()}catch(e){}}}var S=[10,1,100,.1,1e3,.01],w=0;let E=0,D=!0,O=0;for(let t=0;t<1e3;t++){try{var I=R(S[w],m)}catch(e){continue}if(!1===I.always_zero&&(D=!1),!I.equal&&!I.out_of_bounds&&!I.always_zero&&!1!==I.sufficient_finite_values&&(O++,O>100))return!1;if(I.equal){if(I.always_zero){if(!D)continue;if(E+=1,E>5&&(w+=1,E=0),w>=S.length)return!0;continue}return!0}}return!1;function R(e,t){var r,a=n(t,g,e);for(let e=0;e0)||!(0===m||m>0))return{out_of_bounds:!0,always_zero:!1};var f=Math.min(d,m),y=Math.max(d,m),N=1;let A=0;if(x){try{A=math$1.abs(x(r))}catch(e){return{equal_at_start:!1,always_zero:!1}}if(!Number.isFinite(A))return{equal_at_start:!1,always_zero:!1}}if(A+=f*o,A=Math.min(A,.1*f),A+=0!==A||0!==c&&0!==p?l:u,!(0===y||math$1.abs(math$1.subtract(c,p))0))return{equal_at_start:!1,always_zero:!1}}var S=0===y,w=0;for(let r=0;r<100;r++){var E,D=n(t,g,.01,a);for(let e=0;e=10)return{equal:!0,always_zero:S}}}return{sufficient_finite_values:!1,always_zero:S}}};function replace_numbers_with_parameters({expr:e,variables:t,include_exponents:n=!1}){let r={},a=0;function i(){a++;let e="par"+a;for(;t.includes(e);)a++,e="par"+a;return e}return{expr_with_params:function e(t){if("number"==typeof t){if(0===t)return t;{let e=i();return r[e]=t,e}}if("string"==typeof t){if("pi"===t){if(math$1.define_pi){let e=i();return r[e]=math$1.PI,e}}else if("e"===t&&math$1.define_e){let e=i();return r[e]=math$1.e,e}return t}if(!Array.isArray(t))return t;let a=t[0],s=t.slice(1);return"^"!==a||n?[a,...s.map(e)]:[a,e(s[0]),s[1]]}((e=e.evaluate_numbers({max_digits:1/0})).tree),parameters:r}}function rename_functions_with_exponents(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("apply"===t){let e=n[0];return Array.isArray(e)&&"^"===e[0]&&e.slice(1).every((e=>["number","string"].includes(typeof e)))&&(e=astToText.convert(e)),["apply",e,n[1]]}return[t,...n.map(rename_functions_with_exponents)]}function rename_vecs(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return"vec"===t&&1===n.length?"__vec_"+astToText.convert(n[0]):[t,...n.map(rename_vecs)]}function randomComplexBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=math$1.complex(2*e()*n-n,2*e()*n-n)})):t.forEach((function(t){a[t]=math$1.complex(r[t].re+2*e()*n-n,r[t].im+2*e()*n-n)})),a}const equals$4=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:s=!1,allowed_error_is_absolute:o=!1,allow_blanks:l=!1}={}){if(!l&&(e.variables().includes("_")||t.variables().includes("_")))return!1;let u=seedrandom$1("complex_seed");return e=e.remove_scaling_units(),t=t.remove_scaling_units(),!(!e.isAnalytic({allow_abs:!0,allow_arg:!0,allow_relation:!0})||!t.isAnalytic({allow_abs:!0,allow_arg:!0,allow_relation:!0}))&&equals$5({expr:e,other:t,randomBindings:randomComplexBindings,expr_context:e.context,other_context:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:s,allowed_error_is_absolute:o,rng:u})};function randomRealBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=2*e()*n-n})):t.forEach((function(t){a[t]=r[t]+2*e()*n-n})),a}const equals$3=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:s=!1,allowed_error_is_absolute:o=!1}={}){if(!e.isAnalytic()||!t.isAnalytic())return!1;let l=seedrandom("real_seed");return equals$5({expr:e,other:t,randomBindings:randomRealBindings,expr_context:e.context,other_content:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:s,allowed_error_is_absolute:o,rng:l})},equals$2=function(e,t,{allowed_error_in_numbers:n=0,include_error_in_number_exponents:r=!1,allowed_error_is_absolute:a=!1,allow_blanks:i=!1}={}){if(!i&&(e.variables().includes("_")||t.variables().includes("_")))return!1;let s=e.normalize_function_names().normalize_applied_functions().normalize_angle_linesegment_arg_order(),o=t.normalize_function_names().normalize_applied_functions().normalize_angle_linesegment_arg_order();return equal(s.tree,o.tree,{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})},equals$1=function(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_discrete_infinite_set(e))return!1;if(is_discrete_infinite_set(t)){var a=[];let n=e.context.get_assumptions(e);if(void 0!==n&&a.push(n),n=t.context.get_assumptions(t),void 0!==n&&a.push(n),a=0===a.length?void 0:1===a.length?a[0]:clean_assumptions(["and"].concat(a)),r){let n=contained_in(e.tree,t.tree,a,r);if(!1===n)return 0;let i=contained_in(t.tree,e.tree,a,r);return!1===i?0:!0===n?!0===i?1:i:!0===i?n:Math.min(n,i)}return contained_in(e.tree,t.tree,a,r)&&contained_in(t.tree,e.tree,a,r)}{let r=t.tree;if("list"!==r[0])return!1;let a=r.length-2;if("ldots"!==r[a+1][0])return!1;if(acontained_in(e,t,n)))}var a=e[1],i=e[2],s=e[3],o=e[4];if(!Array.isArray(s)||"-"!==s[0]||s[1]!==1/0||o!==1/0)return!1;a=simplify(["/",a,i],n,1/0);var l=t.slice(1),u=[];for(let e=0;ee[0])))];let p=0;for(let e of c){let t=u.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),i=[];for(let r of t){let t=r[0],s=r[1],o=r[2],l=u[o][2],c=u[o][3];for(let r=0;rp&&(p=t)}}return!!(r&&p>0)&&p}function sequence_from_discrete_infinite(e,t){var n=e.tree.slice(1);if(n.length>1)return;let r=n[0][1],a=n[0][2],i=evaluate_numbers(n[0][3]),s=n[0][4];if(!Number.isInteger(i)||s!==1/0)return;let o=[];for(let e=0;e0))throw Error(`Have not implemented equality check with ${r} sign errors.`);if(r>1){let e=n;n=function(t,n){return equalSpecifiedSignErrors(t,n,{equalityFunction:e,n_sign_errors:r-1})}}var a,i,s=e.tree,o=[[s]],l=0;e.tree=["-",s];var u=n(e,t);if(e.tree=s,u)return!0;for(;a=o[l++];)if(a=a[0],Array.isArray(a))for(i=1;i"];function isAnalytic(e,{allow_abs:t=!1,allow_arg:n=!1,allow_relation:r=!1}={}){var a=normalize_applied_functions(normalize_function_names(e)),i=operators$3(a=subscripts_to_strings(a));for(let e=0;e+")},"-":function(e){return"-"+e.join("-")+""},"*":function(e){return e.join('\\cdot*')},"/":function(e){return astToGuppy$1.dfrac(e[0],e[1])},"^":function(e){return astToGuppy$1.power(e[0],e[1])},sin:function(e){return astToGuppy$1.trig("sin",e[0])},cos:function(e){return astToGuppy$1.trig("cos",e[0])},tan:function(e){return astToGuppy$1.trig("tan",e[0])},arcsin:function(e){return astToGuppy$1.trig("arcsin",e[0])},arccos:function(e){return astToGuppy$1.trig("arccos",e[0])},arctan:function(e){return astToGuppy$1.trig("arctan",e[0])},arccsc:function(e){return astToGuppy$1.trig("arccsc",e[0])},arcsec:function(e){return astToGuppy$1.trig("arcsec",e[0])},arccot:function(e){return astToGuppy$1.trig("arccot",e[0])},csc:function(e){return astToGuppy$1.trig("csc",e[0])},sec:function(e){return astToGuppy$1.trig("sec",e[0])},cot:function(e){return astToGuppy$1.trig("cot",e[0])},log:function(e){return astToGuppy$1.trig("log",e[0])},exp:function(e){return astToGuppy$1.trig("exp",e[0])},ln:function(e){return astToGuppy$1.trig("ln",e[0])},sqrt:function(e){return astToGuppy$1.sqrt(e[0])},abs:function(e){return astToGuppy$1.abs(e[0])}}}static dfrac(e,t){return'\\dfrac{}{}\\frac{}{}()/()'+e+''+t+""}static trig(e,t){return'\\'+e+'\\left(\\right) '+e+'()'+t+""}static sqrt(e){return'\\sqrt{}sqrt()'+e+""}static power(e,t){return'{}^{}()^()'+e+''+t+""}static abs(e){return'\\left|\\right|abs()'+e+""}static paren(e){return'\\left(\\right)()'+e+""}static isFunctionSymbol(e){return-1!==["sin","cos","tan","csc","sec","cot","arcsin","arccos","arctan","arccsc","arcsec","arccot","log","ln","exp","sqrt","abs","this.factorial"].indexOf(e)}static isGreekLetterSymbol(e){return-1!==["pi","theta","theta","Theta","alpha","nu","beta","xi","Xi","gamma","Gamma","delta","Delta","pi","Pi","epsilon","epsilon","rho","rho","zeta","sigma","Sigma","eta","tau","upsilon","Upsilon","iota","phi","phi","Phi","kappa","chi","lambda","Lambda","psi","Psi","omega","Omega"].indexOf(e)}factorWithParenthesesIfNegated(e){var t=this.factor(e);return t.toString().match(/^-/)?astToGuppy$1.paren(t.toString()):t}factor(e){if("string"==typeof e)return astToGuppy$1.isGreekLetterSymbol(e)?'\\'+e+' $'+e+"":""+e+"";if("number"==typeof e)return""+e+"";if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);return"apply"===t&&(t=e[1],n=e.slice(2)),"abs"===t?this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this))):astToGuppy$1.isFunctionSymbol(t)?"this.factorial"!==t||1!==n[0].toString().length&&!n[0].toString().match(/^[0-9]*$/)?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.operators[t](n):"^"===t||"~"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):astToGuppy$1.paren(this.expression(e))}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"*"===t?this.operators[t](n.map(function(e,t){var n=this.factorWithParenthesesIfNegated(e);return n.toString().match(/^[0-9]/)&&t>0?" * "+n:n}.bind(this))):"/"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.factor(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t||"-"===t?this.operators[t](n.map(function(e,t){return this.factorWithParenthesesIfNegated(e)}.bind(this))):this.term(e)}convert(e){return(""+this.expression(e)+"").replace(/<\/e>/g,"")}}const glslOperators={"+":function(e){var t=e[0];return e.slice(1).forEach((function(e){t=t+"+"+e})),t},"-":function(e){var t="-"+e[0];return e.slice(1).forEach((function(e){t=t+"-"+e})),t},"~":function(e){var t="vec2(0.0,0.0)";return e.forEach((function(e){t=t+"-"+e})),t},"*":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cmul("+t+","+e+")"})),t},"/":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cdiv("+t+","+e+")"})),t},sin:function(e){return"csin("+e[0]+")"},cos:function(e){return"ccos("+e[0]+")"},tan:function(e){return"ctan("+e[0]+")"},sinh:function(e){return"csinh("+e[0]+")"},cosh:function(e){return"ccosh("+e[0]+")"},arcsin:function(e){return"carcsin("+e[0]+")"},arccos:function(e){return"carccos("+e[0]+")"},arctan:function(e){return"carctan("+e[0]+")"},arccsc:function(e){return"carcsin(cdiv(vec2(1.0,0),"+e[0]+"))"},arcsec:function(e){return"carccos(cdiv(vec2(1.0,0),"+e[0]+"))"},arccot:function(e){return"carctan(cdiv(vec2(1.0,0),"+e[0]+"))"},csc:function(e){return"ccsc("+e[0]+")"},sec:function(e){return"csec("+e[0]+")"},cot:function(e){return"ccot("+e[0]+")"},exp:function(e){return"cexp("+e[0]+")"},conj:function(e){return"conjugate("+e[0]+")"},sqrt:function(e){return"cpower("+e[0]+",vec2(0.5,0.0))"},log:function(e){return"clog("+e[0]+")"},ln:function(e){return"clog("+e[0]+")"},"^":function(e){return"cpower("+e[0]+","+e[1]+")"},abs:function(e){return"cabs("+e[0]+")"},apply:function(e){return"vec2(NaN,NaN)"}};class astToGLSL$1{constructor(){}convert(e){if("boolean"==typeof e)throw Error("no support for boolean");if("string"==typeof e)return"e"===e?"vec2(2.71828182845905,0.0)":"pi"===e?"vec2(3.14159265358979,0.0)":"i"===e?"vec2(0.0,1.0)":String(e);if("number"==typeof e)return"vec2("+String(e)+",0.0)";if("real"in e&&"imaginary"in e)return e;if(!Array.isArray(e))throw Error("Invalid ast");var t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to GLSL");return t=n[0],n=n.slice(1),glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)))}if(t in glslOperators)return glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var astToGuppy=new astToGuppy$1,astToGLSL=new astToGLSL$1;const tex=function(e,t){return new astToLatex$1(t).convert(e.tree)},toLatex=tex,toString=function(e,t){return new astToText$2(t).convert(e.tree)},toGLSL=function(e){return astToGLSL.convert(e.tree)},toXML=function(e){return astToGuppy.convert(e.tree)};var printing=Object.freeze({__proto__:null,tex:tex,toLatex:toLatex,toString:toString,toXML:toXML,toGLSL:toGLSL});const integrateNumerically=function(e,t,n,r){for(var a=0,i={},s=0;s<100;s++){var o=n+(r-n)*(s+.5)/100;i[t]=o,a+=e.evaluate(i)}return a*(r-n)/100};var integration=Object.freeze({__proto__:null,integrateNumerically:integrateNumerically});function expression_to_polynomial(e){var t=get_tree(e);if("string"==typeof t)return"pi"===t&&math$1.define_pi||"i"===t&&math$1.define_i||"e"===t&&math$1.define_e?t:["polynomial",t,[[1,1]]];if("number"==typeof t)return t;let n=evaluate_to_constant(t,!1);if(null!==n&&Number.isFinite(n))return simplify(t);if(!Array.isArray(t))return!1;if(!operators$3(t).every((e=>["+","-","*","^","/","_","prime"].includes(e))))return!1;var r=t[0],a=t.slice(1);if("+"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_add(e,t)))}if("-"===r){let e=expression_to_polynomial(a[0]);return!!e&&polynomial_neg(e)}if("*"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_mul(e,t)))}if("^"===r){let e=a[0],n=expression_to_polynomial(e);if(!1===n)return!1;let r=simplify(a[1]);if("number"!=typeof r||r<0||!Number.isInteger(r)){let n=evaluate_to_constant(r,!1);if(null!==n||Number.isFinite(n)){let t=math$1.fraction(n);if(t.d<=100){e=t.s<0?["^",e,["/",-1,t.d]]:["^",e,["/",1,t.d]];var i=["polynomial",simplify(e),[]];return i[2].push([t.n,1]),i}}return["polynomial",t,[[1,1]]]}return 0===r?1:1===r?n:polynomial_pow(n,r)}if("/"===r){var s=a[1],o=evaluate_to_constant(s,!1);return null!==o&&Number.isFinite(o)?polynomial_mul(expression_to_polynomial(a[0]),["/",1,o]):["polynomial",t,[[1,1]]]}return["polynomial",t,[[1,1]]]}function polynomials_in_same_leading_variable(e,t){return e[1]!==t[1]&&(compare_function(e[1],t[1])<0?t=["polynomial",e[1],[[0,t]]]:e=["polynomial",t[1],[[0,e]]]),[e,t]}function polynomial_add(e,t){if("polynomial"!==e[0]){if("polynomial"!==t[0])return simplify(["+",e,t]);e=["polynomial",t[1],[[0,e]]]}else if("polynomial"!==t[0])t=["polynomial",e[1],[[0,t]]];else{let n=polynomials_in_same_leading_variable(e,t);e=n[0],t=n[1]}let n=["polynomial",e[1],[]],r=e[2],a=t[2],i=n[2],s=r.length,o=a.length,l=0,u=0;for(;l0;)1&t&&(n=polynomial_mul(n,e)),e=polynomial_mul(e,e),t>>=1;return n}function polynomial_to_expression(e){if(!Array.isArray(e)||"polynomial"!==e[0])return e;let t=e[1],n=e[2],r=[],a=n.length;for(var i=0;ir[o][1])return!1}return a!==i&&s!==i}function mono_gcd(e,t){if(!Array.isArray(e)||!Array.isArray(t)||"monomial"!==e[0]||"monomial"!==t[0])return 1;let n=e[2],r=t[2],a=[],i=n.length,s=r.length,o=0,l=0;for(;o1&&(t[n]=(t[n]||0)+1):t[e]=(t[e]||0)+1,t}var s=function(e,t){var a,i=0,s=1,o=1,u=0,c=0,p=0,d=1,m=1,h=0,f=1,y=1,g=1,b=1e7;if(null==e);else if(void 0!==t){if(o=(i=e)*(s=t),i%1!=0||s%1!=0)throw l.NonIntegerParameter}else switch(typeof e){case"object":if("d"in e&&"n"in e)i=e.n,s=e.d,"s"in e&&(i*=e.s);else{if(!(0 in e))throw l.InvalidParameter;i=e[0],1 in e&&(s=e[1])}o=i*s;break;case"number":if(e<0&&(o=e,e=-e),e%1==0)i=e;else if(e>0){for(e>=1&&(e/=m=Math.pow(10,Math.floor(1+Math.log(e)/Math.LN10)));f<=b&&g<=b;){if(e===(a=(h+y)/(f+g))){f+g<=b?(i=h+y,s=f+g):g>f?(i=y,s=g):(i=h,s=f);break}e>a?(h+=y,f+=g):(y+=h,g+=f),f>b?(i=y,s=g):(i=h,s=f)}i*=m}else(isNaN(e)||isNaN(t))&&(s=i=NaN);break;case"string":if(null===(f=e.match(/\d+|./g)))throw l.InvalidParameter;if("-"===f[h]?(o=-1,h++):"+"===f[h]&&h++,f.length===h+1?c=r(f[h++],o):"."===f[h+1]||"."===f[h]?("."!==f[h]&&(u=r(f[h++],o)),(1+ ++h===f.length||"("===f[h+1]&&")"===f[h+3]||"'"===f[h+1]&&"'"===f[h+3])&&(c=r(f[h],o),d=Math.pow(10,f[h].length),h++),("("===f[h]&&")"===f[h+2]||"'"===f[h]&&"'"===f[h+2])&&(p=r(f[h+1],o),m=Math.pow(10,f[h+1].length)-1,h+=3)):"/"===f[h+1]||":"===f[h+1]?(c=r(f[h],o),d=r(f[h+2],1),h+=3):"/"===f[h+3]&&" "===f[h+1]&&(u=r(f[h],o),c=r(f[h+2],o),d=r(f[h+4],1),h+=5),f.length<=h){o=i=p+(s=d*m)*u+m*c;break}default:throw l.InvalidParameter}if(0===s)throw l.DivisionByZero;n.s=o<0?-1:1,n.n=Math.abs(i),n.d=Math.abs(s)};function o(e,t){if(!e)return t;if(!t)return e;for(;;){if(!(e%=t))return t;if(!(t%=e))return e}}function l(e,t){if(s(e,t),!(this instanceof l))return a(n.s*n.n,n.d);e=o(n.d,n.n),this.s=n.s,this.n=n.n/e,this.d=n.d/e}l.DivisionByZero=new Error("Division by Zero"),l.InvalidParameter=new Error("Invalid argument"),l.NonIntegerParameter=new Error("Parameters must be integer"),l.prototype={s:1,n:0,d:1,abs:function(){return a(this.n,this.d)},neg:function(){return a(-this.s*this.n,this.d)},add:function(e,t){return s(e,t),a(this.s*this.n*n.d+n.s*this.d*n.n,this.d*n.d)},sub:function(e,t){return s(e,t),a(this.s*this.n*n.d-n.s*this.d*n.n,this.d*n.d)},mul:function(e,t){return s(e,t),a(this.s*n.s*this.n*n.n,this.d*n.d)},div:function(e,t){return s(e,t),a(this.s*n.s*this.n*n.d,this.d*n.n)},clone:function(){return a(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new l(NaN);if(void 0===e)return a(this.s*this.n%this.d,1);if(s(e,t),0===n.n&&0===this.d)throw l.DivisionByZero;return a(this.s*(n.d*this.n)%(n.n*this.d),n.d*this.d)},gcd:function(e,t){return s(e,t),a(o(n.n,this.n)*o(n.d,this.d),n.d*this.d)},lcm:function(e,t){return s(e,t),0===n.n&&0===this.n?a(0,1):a(n.n*this.n,o(n.n,this.n)*o(n.d,this.d))},ceil:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return a(this.s*this.d,this.n)},pow:function(e,t){if(s(e,t),1===n.d)return n.s<0?a(Math.pow(this.s*this.d,n.n),Math.pow(this.n,n.n)):a(Math.pow(this.s*this.n,n.n),Math.pow(this.d,n.n));if(this.s<0)return null;var r=i(this.n),o=i(this.d),l=1,u=1;for(var c in r)if("1"!==c){if("0"===c){l=0;break}if(r[c]*=n.n,r[c]%n.d!=0)return null;r[c]/=n.d,l*=Math.pow(c,r[c])}for(var c in o)if("1"!==c){if(o[c]*=n.n,o[c]%n.d!=0)return null;o[c]/=n.d,u*=Math.pow(c,o[c])}return n.s<0?a(u,l):a(l,u)},equals:function(e,t){return s(e,t),this.s*this.n*n.d==n.s*n.n*this.d},compare:function(e,t){s(e,t);var r=this.s*this.n*n.d-n.s*n.n*this.d;return(0=0;s--)i=i.inverse().add(n[s]);if(i.sub(t).abs().valueOf()0&&(n+=t,n+=" ",r%=a),n+=r,n+="/",n+=a),n},toLatex:function(e){var t,n="",r=this.n,a=this.d;return this.s<0&&(n+="-"),1===a?n+=r:(e&&(t=Math.floor(r/a))>0&&(n+=t,r%=a),n+="\\frac{",n+=r,n+="}{",n+=a,n+="}"),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do{r.push(Math.floor(t/n)),e=t%n,t=n,n=e}while(1!==t);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return"NaN";e=e||15;var r=function(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(1===t)return 0;for(var n=10%t,r=1;1!==n;r++)if(n=10*n%t,r>2e3)return 0;return r}(0,n),a=function(e,t,n){for(var r=1,a=function(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)1&t&&(r=r*e%n);return r}(10,n,t),i=0;i<300;i++){if(r===a)return i;r=10*r%t,a=10*a%t}return 0}(0,n,r),i=this.s<0?"-":"";if(i+=t/n|0,t%=n,(t*=10)&&(i+="."),r){for(var s=a;s--;)i+=t/n|0,t%=n,t*=10;for(i+="(",s=r;s--;)i+=t/n|0,t%=n,t*=10;i+=")"}else for(s=e;t&&s--;)i+=t/n|0,t%=n,t*=10;return i}},Object.defineProperty(l,"__esModule",{value:!0}),l.default=l,l.Fraction=l,e.exports=l}()}(fraction$1);var Fraction$1=getDefaultExportFromCjs(fraction$1.exports),name$4z="Fraction",dependencies$4z=[],createFractionClass=factory(name$4z,dependencies$4z,(()=>(Fraction$1.prototype.type="Fraction",Fraction$1.prototype.isFraction=!0,Fraction$1.prototype.toJSON=function(){return{mathjs:"Fraction",n:this.s*this.n,d:this.d}},Fraction$1.fromJSON=function(e){return new Fraction$1(e)},Fraction$1)),{isClass:!0}),name$4y="Range",dependencies$4y=[],createRangeClass=factory(name$4y,dependencies$4y,(()=>{function e(t,n,r){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");var a=null!=t,i=null!=n,s=null!=r;if(a)if(isBigNumber(t))t=t.toNumber();else if("number"!=typeof t)throw new TypeError("Parameter start must be a number");if(i)if(isBigNumber(n))n=n.toNumber();else if("number"!=typeof n)throw new TypeError("Parameter end must be a number");if(s)if(isBigNumber(r))r=r.toNumber();else if("number"!=typeof r)throw new TypeError("Parameter step must be a number");this.start=a?parseFloat(t):0,this.end=i?parseFloat(n):0,this.step=s?parseFloat(r):1}return e.prototype.type="Range",e.prototype.isRange=!0,e.parse=function(t){if("string"!=typeof t)return null;var n=t.split(":").map((function(e){return parseFloat(e)}));if(n.some((function(e){return isNaN(e)})))return null;switch(n.length){case 2:return new e(n[0],n[1]);case 3:return new e(n[0],n[2],n[1]);default:return null}},e.prototype.clone=function(){return new e(this.start,this.end,this.step)},e.prototype.size=function(){var e=0,t=this.start,n=this.step,r=this.end-t;return sign$3(n)===sign$3(r)?e=Math.ceil(r/n):0===r&&(e=0),isNaN(e)&&(e=0),[e]},e.prototype.min=function(){var e=this.size()[0];return e>0?this.step>0?this.start:this.start+(e-1)*this.step:void 0},e.prototype.max=function(){var e=this.size()[0];return e>0?this.step>0?this.start+(e-1)*this.step:this.start:void 0},e.prototype.forEach=function(e){var t=this.start,n=this.step,r=this.end,a=0;if(n>0)for(;tr;)e(t,[a],this),t+=n,a++},e.prototype.map=function(e){var t=[];return this.forEach((function(n,r,a){t[r[0]]=e(n,r,a)})),t},e.prototype.toArray=function(){var e=[];return this.forEach((function(t,n){e[n[0]]=t})),e},e.prototype.valueOf=function(){return this.toArray()},e.prototype.format=function(e){var t=format$3(this.start,e);return 1!==this.step&&(t+=":"+format$3(this.step,e)),t+":"+format$3(this.end,e)},e.prototype.toString=function(){return this.format()},e.prototype.toJSON=function(){return{mathjs:"Range",start:this.start,end:this.end,step:this.step}},e.fromJSON=function(t){return new e(t.start,t.end,t.step)},e}),{isClass:!0}),name$4x="Matrix",dependencies$4x=[],createMatrixClass=factory(name$4x,dependencies$4x,(()=>{function e(){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator")}return e.prototype.type="Matrix",e.prototype.isMatrix=!0,e.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},e.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},e.prototype.create=function(e,t){throw new Error("Cannot invoke create on a Matrix interface")},e.prototype.subset=function(e,t,n){throw new Error("Cannot invoke subset on a Matrix interface")},e.prototype.get=function(e){throw new Error("Cannot invoke get on a Matrix interface")},e.prototype.set=function(e,t,n){throw new Error("Cannot invoke set on a Matrix interface")},e.prototype.resize=function(e,t){throw new Error("Cannot invoke resize on a Matrix interface")},e.prototype.reshape=function(e,t){throw new Error("Cannot invoke reshape on a Matrix interface")},e.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},e.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},e.prototype.map=function(e,t){throw new Error("Cannot invoke map on a Matrix interface")},e.prototype.forEach=function(e){throw new Error("Cannot invoke forEach on a Matrix interface")},e.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},e.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},e.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},e.prototype.format=function(e){throw new Error("Cannot invoke format on a Matrix interface")},e.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},e}),{isClass:!0}),name$4w="DenseMatrix",dependencies$4w=["Matrix"],createDenseMatrixClass=factory(name$4w,dependencies$4w,(e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))"DenseMatrix"===e.type?(this._data=clone$3(e._data),this._size=clone$3(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,validate(this._data,this._size),this._datatype=t||e.datatype;else if(isArray$1(e))this._data=o(e),this._size=arraySize(this._data),validate(this._data,this._size),this._datatype=t;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t}}function r(e,t,n,a){var i=a===n-1,s=t.dimension(a);return i?s.map((function(t){return validateIndex(t,e.length),e[t]})).valueOf():s.map((function(i){return validateIndex(i,e.length),r(e[i],t,n,a+1)})).valueOf()}function a(e,t,n,r,i){var s=i===r-1,o=t.dimension(i);s?o.forEach((function(t,r){validateIndex(t),e[t]=n[r[0]]})):o.forEach((function(s,o){validateIndex(s),a(e[s],t,n[o[0]],r,i+1)}))}function i(e,t,n){if(0===t.length){for(var r=e._data;isArray$1(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize$1(e._data,e._size,n),e}function s(e,t,n){for(var r=e._size.slice(0),a=!1;r.lengthr[s]&&(r[s]=t[s],a=!0);a&&i(e,r,n)}function o(e){for(var t=0,n=e.length;t");var p=t.max().map((function(e){return e+1}));s(e,p,r);var d=o.length;a(e._data,t,n,d,0)}return e}(this,e,t,i);default:throw new SyntaxError("Wrong number of arguments")}},n.prototype.get=function(e){if(!isArray$1(e))throw new TypeError("Array expected");if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;tArray.isArray(e)&&1===e.length?e[0]:e));return i(n?this.clone():this,r,t)},n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=reshape$1(n._data,e);var r=n._size.reduce(((e,t)=>e*t));return n._size=processSizesWildcard(e,r),n},n.prototype.clone=function(){return new n({data:clone$3(this._data),size:clone$3(this._size),datatype:this._datatype})},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=function n(r,a){return isArray$1(r)?r.map((function(e,t){return n(e,a.concat(t))})):e(r,a,t)}(this._data,[]);return new n(r,void 0!==this._datatype?getArrayDataType(r,typeOf$1):void 0)},n.prototype.forEach=function(e){var t=this;!function n(r,a){isArray$1(r)?r.forEach((function(e,t){n(e,a.concat(t))})):e(r,a,t)}(this._data,[])},n.prototype[Symbol.iterator]=function*(){yield*function*e(t,n){if(isArray$1(t))for(var r=0;r[e[r]]));t.push(new n(i,e._datatype))},s=0;s0?e:0,r=e<0?-e:0,a=this._size[0],i=this._size[1],s=Math.min(a-r,i-t),o=[],l=0;l0?r:0,o=r<0?-r:0,l=e[0],u=e[1],c=Math.min(l-o,u-s);if(isArray$1(t)){if(t.length!==c)throw new Error("Invalid value array length");i=function(e){return t[e]}}else if(isMatrix(t)){var p=t.size();if(1!==p.length||p[0]!==c)throw new Error("Invalid matrix length");i=function(e){return t.get([e])}}else i=function(){return t};a||(a=isBigNumber(i(0))?i(0).mul(0):0);var d=[];if(e.length>0){d=resize$1(d,e,a);for(var m=0;m{var{typed:t}=e;return t(name$4v,{any:clone$3})}));function _switch$1(e){var t,n,r=e.length,a=e[0].length,i=[];for(n=0;n=r.length)throw new IndexError(t,r.length);return isMatrix(e)?e.create(_reduce(e.valueOf(),t,n)):_reduce(e,t,n)}function _reduce(e,t,n){var r,a,i,s;if(t<=0){if(Array.isArray(e[0])){for(s=_switch$1(e),a=[],r=0;r{var{typed:t}=e;return t(name$4u,{number:isInteger$1,BigNumber:function(e){return e.isInt()},Fraction:function(e){return 1===e.d&&isFinite(e.n)},"Array | Matrix":function(e){return deepMap(e,this)}})})),n1$4="number",n2$2="number, number";function absNumber(e){return Math.abs(e)}function addNumber(e,t){return e+t}function multiplyNumber(e,t){return e*t}function unaryMinusNumber(e){return-e}function unaryPlusNumber(e){return e}function cbrtNumber(e){return cbrt$2(e)}function cubeNumber(e){return e*e*e}function expNumber(e){return Math.exp(e)}function expm1Number(e){return expm1$1(e)}function gcdNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function gcd must be integer numbers");for(var n;0!==t;)n=e%t,e=t,t=n;return e<0?-e:e}function lcmNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function lcm must be integer numbers");if(0===e||0===t)return 0;for(var n,r=e*t;0!==t;)t=e%(n=t),e=n;return Math.abs(r/e)}function logNumber(e,t){return t?Math.log(e)/Math.log(t):Math.log(e)}function log10Number(e){return log10$3(e)}function log2Number(e){return log2$2(e)}function modNumber(e,t){if(t>0)return e-t*Math.floor(e/t);if(0===t)return e;throw new Error("Cannot calculate mod for a negative divisor")}function nthRootNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2,n=t<0;if(n&&(t=-t),0===t)throw new Error("Root must be non-zero");if(e<0&&Math.abs(t)%2!=1)throw new Error("Root must be odd when a is negative.");if(0===e)return n?1/0:0;if(!isFinite(e))return n?0:e;var r=Math.pow(Math.abs(e),1/t);return r=e<0?-r:r,n?1/r:r}function signNumber(e){return sign$3(e)}function squareNumber(e){return e*e}function xgcdNumber(e,t){var n,r,a,i=0,s=1,o=1,l=0;if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function xgcd must be integer numbers");for(;t;)a=e-(r=Math.floor(e/t))*t,n=i,i=s-r*i,s=n,n=o,o=l-r*o,l=n,e=t,t=a;return e<0?[-e,-s,-l]:[e,e?s:0,l]}function powNumber(e,t){return e*e<1&&t===1/0||e*e>1&&t===-1/0?0:Math.pow(e,t)}function roundNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!isInteger$1(t)||t<0||t>15)throw new Error("Number of decimals in function round must be an integer from 0 to 15 inclusive");return parseFloat(toFixed$2(e,t))}absNumber.signature=n1$4,addNumber.signature=n2$2,multiplyNumber.signature=n2$2,unaryMinusNumber.signature=n1$4,unaryPlusNumber.signature=n1$4,cbrtNumber.signature=n1$4,cubeNumber.signature=n1$4,expNumber.signature=n1$4,expm1Number.signature=n1$4,gcdNumber.signature=n2$2,lcmNumber.signature=n2$2,log10Number.signature=n1$4,log2Number.signature=n1$4,modNumber.signature=n2$2,signNumber.signature=n1$4,squareNumber.signature=n1$4,xgcdNumber.signature=n2$2,powNumber.signature=n2$2;var n1$3="number",n2$1="number, number";function bitAndNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitAnd");return e&t}function bitNotNumber(e){if(!isInteger$1(e))throw new Error("Integer expected in function bitNot");return~e}function bitOrNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitOr");return e|t}function bitXorNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitXor");return e^t}function leftShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function leftShift");return e<>t}function rightLogShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function rightLogShift");return e>>>t}function product(e,t){if(t>1;return product(e,n)*product(n+1,t)}function combinationsNumber(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinations");if(t>e)throw new TypeError("k must be less than or equal to n");for(var n=e-t,r=1,a=2,i=t171?1/0:product(1,e-1);if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*gammaNumber(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,r=n*e,a=r*e,i=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*n)-139/(51840*r)-571/(2488320*a)+163879/(209018880*i)+5246819/(75246796800*i*e))}--e,t=gammaP[0];for(var s=1;s=1;r--)n+=lgammaSeries[r]/(e+r);return lnSqrt2PI+(e+.5)*Math.log(t)-t+Math.log(n)}lgammaNumber.signature="number";var n1$1="number";function acoshNumber(e){return acosh$3(e)}function acotNumber(e){return Math.atan(1/e)}function acothNumber(e){return isFinite(e)?(Math.log((e+1)/e)+Math.log(e/(e-1)))/2:0}function acscNumber(e){return Math.asin(1/e)}function acschNumber(e){var t=1/e;return Math.log(t+Math.sqrt(t*t+1))}function asecNumber(e){return Math.acos(1/e)}function asechNumber(e){var t=1/e,n=Math.sqrt(t*t-1);return Math.log(n+t)}function asinhNumber(e){return asinh$3(e)}function atanhNumber(e){return atanh$3(e)}function cotNumber(e){return 1/Math.tan(e)}function cothNumber(e){var t=Math.exp(2*e);return(t+1)/(t-1)}function cscNumber(e){return 1/Math.sin(e)}function cschNumber(e){return 0===e?Number.POSITIVE_INFINITY:Math.abs(2/(Math.exp(e)-Math.exp(-e)))*sign$3(e)}function secNumber(e){return 1/Math.cos(e)}function sechNumber(e){return 2/(Math.exp(e)+Math.exp(-e))}function sinhNumber(e){return sinh$3(e)}acoshNumber.signature=n1$1,acotNumber.signature=n1$1,acothNumber.signature=n1$1,acscNumber.signature=n1$1,acschNumber.signature=n1$1,asecNumber.signature=n1$1,asechNumber.signature=n1$1,asinhNumber.signature=n1$1,atanhNumber.signature=n1$1,cotNumber.signature=n1$1,cothNumber.signature=n1$1,cscNumber.signature=n1$1,cschNumber.signature=n1$1,secNumber.signature=n1$1,sechNumber.signature=n1$1,sinhNumber.signature=n1$1;var n1="number";function isNegativeNumber(e){return e<0}function isPositiveNumber(e){return e>0}function isZeroNumber(e){return 0===e}function isNaNNumber(e){return Number.isNaN(e)}isNegativeNumber.signature=n1,isPositiveNumber.signature=n1,isZeroNumber.signature=n1,isNaNNumber.signature=n1;var name$4t="isNegative",dependencies$4t=["typed"],createIsNegative=factory(name$4t,dependencies$4t,(e=>{var{typed:t}=e;return t(name$4t,{number:isNegativeNumber,BigNumber:function(e){return e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s<0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4s="isNumeric",dependencies$4s=["typed"],createIsNumeric=factory(name$4s,dependencies$4s,(e=>{var{typed:t}=e;return t(name$4s,{"number | BigNumber | Fraction | boolean":function(){return!0},"Complex | Unit | string | null | undefined | Node":function(){return!1},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4r="hasNumericValue",dependencies$4r=["typed","isNumeric"],createHasNumericValue=factory(name$4r,dependencies$4r,(e=>{var{typed:t,isNumeric:n}=e;return t(name$4r,{string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})})),name$4q="isPositive",dependencies$4q=["typed"],createIsPositive=factory(name$4q,dependencies$4q,(e=>{var{typed:t}=e;return t(name$4q,{number:isPositiveNumber,BigNumber:function(e){return!e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s>0&&e.n>0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4p="isZero",dependencies$4p=["typed"],createIsZero=factory(name$4p,dependencies$4p,(e=>{var{typed:t}=e;return t(name$4p,{number:isZeroNumber,BigNumber:function(e){return e.isZero()},Complex:function(e){return 0===e.re&&0===e.im},Fraction:function(e){return 1===e.d&&0===e.n},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4o="isNaN",dependencies$4o=["typed"],createIsNaN=factory(name$4o,dependencies$4o,(e=>{var{typed:t}=e;return t(name$4o,{number:isNaNNumber,BigNumber:function(e){return e.isNaN()},Fraction:function(e){return!1},Complex:function(e){return e.isNaN()},Unit:function(e){return Number.isNaN(e.value)},"Array | Matrix":function(e){return deepMap(e,Number.isNaN)}})})),name$4n="typeOf",dependencies$4n=["typed"],createTypeOf=factory(name$4n,dependencies$4n,(e=>{var{typed:t}=e;return t(name$4n,{any:typeOf$1})}));function nearlyEqual(e,t,n){if(null==n)return e.eq(t);if(e.eq(t))return!0;if(e.isNaN()||t.isNaN())return!1;if(e.isFinite()&&t.isFinite()){var r=e.minus(t).abs();if(r.isZero())return!0;var a=e.constructor.max(e.abs(),t.abs());return r.lte(a.times(n))}return!1}function complexEquals(e,t,n){return nearlyEqual$1(e.re,t.re,n)&&nearlyEqual$1(e.im,t.im,n)}var name$4m="equalScalar",dependencies$4m=["typed","config"],createEqualScalar=factory(name$4m,dependencies$4m,(e=>{var{typed:t,config:n}=e;return t(name$4m,{"boolean, boolean":function(e,t){return e===t},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.eq(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return e.equals(t)},"Complex, Complex":function(e,t){return complexEquals(e,t,n.epsilon)},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)}})}));factory(name$4m,["typed","config"],(e=>{var{typed:t,config:n}=e;return t(name$4m,{"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)}})}));var name$4l="SparseMatrix",dependencies$4l=["typed","equalScalar","Matrix"],createSparseMatrixClass=factory(name$4l,dependencies$4l,(e=>{var{typed:t,equalScalar:n,Matrix:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))!function(e,t,n){"SparseMatrix"===t.type?(e._values=t._values?clone$3(t._values):void 0,e._index=clone$3(t._index),e._ptr=clone$3(t._ptr),e._size=clone$3(t._size),e._datatype=n||t._datatype):i(e,t.valueOf(),n||t._datatype)}(this,e,t);else if(e&&isArray$1(e.index)&&isArray$1(e.ptr)&&isArray$1(e.size))this._values=e.values,this._index=e.index,this._ptr=e.ptr,this._size=e.size,this._datatype=t||e.datatype;else if(isArray$1(e))i(this,e,t);else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=t}}function i(e,r,a){e._values=[],e._index=[],e._ptr=[],e._datatype=a;var i=r.length,s=0,o=n,l=0;if(isString$1(a)&&(o=t.find(n,[a,a])||n,l=t.convert(0,a)),i>0){var u=0;do{e._ptr.push(e._index.length);for(var c=0;ch){for(c=h;cm){if(d){var f=0;for(c=0;cr-1&&(e._values.splice(p,1),e._index.splice(p,1),g++)}e._ptr[c]=e._values.length}return e._size[0]=r,e._size[1]=a,e}function u(e,t,n,r,a){var i,s,o=r[0],l=r[1],u=[];for(i=0;i");if(1===i.length)t.dimension(0).forEach((function(t,a){validateIndex(t),e.set([t,0],n[a[0]],r)}));else{var u=t.dimension(0),c=t.dimension(1);u.forEach((function(t,a){validateIndex(t),c.forEach((function(i,s){validateIndex(i),e.set([t,i],n[a[0]][s[0]],r)}))}))}}return e}(this,e,t,n);default:throw new SyntaxError("Wrong number of arguments")}},a.prototype.get=function(e){if(!isArray$1(e))throw new TypeError("Array expected");if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);if(!this._values)throw new Error("Cannot invoke get on a Pattern only matrix");var t=e[0],n=e[1];validateIndex(t,this._size[0]),validateIndex(n,this._size[1]);var r=s(t,this._ptr[n],this._ptr[n+1],this._index);return rc-1||u>p-1)&&(l(this,Math.max(i+1,c),Math.max(u+1,p),a),c=this._size[0],p=this._size[1]),validateIndex(i,c),validateIndex(u,p);var h=s(i,this._ptr[u],this._ptr[u+1],this._index);return hArray.isArray(e)&&1===e.length?e[0]:e));if(2!==r.length)throw new Error("Only two dimensions matrix are supported");return r.forEach((function(e){if(!isNumber$1(e)||!isInteger$1(e)||e<0)throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(r)+")")})),l(n?this.clone():this,r[0],r[1],t)},a.prototype.reshape=function(e,t){if(!isArray$1(e))throw new TypeError("Array expected");if(2!==e.length)throw new Error("Sparse matrices can only be reshaped in two dimensions");e.forEach((function(t){if(!isNumber$1(t)||!isInteger$1(t)||t<=-2||0===t)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+format$1(e)+")")}));var n=this._size[0]*this._size[1];if(n!==(e=processSizesWildcard(e,n))[0]*e[1])throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var r=t?this.clone():this;if(this._size[0]===e[0]&&this._size[1]===e[1])return r;for(var a=[],i=0;i=0&&N<=i&&f(e._values[v],N-0,y-0)}else{for(var T={},C=g;C "+(this._values?format$1(this._values[l],e):"X");return a},a.prototype.toString=function(){return format$1(this.toArray())},a.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},a.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger$1(e))throw new TypeError("The parameter k must be an integer number")}else e=0;var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],s=Math.min(r-n,i-t),o=[],l=[],u=[];u[0]=0;for(var c=t;c0?i:0,d=i<0?-i:0,m=e[0],h=e[1],f=Math.min(m-d,h-p);if(isArray$1(r)){if(r.length!==f)throw new Error("Invalid value array length");c=function(e){return r[e]}}else if(isMatrix(r)){var y=r.size();if(1!==y.length||y[0]!==f)throw new Error("Invalid matrix length");c=function(e){return r.get([e])}}else c=function(){return r};for(var g=[],b=[],v=[],N=0;N=0&&T=u||a[p]!==t)){var m=r?r[c]:void 0;a.splice(p,0,t),r&&r.splice(p,0,m),a.splice(p<=c?c+1:c,1),r&&r.splice(p<=c?c+1:c,1)}else if(p=u||a[c]!==e)){var h=r?r[p]:void 0;a.splice(c,0,e),r&&r.splice(c,0,h),a.splice(c<=p?p+1:p,1),r&&r.splice(c<=p?p+1:p,1)}}},a}),{isClass:!0}),name$4k="number",dependencies$4k=["typed"];function getNonDecimalNumberParts(e){var t=e.match(/(0[box])([0-9a-fA-F]*)\.([0-9a-fA-F]*)/);return t?{input:e,radix:{"0b":2,"0o":8,"0x":16}[t[1]],integerPart:t[2],fractionalPart:t[3]}:null}function makeNumberFromNonDecimalParts(e){for(var t=parseInt(e.integerPart,e.radix),n=0,r=0;r{var{typed:t}=e,n=t("number",{"":function(){return 0},number:function(e){return e},string:function(e){if("NaN"===e)return NaN;var t=getNonDecimalNumberParts(e);if(t)return makeNumberFromNonDecimalParts(t);var n=0,r=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);r&&(n=Number(r[2]),e=r[1]);var a=Number(e);if(isNaN(a))throw new SyntaxError('String "'+e+'" is no valid number');if(r){if(a>2**n-1)throw new SyntaxError('String "'.concat(e,'" is out of range'));a>=2**(n-1)&&(a-=2**n)}return a},BigNumber:function(e){return e.toNumber()},Fraction:function(e){return e.valueOf()},Unit:function(e){throw new Error("Second argument with valueless unit expected")},null:function(e){return 0},"Unit, string | Unit":function(e,t){return e.toNumber(t)},"Array | Matrix":function(e){return deepMap(e,this)}});return n.fromJSON=function(e){return parseFloat(e.value)},n})),name$4j="string",dependencies$4j=["typed"],createString=factory(name$4j,dependencies$4j,(e=>{var{typed:t}=e;return t(name$4j,{"":function(){return""},number:format$3,null:function(e){return"null"},boolean:function(e){return e+""},string:function(e){return e},"Array | Matrix":function(e){return deepMap(e,this)},any:function(e){return String(e)}})})),name$4i="boolean",dependencies$4i=["typed"],createBoolean=factory(name$4i,dependencies$4i,(e=>{var{typed:t}=e;return t(name$4i,{"":function(){return!1},boolean:function(e){return e},number:function(e){return!!e},null:function(e){return!1},BigNumber:function(e){return!e.isZero()},string:function(e){var t=e.toLowerCase();if("true"===t)return!0;if("false"===t)return!1;var n=Number(e);if(""!==e&&!isNaN(n))return!!n;throw new Error('Cannot convert "'+e+'" to a boolean')},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4h="bignumber",dependencies$4h=["typed","BigNumber"],createBignumber=factory(name$4h,dependencies$4h,(e=>{var{typed:t,BigNumber:n}=e;return t("bignumber",{"":function(){return new n(0)},number:function(e){return new n(e+"")},string:function(e){var t=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);if(t){var r=t[2],a=n(t[1]),i=new n(2).pow(Number(r));if(a.gt(i.sub(1)))throw new SyntaxError('String "'.concat(e,'" is out of range'));var s=new n(2).pow(Number(r)-1);return a.gte(s)?a.sub(i):a}return new n(e)},BigNumber:function(e){return e},Fraction:function(e){return new n(e.n).div(e.d).times(e.s)},null:function(e){return new n(0)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4g="complex",dependencies$4g=["typed","Complex"],createComplex=factory(name$4g,dependencies$4g,(e=>{var{typed:t,Complex:n}=e;return t("complex",{"":function(){return n.ZERO},number:function(e){return new n(e,0)},"number, number":function(e,t){return new n(e,t)},"BigNumber, BigNumber":function(e,t){return new n(e.toNumber(),t.toNumber())},Fraction:function(e){return new n(e.valueOf(),0)},Complex:function(e){return e.clone()},string:function(e){return n(e)},null:function(e){return n(0)},Object:function(e){if("re"in e&&"im"in e)return new n(e.re,e.im);if("r"in e&&"phi"in e||"abs"in e&&"arg"in e)return new n(e);throw new Error("Expected object with properties (re and im) or (r and phi) or (abs and arg)")},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4f="fraction",dependencies$4f=["typed","Fraction"],createFraction=factory(name$4f,dependencies$4f,(e=>{var{typed:t,Fraction:n}=e;return t("fraction",{number:function(e){if(!isFinite(e)||isNaN(e))throw new Error(e+" cannot be represented as a fraction");return new n(e)},string:function(e){return new n(e)},"number, number":function(e,t){return new n(e,t)},null:function(e){return new n(0)},BigNumber:function(e){return new n(e.toString())},Fraction:function(e){return e},Object:function(e){return new n(e)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4e="matrix",dependencies$4e=["typed","Matrix","DenseMatrix","SparseMatrix"],createMatrix=factory(name$4e,dependencies$4e,(e=>{var{typed:t,Matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$4e,{"":function(){return i([])},string:function(e){return i([],e)},"string, string":function(e,t){return i([],e,t)},Array:function(e){return i(e)},Matrix:function(e){return i(e,e.storage())},"Array | Matrix, string":i,"Array | Matrix, string, string":i});function i(e,t,n){if("dense"===t||"default"===t||void 0===t)return new r(e,n);if("sparse"===t)return new a(e,n);throw new TypeError("Unknown matrix type "+JSON.stringify(t)+".")}})),name$4d="matrixFromFunction",dependencies$4d=["typed","matrix","isZero"],createMatrixFromFunction=factory(name$4d,dependencies$4d,(e=>{var{typed:t,matrix:n,isZero:r}=e;return t(name$4d,{"Array | Matrix, function, string, string":function(e,t,n,r){return a(e,t,n,r)},"Array | Matrix, function, string":function(e,t,n){return a(e,t,n)},"Matrix, function":function(e,t){return a(e,t,"dense")},"Array, function":function(e,t){return a(e,t,"dense").toArray()},"Array | Matrix, string, function":function(e,t,n){return a(e,n,t)},"Array | Matrix, string, string, function":function(e,t,n,r){return a(e,r,t,n)}});function a(e,t,a,i){var s;return(s=void 0!==i?n(a,i):n(a)).resize(e),s.forEach((function(e,n){var a=t(n);r(a)||s.set(n,a)})),s}})),name$4c="matrixFromRows",dependencies$4c=["typed","matrix","flatten","size"],createMatrixFromRows=factory(name$4c,dependencies$4c,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4c,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one row is needed to construct a matrix.");var t=s(e[0]),n=[];for(var a of e){var i=s(a);if(i!==t)throw new TypeError("The vectors had different length: "+(0|t)+" ≠ "+(0|i));n.push(r(a))}return n}function s(e){var t=a(e);if(1===t.length)return t[0];if(2===t.length){if(1===t[0])return t[1];if(1===t[1])return t[0];throw new TypeError("At least one of the arguments is not a vector.")}throw new TypeError("Only one- or two-dimensional vectors are supported.")}})),name$4b="matrixFromColumns",dependencies$4b=["typed","matrix","flatten","size"],createMatrixFromColumns=factory(name$4b,dependencies$4b,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4b,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one column is needed to construct a matrix.");for(var t=s(e[0]),n=[],a=0;a{var{typed:t}=e;return t(name$4a,{"Unit, Array":function(e,t){return e.splitUnit(t)}})})),name$49="unaryMinus",dependencies$49=["typed"],createUnaryMinus=factory(name$49,dependencies$49,(e=>{var{typed:t}=e;return t(name$49,{number:unaryMinusNumber,Complex:function(e){return e.neg()},BigNumber:function(e){return e.neg()},Fraction:function(e){return e.neg()},Unit:function(e){var t=e.clone();return t.value=this(e.value),t},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$48="unaryPlus",dependencies$48=["typed","config","BigNumber"],createUnaryPlus=factory(name$48,dependencies$48,(e=>{var{typed:t,config:n,BigNumber:r}=e;return t(name$48,{number:unaryPlusNumber,Complex:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Unit:function(e){return e.clone()},"Array | Matrix":function(e){return deepMap(e,this)},"boolean | string":function(e){return"BigNumber"===n.number?new r(+e):+e}})})),name$47="abs",dependencies$47=["typed"],createAbs=factory(name$47,dependencies$47,(e=>{var{typed:t}=e;return t(name$47,{number:absNumber,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},Fraction:function(e){return e.abs()},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.abs()}})})),name$46="apply",dependencies$46=["typed","isInteger"],createApply=factory(name$46,dependencies$46,(e=>{var{typed:t,isInteger:n}=e;return t(name$46,{"Array | Matrix, number | BigNumber, function":function(e,t,r){if(!n(t))throw new TypeError("Integer number expected for dimension");var a=Array.isArray(e)?arraySize(e):e.size();if(t<0||t>=a.length)throw new IndexError(t,a.length);return isMatrix(e)?e.create(_apply(e.valueOf(),t,r)):_apply(e,t,r)}})}));function _apply(e,t,n){var r,a,i;if(t<=0){if(Array.isArray(e[0])){for(i=_switch(e),a=[],r=0;r{var{typed:t}=e;return t(name$45,{"number, number":addNumber,"Complex, Complex":function(e,t){return e.add(t)},"BigNumber, BigNumber":function(e,t){return e.plus(t)},"Fraction, Fraction":function(e,t){return e.add(t)},"Unit, Unit":function(e,t){if(null===e.value||void 0===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value||void 0===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n}})})),name$44="cbrt",dependencies$44=["config","typed","isNegative","unaryMinus","matrix","Complex","BigNumber","Fraction"],createCbrt=factory(name$44,dependencies$44,(e=>{var{config:t,typed:n,isNegative:r,unaryMinus:a,matrix:i,Complex:s,BigNumber:o,Fraction:l}=e;return n(name$44,{number:cbrtNumber,Complex:u,"Complex, boolean":u,BigNumber:function(e){return e.cbrt()},Unit:function(e){if(e.value&&isComplex(e.value)){var t=e.clone();return t.value=1,(t=t.pow(1/3)).value=u(e.value),t}var n,i=r(e.value);i&&(e.value=a(e.value)),n=isBigNumber(e.value)?new o(1).div(3):isFraction(e.value)?new l(1,3):1/3;var s=e.pow(n);return i&&(s.value=a(s.value)),s},"Array | Matrix":function(e){return deepMap(e,this)}});function u(e,n){var r=e.arg()/3,a=e.abs(),o=new s(cbrtNumber(a),0).mul(new s(0,r).exp());if(n){var l=[o,new s(cbrtNumber(a),0).mul(new s(0,r+2*Math.PI/3).exp()),new s(cbrtNumber(a),0).mul(new s(0,r-2*Math.PI/3).exp())];return"Array"===t.matrix?l:i(l)}return o}})),name$43="algorithm11",dependencies$43=["typed","equalScalar"],createAlgorithm11=factory(name$43,dependencies$43,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=n,f=0,y=a;"string"==typeof c&&(p=c,h=t.find(n,[p,p]),f=t.convert(0,p),r=t.convert(r,p),y=t.find(a,[p,p]));for(var g=[],b=[],v=[],N=0;N{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=a;"string"==typeof c&&(p=c,r=t.convert(r,p),h=t.find(a,[p,p]));for(var f=[],y=[],g=[],b=0;b{var{typed:t}=e;return function(e,r,a,i){var s,o=e._data,l=e._size,u=e._datatype,c=a;"string"==typeof u&&(s=u,r=t.convert(r,s),c=t.find(a,[s,s]));var p=l.length>0?n(c,0,l,l[0],o,r,i):[];return e.createDenseMatrix({data:p,size:clone$3(l),datatype:s})};function n(e,t,r,a,i,s,o){var l=[];if(t===r.length-1)for(var u=0;u{var{typed:t,config:n,round:r}=e;return t(name$40,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.ceil(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),s=Math.ceil(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(s,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createCeil=factory(name$40,dependencies$40,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:s,DenseMatrix:o}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:o}),c=createAlgorithm14({typed:t}),p=createCeilNumber({typed:t,config:n,round:r});return t("ceil",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.ceil()},"Complex, number":function(e,t){return e.ceil(t)},"Complex, BigNumber":function(e,t){return e.ceil(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.ceil()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_CEIL)},Fraction:function(e){return e.ceil()},"Fraction, number":function(e,t){return e.ceil(t)},"Fraction, BigNumber":function(e,t){return e.ceil(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?s(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3$="cube",dependencies$3$=["typed"],createCube=factory(name$3$,dependencies$3$,(e=>{var{typed:t}=e;return t(name$3$,{number:cubeNumber,Complex:function(e){return e.mul(e).mul(e)},BigNumber:function(e){return e.times(e).times(e)},Fraction:function(e){return e.pow(3)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(3)}})})),name$3_="exp",dependencies$3_=["typed"],createExp=factory(name$3_,dependencies$3_,(e=>{var{typed:t}=e;return t(name$3_,{number:expNumber,Complex:function(e){return e.exp()},BigNumber:function(e){return e.exp()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Z="expm1",dependencies$3Z=["typed","Complex"],createExpm1=factory(name$3Z,dependencies$3Z,(e=>{var{typed:t,Complex:n}=e;return t(name$3Z,{number:expm1Number,Complex:function(e){var t=Math.exp(e.re);return new n(t*Math.cos(e.im)-1,t*Math.sin(e.im))},BigNumber:function(e){return e.exp().minus(1)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Y="fix",dependencies$3Y=["typed","Complex","matrix","ceil","floor","equalScalar","zeros","DenseMatrix"],createFixNumber=factory(name$3Y,["typed","ceil","floor"],(e=>{var{typed:t,ceil:n,floor:r}=e;return t(name$3Y,{number:function(e){return e>0?r(e):n(e)},"number, number":function(e,t){return e>0?r(e,t):n(e,t)}})})),createFix=factory(name$3Y,dependencies$3Y,(e=>{var{typed:t,Complex:n,matrix:r,ceil:a,floor:i,equalScalar:s,zeros:o,DenseMatrix:l}=e,u=createAlgorithm12({typed:t,DenseMatrix:l}),c=createAlgorithm14({typed:t}),p=createFixNumber({typed:t,ceil:a,floor:i});return t("fix",{number:p.signatures.number,"number, number | BigNumber":p.signatures["number,number"],Complex:function(e){return new n(e.re>0?Math.floor(e.re):Math.ceil(e.re),e.im>0?Math.floor(e.im):Math.ceil(e.im))},"Complex, number":function(e,t){return new n(e.re>0?i(e.re,t):a(e.re,t),e.im>0?i(e.im,t):a(e.im,t))},"Complex, BigNumber":function(e,t){var r=t.toNumber();return new n(e.re>0?i(e.re,r):a(e.re,r),e.im>0?i(e.im,r):a(e.im,r))},BigNumber:function(e){return e.isNegative()?a(e):i(e)},"BigNumber, number | BigNumber":function(e,t){return e.isNegative()?a(e,t):i(e,t)},Fraction:function(e){return e.s<0?e.ceil():e.floor()},"Fraction, number | BigNumber":function(e,t){return e.s<0?a(e,t):i(e,t)},"Array | Matrix":function(e){return deepMap(e,this)},"Array | Matrix, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(r(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return s(e,0)?o(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3X="floor",dependencies$3X=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix"],createFloorNumber=factory(name$3X,["typed","config","round"],(e=>{var{typed:t,config:n,round:r}=e;return t(name$3X,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.floor(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),s=Math.floor(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(s,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createFloor=factory(name$3X,dependencies$3X,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:s,DenseMatrix:o}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:o}),c=createAlgorithm14({typed:t}),p=createFloorNumber({typed:t,config:n,round:r});return t("floor",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.floor()},"Complex, number":function(e,t){return e.floor(t)},"Complex, BigNumber":function(e,t){return e.floor(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.floor()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_FLOOR)},Fraction:function(e){return e.floor()},"Fraction, number":function(e,t){return e.floor(t)},"Fraction, BigNumber":function(e,t){return e.floor(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?s(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3W="algorithm01",dependencies$3W=["typed"],createAlgorithm01=factory(name$3W,dependencies$3W,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,s=e._size,o=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(s.length!==p.length)throw new DimensionError(s.length,p.length);if(s[0]!==p[0]||s[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,h,f=s[0],y=s[1],g="string"==typeof o&&o===d?o:void 0,b=g?t.find(r,[g,g]):r,v=[];for(m=0;m{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x,S=i&&c?[]:void 0,w=[],E=[],D=i&&c?[]:void 0,O=i&&c?[]:void 0,I=[],R=[];for(C=0;C{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=a;"string"==typeof c&&(p=c,r=t.convert(r,p),h=t.find(a,[p,p]));for(var f=[],y=[],g=[],b=0;b{var{typed:t}=e;return function(e,r,a){var i,s=e._data,o=e._size,l=e._datatype,u=r._data,c=r._size,p=r._datatype,d=[];if(o.length!==c.length)throw new DimensionError(o.length,c.length);for(var m=0;m0?n(h,0,d,d[0],s,u):[];return e.createDenseMatrix({data:f,size:d,datatype:i})};function n(e,t,r,a,i,s){var o=[];if(t===r.length-1)for(var l=0;l{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm04({typed:t,equalScalar:r}),l=createAlgorithm10({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$3S,{"number, number":gcdNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function gcd must be integer numbers");for(var n=new a(0);!t.isZero();){var r=e.mod(t);e=t,t=r}return e.lt(n)?e.neg():e},"Fraction, Fraction":function(e,t){return e.gcd(t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return l(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return c(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return c(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var s=e._data,o=e._size,l=e._datatype,u=r._values,c=r._index,p=r._ptr,d=r._size,m=r._datatype;if(o.length!==d.length)throw new DimensionError(o.length,d.length);if(o[0]!==d[0]||o[1]!==d[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+d+")");if(!u)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var h,f=o[0],y=o[1],g=n,b=0,v=a;"string"==typeof l&&l===m&&(h=l,g=t.find(n,[h,h]),b=t.convert(0,h),v=t.find(a,[h,h]));for(var N=[],T=[],C=[],A=0;A{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._size,o=e._datatype,l=r._values,u=r._size,c=r._datatype;if(s.length!==u.length)throw new DimensionError(s.length,u.length);if(s[0]!==u[0]||s[1]!==u[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+u+")");var p,d=s[0],m=s[1],h=n,f=0,y=a;"string"==typeof o&&o===c&&(p=o,h=t.find(n,[p,p]),f=t.convert(0,p),y=t.find(a,[p,p]));for(var g=i&&l?[]:void 0,b=[],v=[],N=g?[]:void 0,T=[],C=[],A=0;A{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),s=createAlgorithm11({typed:t,equalScalar:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3P,{"number, number":lcmNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function lcm must be integer numbers");if(e.isZero())return e;if(t.isZero())return t;for(var n=e.times(t);!t.isZero();){var r=t;t=e.mod(r),e=r}return n.div(e).abs()},"Fraction, Fraction":function(e,t){return e.lcm(t)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return s(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return s(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return l(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return l(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,config:n,Complex:r}=e;return t(name$3O,{number:function(e){return e>=0||n.predictable?log10Number(e):new r(e,0).log().div(Math.LN10)},Complex:function(e){return new r(e).log().div(Math.LN10)},BigNumber:function(e){return!e.isNegative()||n.predictable?e.log():new r(e.toNumber(),0).log().div(Math.LN10)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3N="log2",dependencies$3N=["typed","config","Complex"],createLog2=factory(name$3N,dependencies$3N,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$3N,{number:function(e){return e>=0||n.predictable?log2Number(e):a(new r(e,0))},Complex:a,BigNumber:function(e){return!e.isNegative()||n.predictable?e.log(2):a(new r(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)}});function a(e){var t=Math.sqrt(e.re*e.re+e.im*e.im);return new r(Math.log2?Math.log2(t):Math.log(t)/Math.LN2,Math.atan2(e.im,e.re)/Math.LN2)}})),name$3M="algorithm03",dependencies$3M=["typed"],createAlgorithm03=factory(name$3M,dependencies$3M,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,s=e._size,o=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(s.length!==p.length)throw new DimensionError(s.length,p.length);if(s[0]!==p[0]||s[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,h=s[0],f=s[1],y=0,g=r;"string"==typeof o&&o===d&&(m=o,y=t.convert(0,m),g=t.find(r,[m,m]));for(var b=[],v=0;v{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x=i&&c?[]:void 0,S=[],w=[],E=x?[]:void 0,D=x?[]:void 0,O=[],I=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm03({typed:t}),o=createAlgorithm05({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm12({typed:t,DenseMatrix:a}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$3K,{"number, number":modNumber,"BigNumber, BigNumber":function(e,t){if(t.isNeg())throw new Error("Cannot calculate mod for a negative divisor");return t.isZero()?e:e.mod(t)},"Fraction, Fraction":function(e,t){if(t.compare(0)<0)throw new Error("Cannot calculate mod for a negative divisor");return e.compare(0)>=0?e.mod(t):e.mod(t).add(t).mod(t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,this,!0).valueOf()}})})),name$3J="multiplyScalar",dependencies$3J=["typed"],createMultiplyScalar=factory(name$3J,dependencies$3J,(e=>{var{typed:t}=e;return t("multiplyScalar",{"number, number":multiplyNumber,"Complex, Complex":function(e,t){return e.mul(t)},"BigNumber, BigNumber":function(e,t){return e.times(t)},"Fraction, Fraction":function(e,t){return e.mul(t)},"number | Fraction | BigNumber | Complex, Unit":function(e,t){var n=t.clone();return n.value=null===n.value?n._normalize(e):this(n.value,e),n},"Unit, number | Fraction | BigNumber | Complex":function(e,t){var n=e.clone();return n.value=null===n.value?n._normalize(t):this(n.value,t),n},"Unit, Unit":function(e,t){return e.multiply(t)}})})),name$3I="multiply",dependencies$3I=["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],createMultiply=factory(name$3I,dependencies$3I,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,equalScalar:i,dot:s}=e,o=createAlgorithm11({typed:t,equalScalar:i}),l=createAlgorithm14({typed:t});function u(e,t){switch(e.length){case 1:switch(t.length){case 1:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+e[0]+") must match Matrix rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;case 2:switch(t.length){case 1:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+e[1]+") must match Vector length ("+t[0]+")");break;case 2:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+e[1]+") must match Matrix B rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+e.length+" dimensions)")}}function c(e,n){if("dense"!==n.storage())throw new Error("Support for SparseMatrix not implemented");return function(e,n){var i,s=e._data,o=e._size,l=e._datatype,u=n._data,c=n._size,p=n._datatype,d=o[0],m=c[1],h=r,f=a;l&&p&&l===p&&"string"==typeof l&&(i=l,h=t.find(r,[i,i]),f=t.find(a,[i,i]));for(var y=[],g=0;gS)for(var E=0,D=0;D{var{typed:t,matrix:n,equalScalar:r,BigNumber:a}=e,i=createAlgorithm01({typed:t}),s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t}),p="Complex number not supported in function nthRoot. Use nthRoots instead.";return t(name$3H,{number:nthRootNumber,"number, number":nthRootNumber,BigNumber:function(e){return d(e,new a(2))},Complex:function(e){throw new Error(p)},"Complex, number":function(e,t){throw new Error(p)},"BigNumber, BigNumber":d,"Array | Matrix":function(e){return this(e,2)},"SparseMatrix, SparseMatrix":function(e,t){if(1===t.density())return o(e,t,this);throw new Error("Root must be non-zero")},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){if(1===t.density())return i(e,t,this,!1);throw new Error("Root must be non-zero")},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){if(1===t.density())return l(t,e,this,!0);throw new Error("Root must be non-zero")},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}});function d(e,t){var n=a.precision,r=a.clone({precision:n+2}),i=new a(0),s=new r(1),o=t.isNegative();if(o&&(t=t.neg()),t.isZero())throw new Error("Root must be non-zero");if(e.isNegative()&&!t.abs().mod(2).equals(1))throw new Error("Root must be odd when a is negative.");if(e.isZero())return o?new r(1/0):0;if(!e.isFinite())return o?i:e;var l=e.abs().pow(s.div(t));return l=e.isNeg()?l.neg():l,new a((o?s.div(l):l).toPrecision(n))}})),name$3G="sign",dependencies$3G=["typed","BigNumber","Fraction","complex"],createSign=factory(name$3G,dependencies$3G,(e=>{var{typed:t,BigNumber:n,complex:r,Fraction:a}=e;return t(name$3G,{number:signNumber,Complex:function(e){return 0===e.im?r(signNumber(e.re)):e.sign()},BigNumber:function(e){return new n(e.cmp(0))},Fraction:function(e){return new a(e.s,1)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){if(!e._isDerived()&&0!==e.units[0].unit.offset)throw new TypeError("sign is ambiguous for units with offset");return this(e.value)}})})),name$3F="sqrt",dependencies$3F=["config","typed","Complex"],createSqrt=factory(name$3F,dependencies$3F,(e=>{var{config:t,typed:n,Complex:r}=e;return n("sqrt",{number:a,Complex:function(e){return e.sqrt()},BigNumber:function(e){return!e.isNegative()||t.predictable?e.sqrt():a(e.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(.5)}});function a(e){return isNaN(e)?NaN:e>=0||t.predictable?Math.sqrt(e):new r(e,0).sqrt()}})),name$3E="square",dependencies$3E=["typed"],createSquare=factory(name$3E,dependencies$3E,(e=>{var{typed:t}=e;return t(name$3E,{number:squareNumber,Complex:function(e){return e.mul(e)},BigNumber:function(e){return e.times(e)},Fraction:function(e){return e.mul(e)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(2)}})})),name$3D="subtract",dependencies$3D=["typed","matrix","equalScalar","addScalar","unaryMinus","DenseMatrix"],createSubtract=factory(name$3D,dependencies$3D,(e=>{var{typed:t,matrix:n,equalScalar:r,addScalar:a,unaryMinus:i,DenseMatrix:s}=e,o=createAlgorithm01({typed:t}),l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm10({typed:t,DenseMatrix:s}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$3D,{"number, number":function(e,t){return e-t},"Complex, Complex":function(e,t){return e.sub(t)},"BigNumber, BigNumber":function(e,t){return e.minus(t)},"Fraction, Fraction":function(e,t){return e.sub(t)},"Unit, Unit":function(e,t){if(null===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n},"SparseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return c(e,i(t),a)},"DenseMatrix, any":function(e,t){return d(e,t,this)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})}));function checkEqualDimensions(e,t){var n=e.size(),r=t.size();if(n.length!==r.length)throw new DimensionError(n.length,r.length)}var name$3C="xgcd",dependencies$3C=["typed","config","matrix","BigNumber"],createXgcd=factory(name$3C,dependencies$3C,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$3C,{"number, number":function(e,t){var a=xgcdNumber(e,t);return"Array"===n.matrix?a:r(a)},"BigNumber, BigNumber":function(e,t){var i,s,o,l,u=new a(0),c=new a(1),p=u,d=c,m=c,h=u;if(!e.isInt()||!t.isInt())throw new Error("Parameters in function xgcd must be integer numbers");for(;!t.isZero();)s=e.div(t).floor(),o=e.mod(t),i=p,p=d.minus(s.times(p)),d=i,i=m,m=h.minus(s.times(m)),h=i,e=t,t=o;return l=e.lt(u)?[e.neg(),d.neg(),h.neg()]:[e,e.isZero()?0:d,h],"Array"===n.matrix?l:r(l)}})})),name$3B="invmod",dependencies$3B=["typed","config","BigNumber","xgcd","equal","smaller","mod","add","isInteger"],createInvmod=factory(name$3B,dependencies$3B,(e=>{var{typed:t,config:n,BigNumber:r,xgcd:a,equal:i,smaller:s,mod:o,add:l,isInteger:u}=e;return t(name$3B,{"number, number":c,"BigNumber, BigNumber":c});function c(e,t){if(!u(e)||!u(t))throw new Error("Parameters in function invmod must be integer numbers");if(e=o(e,t),i(t,0))throw new Error("Divisor must be non zero");var n=a(e,t);n=n.valueOf();var[c,p]=n;return i(c,r(1))?(p=o(p,t),s(p,r(0))&&(p=l(p,t)),p):NaN}})),name$3A="algorithm09",dependencies$3A=["typed","equalScalar"],createAlgorithm09=factory(name$3A,dependencies$3A,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x,S=i&&c?[]:void 0,w=[],E=[],D=S?[]:void 0,O=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,multiplyScalar:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm09({typed:t,equalScalar:r}),o=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3z,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,a,!1)},"DenseMatrix, any":function(e,t){return u(e,t,a,!1)},"any, SparseMatrix":function(e,t){return o(t,e,a,!0)},"any, DenseMatrix":function(e,t){return u(t,e,a,!0)},"Array, any":function(e,t){return u(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,a,!0).valueOf()}})}));function bitAndBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitAnd");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero()||t.eq(-1)||e.eq(t))return e;if(t.isZero()||e.eq(-1))return t;if(!e.isFinite()||!t.isFinite()){if(!e.isFinite()&&!t.isFinite())return e.isNegative()===t.isNegative()?e:new n(0);if(!e.isFinite())return t.isNegative()?e:e.isNegative()?new n(0):t;if(!t.isFinite())return e.isNegative()?t:t.isNegative()?new n(0):e}return bitwise(e,t,(function(e,t){return e&t}))}function bitNotBigNumber(e){if(e.isFinite()&&!e.isInteger())throw new Error("Integer expected in function bitNot");var t=e.constructor,n=t.precision;t.config({precision:1e9});var r=e.plus(new t(1));return r.s=-r.s||null,t.config({precision:n}),r}function bitOrBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitOr");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);var r=new n(-1);return e.isZero()||t.eq(r)||e.eq(t)?t:t.isZero()||e.eq(r)?e:e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e|t})):!e.isFinite()&&!e.isNegative()&&t.isNegative()||e.isNegative()&&!t.isNegative()&&!t.isFinite()?r:e.isNegative()&&t.isNegative()?e.isFinite()?e:t:e.isFinite()?t:e}function bitwise(e,t,n){var r,a,i,s,o,l=e.constructor,u=+(e.s<0),c=+(t.s<0);if(u){r=decCoefficientToBinaryString(bitNotBigNumber(e));for(var p=0;p0;)n(i[--m],s[--h])===f&&(y=y.plus(g)),g=g.times(b);for(;h>0;)n(o,s[--h])===f&&(y=y.plus(g)),g=g.times(b);return l.config({precision:v}),0===f&&(y.s=-y.s),y}function decCoefficientToBinaryString(e){for(var t=e.d,n=t[0]+"",r=1;r0)if(++o>u)for(o-=u;o--;)l+="0";else o1&&(null!==c[m+1]&&void 0!==c[m+1]||(c[m+1]=0),c[m+1]+=c[m]>>1,c[m]&=1)}return c.reverse()}function bitXor$1(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitXor");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero())return t;if(t.isZero())return e;if(e.eq(t))return new n(0);var r=new n(-1);return e.eq(r)?bitNotBigNumber(t):t.eq(r)?bitNotBigNumber(e):e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e^t})):e.isFinite()||t.isFinite()?new n(e.isNegative()===t.isNegative()?1/0:-1/0):r}function leftShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function leftShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:e.isFinite()||t.isFinite()?t.lt(55)?e.times(Math.pow(2,t.toNumber())+""):e.times(new n(2).pow(t)):new n(NaN)}function rightArithShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function rightArithShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:t.isFinite()?t.lt(55)?e.div(Math.pow(2,t.toNumber())+"").floor():e.div(new n(2).pow(t)).floor():e.isNegative()?new n(-1):e.isFinite()?new n(0):new n(NaN)}var name$3y="bitAnd",dependencies$3y=["typed","matrix","equalScalar"],createBitAnd=factory(name$3y,dependencies$3y,(e=>{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),s=createAlgorithm11({typed:t,equalScalar:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3y,{"number, number":bitAndNumber,"BigNumber, BigNumber":bitAndBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3x="bitNot",dependencies$3x=["typed"],createBitNot=factory(name$3x,dependencies$3x,(e=>{var{typed:t}=e;return t(name$3x,{number:bitNotNumber,BigNumber:bitNotBigNumber,"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3w="bitOr",dependencies$3w=["typed","matrix","equalScalar","DenseMatrix"],createBitOr=factory(name$3w,dependencies$3w,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm01({typed:t}),s=createAlgorithm04({typed:t,equalScalar:r}),o=createAlgorithm10({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3w,{"number, number":bitOrNumber,"BigNumber, BigNumber":bitOrBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3v="algorithm07",dependencies$3v=["typed","DenseMatrix"],createAlgorithm07=factory(name$3v,dependencies$3v,(e=>{var{typed:t,DenseMatrix:n}=e;return function(e,a,i){var s=e._size,o=e._datatype,l=a._size,u=a._datatype;if(s.length!==l.length)throw new DimensionError(s.length,l.length);if(s[0]!==l[0]||s[1]!==l[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+l+")");var c,p,d,m=s[0],h=s[1],f=0,y=i;"string"==typeof o&&o===u&&(c=o,f=t.convert(0,c),y=t.find(i,[c,c]));var g=[];for(p=0;p{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),s=createAlgorithm12({typed:t,DenseMatrix:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3u,{"number, number":bitXorNumber,"BigNumber, BigNumber":bitXor$1,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3t="arg",dependencies$3t=["typed"],createArg=factory(name$3t,dependencies$3t,(e=>{var{typed:t}=e;return t(name$3t,{number:function(e){return Math.atan2(0,e)},BigNumber:function(e){return e.constructor.atan2(0,e)},Complex:function(e){return e.arg()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3s="conj",dependencies$3s=["typed"],createConj=factory(name$3s,dependencies$3s,(e=>{var{typed:t}=e;return t(name$3s,{number:function(e){return e},BigNumber:function(e){return e},Complex:function(e){return e.conjugate()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3r="im",dependencies$3r=["typed"],createIm=factory(name$3r,dependencies$3r,(e=>{var{typed:t}=e;return t(name$3r,{number:function(e){return 0},BigNumber:function(e){return e.mul(0)},Fraction:function(e){return e.mul(0)},Complex:function(e){return e.im},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3q="re",dependencies$3q=["typed"],createRe=factory(name$3q,dependencies$3q,(e=>{var{typed:t}=e;return t(name$3q,{number:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Complex:function(e){return e.re},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3p="not",dependencies$3p=["typed"],createNot=factory(name$3p,dependencies$3p,(e=>{var{typed:t}=e;return t(name$3p,{number:notNumber,Complex:function(e){return 0===e.re&&0===e.im},BigNumber:function(e){return e.isZero()||e.isNaN()},Unit:function(e){return null===e.value||this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3o="or",dependencies$3o=["typed","matrix","equalScalar","DenseMatrix"],createOr=factory(name$3o,dependencies$3o,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm05({typed:t,equalScalar:r}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3o,{"number, number":orNumber,"Complex, Complex":function(e,t){return 0!==e.re||0!==e.im||0!==t.re||0!==t.im},"BigNumber, BigNumber":function(e,t){return!e.isZero()&&!e.isNaN()||!t.isZero()&&!t.isNaN()},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3n="xor",dependencies$3n=["typed","matrix","DenseMatrix"],createXor=factory(name$3n,dependencies$3n,(e=>{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),s=createAlgorithm12({typed:t,DenseMatrix:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3n,{"number, number":xorNumber,"Complex, Complex":function(e,t){return(0!==e.re||0!==e.im)!=(0!==t.re||0!==t.im)},"BigNumber, BigNumber":function(e,t){return(!e.isZero()&&!e.isNaN())!=(!t.isZero()&&!t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3m="concat",dependencies$3m=["typed","matrix","isInteger"],createConcat=factory(name$3m,dependencies$3m,(e=>{var{typed:t,matrix:n,isInteger:r}=e;return t(name$3m,{"...Array | Matrix | number | BigNumber":function(e){var t,a,i=e.length,s=-1,o=!1,l=[];for(t=0;t0&&s>a)throw new IndexError(s,a+1)}else{var c=clone$3(u).valueOf(),p=arraySize(c);if(l[t]=c,a=s,s=p.length-1,t>0&&s!==a)throw new DimensionError(a+1,s+1)}}if(0===l.length)throw new SyntaxError("At least one matrix expected");for(var d=l.shift();l.length;)d=_concat(d,l.shift(),s,0);return o?n(d):d},"...string":function(e){return e.join("")}})}));function _concat(e,t,n,r){if(r{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$3l,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$3(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[1]);var r=a(0,e.size()[0]),i=new n(r,t);return e.subset(i)}})),name$3k="count",dependencies$3k=["typed","size","prod"],createCount=factory(name$3k,dependencies$3k,(e=>{var{typed:t,size:n,prod:r}=e;return t(name$3k,{string:function(e){return e.length},"Matrix | Array":function(e){return r(n(e))}})})),name$3j="cross",dependencies$3j=["typed","matrix","subtract","multiply"],createCross=factory(name$3j,dependencies$3j,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a}=e;return t(name$3j,{"Matrix, Matrix":function(e,t){return n(i(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(i(e.toArray(),t))},"Array, Matrix":function(e,t){return n(i(e,t.toArray()))},"Array, Array":i});function i(e,t){var n=Math.max(arraySize(e).length,arraySize(t).length);e=squeeze$1(e),t=squeeze$1(t);var i=arraySize(e),s=arraySize(t);if(1!==i.length||1!==s.length||3!==i[0]||3!==s[0])throw new RangeError("Vectors with length 3 expected (Size A = ["+i.join(", ")+"], B = ["+s.join(", ")+"])");var o=[r(a(e[1],t[2]),a(e[2],t[1])),r(a(e[2],t[0]),a(e[0],t[2])),r(a(e[0],t[1]),a(e[1],t[0]))];return n>1?[o]:o}})),name$3i="diag",dependencies$3i=["typed","matrix","DenseMatrix","SparseMatrix"],createDiag=factory(name$3i,dependencies$3i,(e=>{var{typed:t,matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$3i,{Array:function(e){return i(e,0,arraySize(e),null)},"Array, number":function(e,t){return i(e,t,arraySize(e),null)},"Array, BigNumber":function(e,t){return i(e,t.toNumber(),arraySize(e),null)},"Array, string":function(e,t){return i(e,0,arraySize(e),t)},"Array, number, string":function(e,t,n){return i(e,t,arraySize(e),n)},"Array, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),arraySize(e),n)},Matrix:function(e){return i(e,0,e.size(),e.storage())},"Matrix, number":function(e,t){return i(e,t,e.size(),e.storage())},"Matrix, BigNumber":function(e,t){return i(e,t.toNumber(),e.size(),e.storage())},"Matrix, string":function(e,t){return i(e,0,e.size(),t)},"Matrix, number, string":function(e,t,n){return i(e,t,e.size(),n)},"Matrix, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),e.size(),n)}});function i(e,t,i,s){if(!isInteger$1(t))throw new TypeError("Second parameter in function diag must be an integer");var o=t>0?t:0,l=t<0?-t:0;switch(i.length){case 1:return function(e,t,n,i,s,o){var l=[i+s,i+o];if(n&&"sparse"!==n&&"dense"!==n)throw new TypeError("Unknown matrix type ".concat(n,'"'));var u="sparse"===n?a.diagonal(l,e,t):r.diagonal(l,e,t);return null!==n?u:u.valueOf()}(e,t,s,i[0],l,o);case 2:return function(e,t,r,a,i,s){if(isMatrix(e)){var o=e.diagonal(t);return null!==r?r!==o.storage()?n(o,r):o:o.valueOf()}for(var l=Math.min(a[0]-i,a[1]-s),u=[],c=0;c1&&void 0!==arguments[1]?arguments[1]:{};return n=null==n?Number.POSITIVE_INFINITY:n,t=null==t?JSON.stringify:t,function r(){"object"!=typeof r.cache&&(r.cache={values:new Map,lru:lruQueue(n||Number.POSITIVE_INFINITY)});for(var a=[],i=0;i{var{typed:t}=e;return t("filter",{"Array, function":_filterCallback,"Matrix, function":function(e,t){return e.create(_filterCallback(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}})}));function _filterCallback(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r]):t(e,[r],a)}))}var name$3g="flatten",dependencies$3g=["typed","matrix"],createFlatten=factory(name$3g,dependencies$3g,(e=>{var{typed:t,matrix:n}=e;return t(name$3g,{Array:function(e){return flatten$4(clone$3(e))},Matrix:function(e){var t=flatten$4(clone$3(e.toArray()));return n(t)}})})),name$3f="forEach",dependencies$3f=["typed"],createForEach=factory(name$3f,dependencies$3f,(e=>{var{typed:t}=e;return t(name$3f,{"Array, function":_forEach,"Matrix, function":function(e,t){return e.forEach(t)}})}));function _forEach(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e,[])}var name$3e="getMatrixDataType",dependencies$3e=["typed"],createGetMatrixDataType=factory(name$3e,dependencies$3e,(e=>{var{typed:t}=e;return t(name$3e,{Array:function(e){return getArrayDataType(e,typeOf$1)},Matrix:function(e){return e.getDataType()}})})),name$3d="identity",dependencies$3d=["typed","config","matrix","BigNumber","DenseMatrix","SparseMatrix"],createIdentity=factory(name$3d,dependencies$3d,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a,DenseMatrix:i,SparseMatrix:s}=e;return t(name$3d,{"":function(){return"Matrix"===n.matrix?r([]):[]},string:function(e){return r(e)},"number | BigNumber":function(e){return l(e,e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, string":function(e,t){return l(e,e,t)},"number | BigNumber, number | BigNumber":function(e,t){return l(e,t,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, number | BigNumber, string":function(e,t,n){return l(e,t,n)},Array:function(e){return o(e)},"Array, string":function(e,t){return o(e,t)},Matrix:function(e){return o(e.valueOf(),e.storage())},"Matrix, string":function(e,t){return o(e.valueOf(),t)}});function o(e,t){switch(e.length){case 0:return t?r(t):[];case 1:return l(e[0],e[0],t);case 2:return l(e[0],e[1],t);default:throw new Error("Vector containing two values expected")}}function l(e,t,n){var r=isBigNumber(e)||isBigNumber(t)?a:null;if(isBigNumber(e)&&(e=e.toNumber()),isBigNumber(t)&&(t=t.toNumber()),!isInteger$1(e)||e<1)throw new Error("Parameters in function identity must be positive integers");if(!isInteger$1(t)||t<1)throw new Error("Parameters in function identity must be positive integers");var o=r?new a(1):1,l=r?new r(0):0,u=[e,t];if(n){if("sparse"===n)return s.diagonal(u,o,0,l);if("dense"===n)return i.diagonal(u,o,0,l);throw new TypeError('Unknown matrix type "'.concat(n,'"'))}for(var c=resize$1([],u,l),p=e{var{typed:t,matrix:n,multiplyScalar:r}=e;return t(name$3c,{"Matrix, Matrix":function(e,t){return n(a(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(a(e.toArray(),t))},"Array, Matrix":function(e,t){return n(a(e,t.toArray()))},"Array, Array":a});function a(e,t){if(1===arraySize(e).length&&(e=[e]),1===arraySize(t).length&&(t=[t]),arraySize(e).length>2||arraySize(t).length>2)throw new RangeError("Vectors with dimensions greater then 2 are not supported expected (Size x = "+JSON.stringify(e.length)+", y = "+JSON.stringify(t.length)+")");var n=[],a=[];return e.map((function(e){return t.map((function(t){return a=[],n.push(a),e.map((function(e){return t.map((function(t){return a.push(r(e,t))}))}))}))}))&&n}})),name$3b="map",dependencies$3b=["typed"],createMap=factory(name$3b,dependencies$3b,(e=>{var{typed:t}=e;return t(name$3b,{"Array, function":_map$1,"Matrix, function":function(e,t){return e.map(t)}})}));function _map$1(e,t){var n=maxArgumentCount(t);return function r(a,i){if(Array.isArray(a))return a.map((function(e,t){return r(e,i.concat(t))}));try{return 1===n?t(a):2===n?t(a,i):t(a,i,e)}catch(t){if(t instanceof TypeError&&"data"in t&&"wrongType"===t.data.category){var s="map attempted to call '".concat(t.data.fn,"(").concat(a),o=JSON.stringify(i);throw 2===n?s+=","+o:1!==n&&(s+=",".concat(o,",").concat(e)),s+=")' but argument ".concat(t.data.index+1," of type "),s+="".concat(t.data.actual," does not match expected type "),s+=t.data.expected.join(" or "),new TypeError(s)}throw t}}(e,[])}var name$3a="diff",dependencies$3a=["typed","matrix","subtract","number"],createDiff=factory(name$3a,dependencies$3a,(e=>{var{typed:t,matrix:n,subtract:r,number:a}=e;return t(name$3a,{"Array | Matrix":function(e){return isMatrix(e)?n(s(e.toArray())):s(e)},"Array | Matrix, number":function(e,t){if(!isInteger$1(t))throw new RangeError("Dimension must be a whole number");return isMatrix(e)?n(i(e.toArray(),t)):i(e,t)},"Array | Matrix, BigNumber":function(e,t){return this(e,a(t))}});function i(e,t){if(isMatrix(e)&&(e=e.toArray()),!Array.isArray(e))throw RangeError("Array/Matrix does not have that many dimensions");if(t>0){var n=[];return e.forEach((e=>{n.push(i(e,t-1))})),n}if(0===t)return s(e);throw RangeError("Cannot have negative dimension")}function s(e){var t=[],n=e.length;if(n<2)return e;for(var r=1;r{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t("ones",{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(1):1;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function ones must be positive integers")}))}(e),t){var s=r(t);return e.length>0?s.resize(e,i):s}var o=[];return e.length>0?resize$1(o,e,i):o}}));function noBignumber(){throw new Error('No "bignumber" implementation available')}function noFraction(){throw new Error('No "fraction" implementation available')}function noMatrix(){throw new Error('No "matrix" implementation available')}var name$38="range",dependencies$38=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRange=factory(name$38,dependencies$38,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l}=e;return t(name$38,{string:c,"string, boolean":c,"number, number":function(e,t){return u(p(e,t,1))},"number, number, number":function(e,t,n){return u(p(e,t,n))},"number, number, boolean":function(e,t,n){return u(n?d(e,t,1):p(e,t,1))},"number, number, number, boolean":function(e,t,n,r){return u(r?d(e,t,n):p(e,t,n))},"BigNumber, BigNumber":function(e,t){return u(m(e,t,new e.constructor(1)))},"BigNumber, BigNumber, BigNumber":function(e,t,n){return u(m(e,t,n))},"BigNumber, BigNumber, boolean":function(e,t,n){var r=e.constructor;return u(n?h(e,t,new r(1)):m(e,t,new r(1)))},"BigNumber, BigNumber, BigNumber, boolean":function(e,t,n,r){return u(r?h(e,t,n):m(e,t,n))}});function u(e){return"Matrix"===n.matrix?r?r(e):noMatrix():e}function c(e,t){var r=function(e){var t=e.split(":").map((function(e){return Number(e)}));if(t.some((function(e){return isNaN(e)})))return null;switch(t.length){case 2:return{start:t[0],end:t[1],step:1};case 3:return{start:t[0],end:t[2],step:t[1]};default:return null}}(e);if(!r)throw new SyntaxError('String "'+e+'" is no valid range');return"BigNumber"===n.number?(void 0===a&&noBignumber(),u((t?h:m)(a(r.start),a(r.end),a(r.step)))):u((t?d:p)(r.start,r.end,r.step))}function p(e,t,n){var r=[],a=e;if(n>0)for(;i(a,t);)r.push(a),a+=n;else if(n<0)for(;o(a,t);)r.push(a),a+=n;return r}function d(e,t,n){var r=[],a=e;if(n>0)for(;s(a,t);)r.push(a),a+=n;else if(n<0)for(;l(a,t);)r.push(a),a+=n;return r}function m(e,t,n){var r=a(0),s=[],l=e;if(n.gt(r))for(;i(l,t);)s.push(l),l=l.plus(n);else if(n.lt(r))for(;o(l,t);)s.push(l),l=l.plus(n);return s}function h(e,t,n){var r=a(0),i=[],o=e;if(n.gt(r))for(;s(o,t);)i.push(o),o=o.plus(n);else if(n.lt(r))for(;l(o,t);)i.push(o),o=o.plus(n);return i}})),name$37="reshape",dependencies$37=["typed","isInteger","matrix"],createReshape=factory(name$37,dependencies$37,(e=>{var{typed:t,isInteger:n}=e;return t(name$37,{"Matrix, Array":function(e,t){return e.reshape(t)},"Array, Array":function(e,t){return t.forEach((function(e){if(!n(e))throw new TypeError("Invalid size for dimension: "+e)})),reshape$1(e,t)}})}));function ArgumentsError(e,t,n,r){if(!(this instanceof ArgumentsError))throw new SyntaxError("Constructor must be called with the new operator");this.fn=e,this.count=t,this.min=n,this.max=r,this.message="Wrong number of arguments in function "+e+" ("+t+" provided, "+n+(null!=r?"-"+r:"")+" expected)",this.stack=(new Error).stack}ArgumentsError.prototype=new Error,ArgumentsError.prototype.constructor=Error,ArgumentsError.prototype.name="ArgumentsError",ArgumentsError.prototype.isArgumentsError=!0;var name$36="resize",dependencies$36=["config","matrix"],createResize=factory(name$36,dependencies$36,(e=>{var{config:t,matrix:n}=e;return function(e,r,a){if(2!==arguments.length&&3!==arguments.length)throw new ArgumentsError("resize",arguments.length,2,3);if(isMatrix(r)&&(r=r.valueOf()),isBigNumber(r[0])&&(r=r.map((function(e){return isBigNumber(e)?e.toNumber():e}))),isMatrix(e))return e.resize(r,a,!0);if("string"==typeof e)return function(e,t,n){if(void 0!==n){if("string"!=typeof n||1!==n.length)throw new TypeError("Single character expected as defaultValue")}else n=" ";if(1!==t.length)throw new DimensionError(t.length,1);var r=t[0];if("number"!=typeof r||!isInteger$1(r))throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(t)+")");if(e.length>r)return e.substring(0,r);if(e.length{var{typed:t,multiply:n,rotationMatrix:r}=e;return t(name$35,{"Array , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e).toArray()},"Matrix , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e)},"Array, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)},"Matrix, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)}});function a(e,t){var n=Array.isArray(e)?arraySize(e):e.size();if(n.length>2)throw new RangeError("Vector must be of dimensions 1x".concat(t));if(2===n.length&&1!==n[1])throw new RangeError("Vector must be of dimensions 1x".concat(t));if(n[0]!==t)throw new RangeError("Vector must be of dimensions 1x".concat(t))}})),name$34="rotationMatrix",dependencies$34=["typed","config","multiplyScalar","addScalar","unaryMinus","norm","matrix","BigNumber","DenseMatrix","SparseMatrix","cos","sin"],createRotationMatrix=factory(name$34,dependencies$34,(e=>{var{typed:t,config:n,multiplyScalar:r,addScalar:a,unaryMinus:i,norm:s,BigNumber:o,matrix:l,DenseMatrix:u,SparseMatrix:c,cos:p,sin:d}=e;return t(name$34,{"":function(){return"Matrix"===n.matrix?l([]):[]},string:function(e){return l(e)},"number | BigNumber | Complex | Unit":function(e){return m(e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber | Complex | Unit, string":function(e,t){return m(e,t)},"number | BigNumber | Complex | Unit, Array":function(e,t){var n=l(t);return h(n),g(e,n,void 0)},"number | BigNumber | Complex | Unit, Matrix":function(e,t){h(t);var r=t.storage()||("Matrix"===n.matrix?"dense":void 0);return g(e,t,r)},"number | BigNumber | Complex | Unit, Array, string":function(e,t,n){var r=l(t);return h(r),g(e,r,n)},"number | BigNumber | Complex | Unit, Matrix, string":function(e,t,n){return h(t),g(e,t,n)}});function m(e,t){var n=isBigNumber(e)?new o(-1):-1,a=p(e),i=d(e);return y([[a,r(n,i)],[i,a]],t)}function h(e){var t=e.size();if(t.length<1||3!==t[0])throw new RangeError("Vector must be of dimensions 1x3")}function f(e){return e.reduce(((e,t)=>r(e,t)))}function y(e,t){if(t){if("sparse"===t)return new c(e);if("dense"===t)return new u(e);throw new TypeError('Unknown matrix type "'.concat(t,'"'))}return e}function g(e,t,n){var r=s(t);if(0===r)throw new RangeError("Rotation around zero vector");var l=isBigNumber(e)?o:null,u=l?new l(1):1,c=l?new l(-1):-1,m=l?new l(t.get([0])/r):t.get([0])/r,h=l?new l(t.get([1])/r):t.get([1])/r,g=l?new l(t.get([2])/r):t.get([2])/r,b=p(e),v=a(u,i(b)),N=d(e);return y([[a(b,f([m,m,v])),a(f([m,h,v]),f([c,g,N])),a(f([m,g,v]),f([h,N]))],[a(f([m,h,v]),f([g,N])),a(b,f([h,h,v])),a(f([h,g,v]),f([c,m,N]))],[a(f([m,g,v]),f([c,h,N])),a(f([h,g,v]),f([m,N])),a(b,f([g,g,v]))]],n)}})),name$33="row",dependencies$33=["typed","Index","matrix","range"],createRow=factory(name$33,dependencies$33,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$33,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$3(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[0]);var r=a(0,e.size()[1]),i=new n(t,r);return e.subset(i)}})),name$32="size",dependencies$32=["typed","config","?matrix"],createSize=factory(name$32,dependencies$32,(e=>{var{typed:t,config:n,matrix:r}=e;return t(name$32,{Matrix:function(e){return e.create(e.size())},Array:arraySize,string:function(e){return"Array"===n.matrix?[e.length]:r([e.length])},"number | Complex | BigNumber | Unit | boolean | null":function(e){return"Array"===n.matrix?[]:r?r([]):noMatrix()}})})),name$31="squeeze",dependencies$31=["typed","matrix"],createSqueeze=factory(name$31,dependencies$31,(e=>{var{typed:t,matrix:n}=e;return t(name$31,{Array:function(e){return squeeze$1(clone$3(e))},Matrix:function(e){var t=squeeze$1(e.toArray());return Array.isArray(t)?n(t):t},any:function(e){return clone$3(e)}})})),name$30="subset",dependencies$30=["typed","matrix"],createSubset=factory(name$30,dependencies$30,(e=>{var{typed:t,matrix:n}=e;return t(name$30,{"Array, Index":function(e,t){var r=n(e).subset(t);return t.isScalar()?r:r.valueOf()},"Matrix, Index":function(e,t){return e.subset(t)},"Object, Index":_getObjectProperty,"string, Index":_getSubstring,"Array, Index, any":function(e,t,r){return n(clone$3(e)).subset(t,r,void 0).valueOf()},"Array, Index, any, any":function(e,t,r,a){return n(clone$3(e)).subset(t,r,a).valueOf()},"Matrix, Index, any":function(e,t,n){return e.clone().subset(t,n)},"Matrix, Index, any, any":function(e,t,n,r){return e.clone().subset(t,n,r)},"string, Index, string":_setSubstring,"string, Index, string, string":_setSubstring,"Object, Index, any":_setObjectProperty})}));function _getSubstring(e,t){if(!isIndex(t))throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);var n=e.length;validateIndex(t.min()[0],n),validateIndex(t.max()[0],n);var r=t.dimension(0),a="";return r.forEach((function(t){a+=e.charAt(t)})),a}function _setSubstring(e,t,n,r){if(!t||!0!==t.isIndex)throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);if(void 0!==r){if("string"!=typeof r||1!==r.length)throw new TypeError("Single character expected as defaultValue")}else r=" ";var a=t.dimension(0);if(a.size()[0]!==n.length)throw new DimensionError(a.size()[0],n.length);var i=e.length;validateIndex(t.min()[0]),validateIndex(t.max()[0]);for(var s=[],o=0;oi)for(var l=i-1,u=s.length;l{var{typed:t,matrix:n}=e;return t("transpose",{Array:function(e){return this(n(e)).valueOf()},Matrix:function(e){var t,n=e.size();switch(n.length){case 1:t=e.clone();break;case 2:var r=n[0],a=n[1];if(0===a)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+format$1(n)+")");switch(e.storage()){case"dense":t=function(e,t,n){for(var r,a=e._data,i=[],s=0;s{var{typed:t,transpose:n,conj:r}=e;return t(name$2_,{any:function(e){return r(n(e))}})})),name$2Z="zeros",dependencies$2Z=["typed","config","matrix","BigNumber"],createZeros=factory(name$2Z,dependencies$2Z,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$2Z,{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(0):0;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function zeros must be positive integers")}))}(e),t){var s=r(t);return e.length>0?s.resize(e,i):s}var o=[];return e.length>0?resize$1(o,e,i):o}})),name$2Y="fft",dependencies$2Y=["typed","matrix","addScalar","multiplyScalar","divideScalar","exp","tau","i"],createFft=factory(name$2Y,dependencies$2Y,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,divideScalar:i,exp:s,tau:o,i:l}=e;return t(name$2Y,{Array:u,Matrix:function(e){return e.create(u(e.toArray()))}});function u(e){var t=arraySize(e);return 1===t.length?p(e,t[0]):c(e.map((e=>u(e,t.slice(1)))),0)}function c(e,t){var n=arraySize(e);if(0!==t)return new Array(n[0]).fill(0).map(((n,r)=>c(e[r],t-1)));if(1===n.length)return p(e);function r(e){var t=arraySize(e);return new Array(t[1]).fill(0).map(((n,r)=>new Array(t[0]).fill(0).map(((t,n)=>e[n][r]))))}return r(c(r(e),1))}function p(e){var t=e.length;if(1===t)return[e[0]];if(t%2==0){for(var n=[...p(e.filter(((e,t)=>t%2==0))),...p(e.filter(((e,t)=>t%2==1)))],u=0;u{var{typed:t,fft:n,dotDivide:r,conj:a}=e;return t(name$2X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);return r(a(n(a(e))),t.reduce(((e,t)=>e*t),1))}})})),name$2W="erf",dependencies$2W=["typed"],createErf=factory(name$2W,dependencies$2W,(e=>{var{typed:t}=e;return t("name",{number:function(e){var t=Math.abs(e);return t>=MAX_NUM?sign$3(e):t<=THRESH?sign$3(e)*function(e){var t,n=e*e,r=P[0][4]*n,a=n;for(t=0;t<3;t+=1)r=(r+P[0][t])*n,a=(a+Q[0][t])*n;return e*(r+P[0][3])/(a+Q[0][3])}(t):t<=4?sign$3(e)*(1-function(e){var t,n=P[1][8]*e,r=e;for(t=0;t<7;t+=1)n=(n+P[1][t])*e,r=(r+Q[1][t])*e;var a=(n+P[1][7])/(r+Q[1][7]),i=parseInt(16*e)/16,s=(e-i)*(e+i);return Math.exp(-i*i)*Math.exp(-s)*a}(t)):sign$3(e)*(1-function(e){var t,n=1/(e*e),r=P[2][5]*n,a=n;for(t=0;t<4;t+=1)r=(r+P[2][t])*n,a=(a+Q[2][t])*n;var i=n*(r+P[2][4])/(a+Q[2][4]);i=(SQRPI-i)/e;var s=(e-(n=parseInt(16*e)/16))*(e+n);return Math.exp(-n*n)*Math.exp(-s)*i}(t))},"Array | Matrix":function(e){return deepMap(e,this)}})})),THRESH=.46875,SQRPI=.5641895835477563,P=[[3.1611237438705655,113.86415415105016,377.485237685302,3209.3775891384694,.18577770618460315],[.5641884969886701,8.883149794388377,66.11919063714163,298.6351381974001,881.952221241769,1712.0476126340707,2051.0783778260716,1230.3393547979972,2.1531153547440383e-8],[.30532663496123236,.36034489994980445,.12578172611122926,.016083785148742275,.0006587491615298378,.016315387137302097]],Q=[[23.601290952344122,244.02463793444417,1282.6165260773723,2844.236833439171],[15.744926110709835,117.6939508913125,537.1811018620099,1621.3895745666903,3290.7992357334597,4362.619090143247,3439.3676741437216,1230.3393548037495],[2.568520192289822,1.8729528499234604,.5279051029514285,.06051834131244132,.0023352049762686918]],MAX_NUM=Math.pow(2,53),name$2V="mode",dependencies$2V=["typed","isNaN","isNumeric"],createMode=factory(name$2V,dependencies$2V,(e=>{var{typed:t,isNaN:n,isNumeric:r}=e;return t(name$2V,{"Array | Matrix":a,"...":function(e){return a(e)}});function a(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate mode of an empty array");for(var t={},a=[],i=0,s=0;si&&(i=t[o],a=[o])}return a}}));function improveErrorMessage(e,t,n){var r;return-1!==String(e).indexOf("Unexpected type")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":" (type: "+e.data.actual+")",new TypeError("Cannot calculate "+t+", unexpected type of argument"+r)):-1!==String(e).indexOf("complex numbers")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":"",new TypeError("Cannot calculate "+t+", no ordering relation is defined for complex numbers"+r)):e}var name$2U="prod",dependencies$2U=["typed","config","multiplyScalar","numeric"],createProd=factory(name$2U,dependencies$2U,(e=>{var{typed:t,config:n,multiplyScalar:r,numeric:a}=e;return t(name$2U,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("prod(A, dim) is not yet supported")},"...":function(e){return i(e)}});function i(e){var t;if(deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"prod",e)}})),"string"==typeof t&&(t=a(t,n.number)),void 0===t)throw new Error("Cannot calculate prod of an empty array");return t}})),name$2T="format",dependencies$2T=["typed"],createFormat=factory(name$2T,dependencies$2T,(e=>{var{typed:t}=e;return t(name$2T,{any:format$1,"any, Object | function | number":format$1})})),name$2S="bin",dependencies$2S=["typed","format"],createBin=factory(name$2S,dependencies$2S,(e=>{var{typed:t,format:n}=e;return t(name$2S,{"number | BigNumber":function(e){return n(e,{notation:"bin"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"bin",wordSize:t})}})})),name$2R="oct",dependencies$2R=["typed","format"],createOct=factory(name$2R,dependencies$2R,(e=>{var{typed:t,format:n}=e;return t(name$2R,{"number | BigNumber":function(e){return n(e,{notation:"oct"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"oct",wordSize:t})}})})),name$2Q="hex",dependencies$2Q=["typed","format"],createHex=factory(name$2Q,dependencies$2Q,(e=>{var{typed:t,format:n}=e;return t(name$2Q,{"number | BigNumber":function(e){return n(e,{notation:"hex"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"hex",wordSize:t})}})})),name$2P="print",dependencies$2P=["typed"],createPrint=factory(name$2P,dependencies$2P,(e=>{var{typed:t}=e;return t(name$2P,{"string, Object | Array":_print,"string, Object | Array, number | Object":_print})}));function _print(e,t,n){return e.replace(/\$([\w.]+)/g,(function(e,r){for(var a=r.split("."),i=t[a.shift()];a.length&&void 0!==i;){var s=a.shift();i=s?i[s]:i+"."}return void 0!==i?isString$1(i)?i:format$1(i,n):e}))}var name$2O="to",dependencies$2O=["typed","matrix"],createTo=factory(name$2O,dependencies$2O,(e=>{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2O,{"Unit, Unit | string":function(e,t){return e.to(t)},"Matrix, Matrix":function(e,t){return r(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"Matrix, any":function(e,t){return a(e,t,this,!1)},"any, Matrix":function(e,t){return a(t,e,this,!0)},"Array, any":function(e,t){return a(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,this,!0).valueOf()}})})),name$2N="isPrime",dependencies$2N=["typed"],createIsPrime=factory(name$2N,dependencies$2N,(e=>{var{typed:t}=e;return t(name$2N,{number:function(e){if(0*e!=0)return!1;if(e<=3)return e>1;if(e%2==0||e%3==0)return!1;for(var t=5;t*t<=e;t+=6)if(e%t==0||e%(t+2)==0)return!1;return!0},BigNumber:function(e){if(0*e.toNumber()!=0)return!1;if(e.lte(3))return e.gt(1);if(e.mod(2).eq(0)||e.mod(3).eq(0))return!1;if(e.lt(Math.pow(2,32))){for(var t=e.toNumber(),n=5;n*n<=t;n+=6)if(t%n==0||t%(n+2)==0)return!1;return!0}function r(e,t,n){for(var r=1;!t.eq(0);)t.mod(2).eq(0)?(t=t.div(2),e=e.mul(e).mod(n)):(t=t.sub(1),r=e.mul(r).mod(n));return r}for(var a=e.constructor.clone({precision:2*e.toFixed(0).length}),i=0,s=(e=new a(e)).sub(1);s.mod(2).eq(0);)s=s.div(2),i+=1;var o=null;if(e.lt("3317044064679887385961981"))o=[2,3,5,7,11,13,17,19,23,29,31,37,41].filter((t=>t{var{number:t,bignumber:n,fraction:r}=e,a={string:!0,number:!0,BigNumber:!0,Fraction:!0},i={number:e=>t(e),BigNumber:n?e=>n(e):noBignumber,Fraction:r?e=>r(e):noFraction};return function(e,t){var n=typeOf$1(e);if(!(n in a))throw new TypeError("Cannot convert "+e+' of type "'+n+'"; valid input types are '+Object.keys(a).join(", "));if(!(t in i))throw new TypeError("Cannot convert "+e+' to type "'+t+'"; valid output types are '+Object.keys(i).join(", "));return t===n?e:i[t](e)}})),name$2L="divideScalar",dependencies$2L=["typed","numeric"],createDivideScalar=factory(name$2L,dependencies$2L,(e=>{var{typed:t,numeric:n}=e;return t(name$2L,{"number, number":function(e,t){return e/t},"Complex, Complex":function(e,t){return e.div(t)},"BigNumber, BigNumber":function(e,t){return e.div(t)},"Fraction, Fraction":function(e,t){return e.div(t)},"Unit, number | Fraction | BigNumber":function(e,t){var r=e.clone(),a=n(1,typeOf$1(t));return r.value=this(null===r.value?r._normalize(a):r.value,t),r},"number | Fraction | BigNumber, Unit":function(e,t){var r=t.clone();r=r.pow(-1);var a=n(1,typeOf$1(e));return r.value=this(e,null===t.value?t._normalize(a):t.value),r},"Unit, Unit":function(e,t){return e.divide(t)}})})),name$2K="pow",dependencies$2K=["typed","config","identity","multiply","matrix","inv","fraction","number","Complex"],createPow=factory(name$2K,dependencies$2K,(e=>{var{typed:t,config:n,identity:r,multiply:a,matrix:i,inv:s,number:o,fraction:l,Complex:u}=e;return t(name$2K,{"number, number":c,"Complex, Complex":function(e,t){return e.pow(t)},"BigNumber, BigNumber":function(e,t){return t.isInteger()||e>=0||n.predictable?e.pow(t):new u(e.toNumber(),0).pow(t.toNumber(),0)},"Fraction, Fraction":function(e,t){var r=e.pow(t);if(null!=r)return r;if(n.predictable)throw new Error("Result of pow is non-rational and cannot be expressed as a fraction");return c(e.valueOf(),t.valueOf())},"Array, number":p,"Array, BigNumber":function(e,t){return p(e,t.toNumber())},"Matrix, number":d,"Matrix, BigNumber":function(e,t){return d(e,t.toNumber())},"Unit, number | BigNumber":function(e,t){return e.pow(t)}});function c(e,t){if(n.predictable&&!isInteger$1(t)&&e<0)try{var r=l(t),a=o(r);if((t===a||Math.abs((t-a)/t)<1e-14)&&r.d%2==1)return(r.n%2==0?1:-1)*Math.pow(-e,t)}catch(e){}return n.predictable&&(e<-1&&t===1/0||e>-1&&e<0&&t===-1/0)?NaN:isInteger$1(t)||e>=0||n.predictable?powNumber(e,t):e*e<1&&t===1/0||e*e>1&&t===-1/0?0:new u(e,0).pow(t,0)}function p(e,t){if(!isInteger$1(t))throw new TypeError("For A^b, b must be an integer (value is "+t+")");var n=arraySize(e);if(2!==n.length)throw new Error("For A^b, A must be 2 dimensional (A has "+n.length+" dimensions)");if(n[0]!==n[1])throw new Error("For A^b, A must be square (size is "+n[0]+"x"+n[1]+")");if(t<0)try{return p(s(e),-t)}catch(e){if("Cannot calculate inverse, determinant is zero"===e.message)throw new TypeError("For A^b, when A is not invertible, b must be a positive integer (value is "+t+")");throw e}for(var i=r(n[0]).valueOf(),o=e;t>=1;)1==(1&t)&&(i=a(o,i)),t>>=1,o=a(o,o);return i}function d(e,t){return i(p(e.valueOf(),t))}})),NO_INT="Number of decimals in function round must be an integer",name$2J="round",dependencies$2J=["typed","matrix","equalScalar","zeros","BigNumber","DenseMatrix"],createRound=factory(name$2J,dependencies$2J,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,BigNumber:i,DenseMatrix:s}=e,o=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm12({typed:t,DenseMatrix:s}),u=createAlgorithm14({typed:t});return t(name$2J,{number:roundNumber,"number, number":roundNumber,"number, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return new i(e).toDecimalPlaces(t.toNumber())},Complex:function(e){return e.round()},"Complex, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Complex, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);var n=t.toNumber();return e.round(n)},BigNumber:function(e){return e.toDecimalPlaces(0)},"BigNumber, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.toDecimalPlaces(t.toNumber())},Fraction:function(e){return e.round()},"Fraction, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Fraction, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.round(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"SparseMatrix, number | BigNumber":function(e,t){return o(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"Array, number | BigNumber":function(e,t){return u(n(e),t,this,!1).valueOf()},"number | Complex | BigNumber | Fraction, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):l(t,e,this,!0)},"number | Complex | BigNumber | Fraction, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | Complex | BigNumber | Fraction, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$2I="log",dependencies$2I=["config","typed","divideScalar","Complex"],createLog=factory(name$2I,dependencies$2I,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e;return t(name$2I,{number:function(e){return e>=0||n.predictable?logNumber(e):new a(e,0).log()},Complex:function(e){return e.log()},BigNumber:function(e){return!e.isNegative()||n.predictable?e.ln():new a(e.toNumber(),0).log()},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),this(t))}})})),name$2H="log1p",dependencies$2H=["typed","config","divideScalar","log","Complex"],createLog1p=factory(name$2H,dependencies$2H,(e=>{var{typed:t,config:n,divideScalar:r,log:a,Complex:i}=e;return t(name$2H,{number:function(e){return e>=-1||n.predictable?log1p$1(e):s(new i(e,0))},Complex:s,BigNumber:function(e){var t=e.plus(1);return!t.isNegative()||n.predictable?t.ln():s(new i(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),a(t))}});function s(e){var t=e.re+1;return new i(Math.log(Math.sqrt(t*t+e.im*e.im)),Math.atan2(e.im,t))}})),name$2G="nthRoots",dependencies$2G=["config","typed","divideScalar","Complex"],createNthRoots=factory(name$2G,dependencies$2G,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e,i=[function(e){return new a(e,0)},function(e){return new a(0,e)},function(e){return new a(-e,0)},function(e){return new a(0,-e)}];function s(e,t){if(t<0)throw new Error("Root must be greater than zero");if(0===t)throw new Error("Root must be non-zero");if(t%1!=0)throw new Error("Root must be an integer");if(0===e||0===e.abs())return[new a(0,0)];var n,r="number"==typeof e;(r||0===e.re||0===e.im)&&(n=r?2*+(e<0):0===e.im?2*+(e.re<0):2*+(e.im<0)+1);for(var s=e.arg(),o=e.abs(),l=[],u=Math.pow(o,1/t),c=0;c{var{typed:t,equalScalar:n,matrix:r,pow:a,DenseMatrix:i}=e,s=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm11({typed:t,equalScalar:n}),u=createAlgorithm12({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$2F,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,a)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(r(t),e,this,!0).valueOf()}})})),name$2E="dotDivide",dependencies$2E=["typed","matrix","equalScalar","divideScalar","DenseMatrix"],createDotDivide=factory(name$2E,dependencies$2E,(e=>{var{typed:t,matrix:n,equalScalar:r,divideScalar:a,DenseMatrix:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm03({typed:t}),l=createAlgorithm07({typed:t,DenseMatrix:i}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2E,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return u(e,t,a,!1)},"DenseMatrix, any":function(e,t){return d(e,t,a,!1)},"any, SparseMatrix":function(e,t){return c(t,e,a,!0)},"any, DenseMatrix":function(e,t){return d(t,e,a,!0)},"Array, any":function(e,t){return d(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,a,!0).valueOf()}})}));function createSolveValidation(e){var{DenseMatrix:t}=e;return function(e,n,r){var a=e.size();if(2!==a.length)throw new RangeError("Matrix must be two dimensional (size: "+format$1(a)+")");var i=a[0];if(i!==a[1])throw new RangeError("Matrix must be square (size: "+format$1(a)+")");var s=[];if(isMatrix(n)){var o=n.size(),l=n._data;if(1===o.length){if(o[0]!==i)throw new RangeError("Dimension mismatch. Matrix columns must match vector length.");for(var u=0;u{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2D,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=[],f=0;ff&&(b.push(p[C]),v.push(A))}if(s(g,0))throw new Error("Linear system cannot be solved since matrix is singular");for(var V=r(y,g),x=0,S=v.length;x{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2C,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=[],f=c-1;f>=0;f--){var y=n[f][0]||0;if(s(y,0))h[f]=[0];else{for(var g=0,b=[],v=[],N=m[f],T=m[f+1]-1;T>=N;T--){var C=d[T];C===f?g=p[T]:C=0;m--){var h=n[m][0]||0,f=void 0;if(s(h,0))f=0;else{var y=d[m][m];if(s(y,0))throw new Error("Linear system cannot be solved since matrix is singular");f=r(h,y);for(var g=m-1;g>=0;g--)n[g]=[i(n[g][0]||0,a(f,d[g][m]))]}p[m]=[f]}return new o({data:p,size:[u,1]})}})),name$2B="lsolveAll",dependencies$2B=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createLsolveAll=factory(name$2B,dependencies$2B,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2B,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=0;hh&&(b.push(p[A]),v.push(V))}if(s(C,0))if(s(g[h],0)){if(0===y){var x=[...g];x[h]=1;for(var S=0,w=v.length;Snew o({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1],d=0;dnew o({data:e.map((e=>[e])),size:[c,1]})))}})),name$2A="usolveAll",dependencies$2A=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createUsolveAll=factory(name$2A,dependencies$2A,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2A,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=c-1;h>=0;h--)for(var f=n.length,y=0;y=N;C--){var A=d[C];A===h?T=p[C]:Anew o({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1]-1;p>=0;p--)for(var d=n.length,m=0;m=0;y--)f[y]=i(f[y],u[y][p]);n.push(f)}}else{if(0===m)return[];n.splice(m,1),m-=1,d-=1}else{h[p]=r(h[p],u[p][p]);for(var g=p-1;g>=0;g--)h[g]=i(h[g],a(h[p],u[g][p]))}}return n.map((e=>new o({data:e.map((e=>[e])),size:[c,1]})))}})),name$2z="algorithm08",dependencies$2z=["typed","equalScalar"],createAlgorithm08=factory(name$2z,dependencies$2z,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");if(!i||!c)throw new Error("Cannot perform operation on Pattern Sparse Matrices");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));for(var T,C,A,V,x=[],S=[],w=[],E=[],D=[],O=0;O{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2y,{"number, number":leftShiftNumber,"BigNumber, BigNumber":leftShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2x="rightArithShift",dependencies$2x=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightArithShift=factory(name$2x,dependencies$2x,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2x,{"number, number":rightArithShiftNumber,"BigNumber, BigNumber":rightArithShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2w="rightLogShift",dependencies$2w=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightLogShift=factory(name$2w,dependencies$2w,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2w,{"number, number":rightLogShiftNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2v="and",dependencies$2v=["typed","matrix","equalScalar","zeros","not"],createAnd=factory(name$2v,dependencies$2v,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,not:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$2v,{"number, number":andNumber,"Complex, Complex":function(e,t){return!(0===e.re&&0===e.im||0===t.re&&0===t.im)},"BigNumber, BigNumber":function(e,t){return!(e.isZero()||t.isZero()||e.isNaN()||t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):c(e,t,this,!1)},"any, SparseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):l(t,e,this,!0)},"any, DenseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):c(t,e,this,!0)},"Array, any":function(e,t){return this(n(e),t).valueOf()},"any, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2u="compare",dependencies$2u=["typed","config","matrix","equalScalar","BigNumber","Fraction","DenseMatrix"],createCompare=factory(name$2u,dependencies$2u,(e=>{var{typed:t,config:n,equalScalar:r,matrix:a,BigNumber:i,Fraction:s,DenseMatrix:o}=e,l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:o}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2u,{"boolean, boolean":function(e,t){return e===t?0:e>t?1:-1},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)?0:e>t?1:-1},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,t,n.epsilon)?new i(0):new i(e.cmp(t))},"Fraction, Fraction":function(e,t){return new s(e.compare(t))},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return c(e,t,this,!1)},"DenseMatrix, any":function(e,t){return d(e,t,this,!1)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(a(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(a(t),e,this,!0).valueOf()}})})),naturalSort=function e(t,n){var r,a,i=/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,s=/(^[ ]*|[ ]*$)/g,o=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,l=/^0x[0-9a-f]+$/i,u=/^0/,c=function(t){return e.insensitive&&(""+t).toLowerCase()||""+t},p=c(t).replace(s,"")||"",d=c(n).replace(s,"")||"",m=p.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),h=d.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),f=parseInt(p.match(l),16)||1!==m.length&&p.match(o)&&Date.parse(p),y=parseInt(d.match(l),16)||f&&d.match(o)&&Date.parse(d)||null;if(y){if(fy)return 1}for(var g=0,b=Math.max(m.length,h.length);ga)return 1}return 0},name$2t="compareNatural",dependencies$2t=["typed","compare"],createCompareNatural=factory(name$2t,dependencies$2t,(e=>{var{typed:t,compare:n}=e,r=n.signatures["boolean,boolean"];return t(name$2t,{"any, any":function(e,t){var s,o=typeOf$1(e),l=typeOf$1(t);if(!("number"!==o&&"BigNumber"!==o&&"Fraction"!==o||"number"!==l&&"BigNumber"!==l&&"Fraction"!==l))return"0"!==(s=n(e,t)).toString()?s>0?1:-1:naturalSort(o,l);if("Array"===o||"Matrix"===o||"Array"===l||"Matrix"===l)return 0!==(s=a(this,e,t))?s:naturalSort(o,l);if(o!==l)return naturalSort(o,l);if("Complex"===o)return compareComplexNumbers(e,t);if("Unit"===o)return e.equalBase(t)?this(e.value,t.value):i(this,e.formatUnits(),t.formatUnits());if("boolean"===o)return r(e,t);if("string"===o)return naturalSort(e,t);if("Object"===o)return function(e,t,n){var r=Object.keys(t),a=Object.keys(n);r.sort(naturalSort),a.sort(naturalSort);var s=i(e,r,a);if(0!==s)return s;for(var o=0;on.length?1:t.lengtht.re?1:e.ret.im?1:e.im{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2s,{"any, any":compareText$1,"DenseMatrix, DenseMatrix":function(e,t){return r(e,t,compareText$1)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return a(e,t,compareText$1,!1)},"any, DenseMatrix":function(e,t){return a(t,e,compareText$1,!0)},"Array, any":function(e,t){return a(n(e),t,compareText$1,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,compareText$1,!0).valueOf()}})})),name$2r="equal",dependencies$2r=["typed","matrix","equalScalar","DenseMatrix"],createEqual=factory(name$2r,dependencies$2r,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:r(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,r)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,r,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,r,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,r,!1)},"DenseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, SparseMatrix":function(e,t){return o(t,e,r,!0)},"any, DenseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return u(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,r,!0).valueOf()}})}));factory(name$2r,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:n(e,t)}})}));var name$2q="equalText",dependencies$2q=["typed","compareText","isZero"],createEqualText=factory(name$2q,dependencies$2q,(e=>{var{typed:t,compareText:n,isZero:r}=e;return t(name$2q,{"any, any":function(e,t){return r(n(e,t))}})})),name$2p="smaller",dependencies$2p=["typed","config","matrix","DenseMatrix"],createSmaller=factory(name$2p,dependencies$2p,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2p,{"boolean, boolean":function(e,t){return e{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2o,{"boolean, boolean":function(e,t){return e<=t},"number, number":function(e,t){return e<=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.lte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2n="larger",dependencies$2n=["typed","config","matrix","DenseMatrix"],createLarger=factory(name$2n,dependencies$2n,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2n,{"boolean, boolean":function(e,t){return e>t},"number, number":function(e,t){return e>t&&!nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gt(t)&&!nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1===e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2m="largerEq",dependencies$2m=["typed","config","matrix","DenseMatrix"],createLargerEq=factory(name$2m,dependencies$2m,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2m,{"boolean, boolean":function(e,t){return e>=t},"number, number":function(e,t){return e>=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return-1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2l="deepEqual",dependencies$2l=["typed","equal"],createDeepEqual=factory(name$2l,dependencies$2l,(e=>{var{typed:t,equal:n}=e;return t(name$2l,{"any, any":function(e,t){return r(e.valueOf(),t.valueOf())}});function r(e,t){if(Array.isArray(e)){if(Array.isArray(t)){var a=e.length;if(a!==t.length)return!1;for(var i=0;i{var{typed:t,config:n,equalScalar:r,matrix:a,DenseMatrix:i}=e,s=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm12({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t("unequal",{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:p(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,p)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,p,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,p,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,p)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return l(e,t,p,!1)},"DenseMatrix, any":function(e,t){return c(e,t,p,!1)},"any, SparseMatrix":function(e,t){return l(t,e,p,!0)},"any, DenseMatrix":function(e,t){return c(t,e,p,!0)},"Array, any":function(e,t){return c(a(e),t,p,!1).valueOf()},"any, Array":function(e,t){return c(a(t),e,p,!0).valueOf()}});function p(e,t){return!r(e,t)}}));factory(name$2k,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2k,{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:!n(e,t)}})}));var name$2j="partitionSelect",dependencies$2j=["typed","isNumeric","isNaN","compare"],createPartitionSelect=factory(name$2j,dependencies$2j,(e=>{var{typed:t,isNumeric:n,isNaN:r,compare:a}=e,i=a,s=(e,t)=>-a(e,t);return t(name$2j,{"Array | Matrix, number":function(e,t){return o(e,t,i)},"Array | Matrix, number, string":function(e,t,n){if("asc"===n)return o(e,t,i);if("desc"===n)return o(e,t,s);throw new Error('Compare string must be "asc" or "desc"')},"Array | Matrix, number, function":o});function o(e,t,n){if(!isInteger$1(t)||t<0)throw new Error("k must be a non-negative integer");if(isMatrix(e)){if(e.size().length>1)throw new Error("Only one dimensional matrices supported");return l(e.valueOf(),t,n)}if(Array.isArray(e))return l(e,t,n)}function l(e,t,a){if(t>=e.length)throw new Error("k out of bounds");for(var i=0;i=0){var p=e[u];e[u]=e[l],e[l]=p,--u}else++l;a(e[l],c)>0&&--l,t<=l?o=l:s=l+1}return e[t]}})),name$2i="sort",dependencies$2i=["typed","matrix","compare","compareNatural"],createSort=factory(name$2i,dependencies$2i,(e=>{var{typed:t,matrix:n,compare:r,compareNatural:a}=e,i=r,s=(e,t)=>-r(e,t);return t(name$2i,{Array:function(e){return l(e),e.sort(i)},Matrix:function(e){return u(e),n(e.toArray().sort(i),e.storage())},"Array, function":function(e,t){return l(e),e.sort(t)},"Matrix, function":function(e,t){return u(e),n(e.toArray().sort(t),e.storage())},"Array, string":function(e,t){return l(e),e.sort(o(t))},"Matrix, string":function(e,t){return u(e),n(e.toArray().sort(o(t)),e.storage())}});function o(e){if("asc"===e)return i;if("desc"===e)return s;if("natural"===e)return a;throw new Error('String "asc", "desc", or "natural" expected')}function l(e){if(1!==arraySize(e).length)throw new Error("One dimensional array expected")}function u(e){if(1!==e.size().length)throw new Error("One dimensional matrix expected")}})),name$2h="max",dependencies$2h=["typed","config","numeric","larger"],createMax=factory(name$2h,dependencies$2h,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e;return t(name$2h,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function max");return s(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"max",t)}}function s(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"max",e)}})),void 0===t)throw new Error("Cannot calculate max of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2g="min",dependencies$2g=["typed","config","numeric","smaller"],createMin=factory(name$2g,dependencies$2g,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e;return t(name$2g,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function min");return s(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"min",t)}}function s(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"min",e)}})),void 0===t)throw new Error("Cannot calculate min of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2f="ImmutableDenseMatrix",dependencies$2f=["smaller","DenseMatrix"],createImmutableDenseMatrixClass=factory(name$2f,dependencies$2f,(e=>{var{smaller:t,DenseMatrix:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e)||isArray$1(e)){var a=new n(e,t);this._data=a._data,this._size=a._size,this._datatype=a._datatype,this._min=null,this._max=null}else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,this._datatype=e.datatype,this._min=void 0!==e.min?e.min:null,this._max=void 0!==e.max?e.max:null;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t,this._min=null,this._max=null}}return r.prototype=new n,r.prototype.type="ImmutableDenseMatrix",r.prototype.isImmutableDenseMatrix=!0,r.prototype.subset=function(e){switch(arguments.length){case 1:var t=n.prototype.subset.call(this,e);return isMatrix(t)?new r({data:t._data,size:t._size,datatype:t._datatype}):t;case 2:case 3:throw new Error("Cannot invoke set subset on an Immutable Matrix instance");default:throw new SyntaxError("Wrong number of arguments")}},r.prototype.set=function(){throw new Error("Cannot invoke set on an Immutable Matrix instance")},r.prototype.resize=function(){throw new Error("Cannot invoke resize on an Immutable Matrix instance")},r.prototype.reshape=function(){throw new Error("Cannot invoke reshape on an Immutable Matrix instance")},r.prototype.clone=function(){return new r({data:clone$3(this._data),size:clone$3(this._size),datatype:this._datatype})},r.prototype.toJSON=function(){return{mathjs:"ImmutableDenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},r.fromJSON=function(e){return new r(e)},r.prototype.swapRows=function(){throw new Error("Cannot invoke swapRows on an Immutable Matrix instance")},r.prototype.min=function(){if(null===this._min){var e=null;this.forEach((function(n){(null===e||t(n,e))&&(e=n)})),this._min=null!==e?e:void 0}return this._min},r.prototype.max=function(){if(null===this._max){var e=null;this.forEach((function(n){(null===e||t(e,n))&&(e=n)})),this._max=null!==e?e:void 0}return this._max},r}),{isClass:!0}),name$2e="Index",dependencies$2e=["ImmutableDenseMatrix"],createIndexClass=factory(name$2e,dependencies$2e,(e=>{var{ImmutableDenseMatrix:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this._dimensions=[],this._isScalar=!0;for(var t=0,a=arguments.length;t{var{smaller:t,larger:n}=e,r=1/Math.log((1+Math.sqrt(5))/2);function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._minimum=null,this._size=0}function i(e,t,n){t.left.right=t.right,t.right.left=t.left,n.degree--,n.child===t&&(n.child=t.right),0===n.degree&&(n.child=null),t.left=e,t.right=e.right,e.right=t,t.right.left=t,t.parent=null,t.mark=!1}function s(e,t){var n=t.parent;n&&(t.mark?(i(e,t,n),s(n)):t.mark=!0)}a.prototype.type="FibonacciHeap",a.prototype.isFibonacciHeap=!0,a.prototype.insert=function(e,n){var r={key:e,value:n,degree:0};if(this._minimum){var a=this._minimum;r.left=a,r.right=a.right,a.right=r,r.right.left=r,t(e,a.key)&&(this._minimum=r)}else r.left=r,r.right=r,this._minimum=r;return this._size++,r},a.prototype.size=function(){return this._size},a.prototype.clear=function(){this._minimum=null,this._size=0},a.prototype.isEmpty=function(){return 0===this._size},a.prototype.extractMinimum=function(){var e=this._minimum;if(null===e)return e;for(var a=this._minimum,i=e.degree,s=e.child;i>0;){var l=s.right;s.left.right=s.right,s.right.left=s.left,s.left=a,s.right=a.right,a.right=s,s.right.left=s,s.parent=null,s=l,i--}return e.left.right=e.right,e.right.left=e.left,a=e===e.right?null:function(e,a){var i,s=Math.floor(Math.log(a)*r)+1,l=new Array(s),u=0,c=e;if(c)for(u++,c=c.right;c!==e;)u++,c=c.right;for(;u>0;){for(var p=c.degree,d=c.right;i=l[p];){if(n(c.key,i.key)){var m=i;i=c,c=m}o(i,c),l[p]=null,p++}l[p]=c,c=d,u--}e=null;for(var h=0;h{var{addScalar:t,equalScalar:n,FibonacciHeap:r}=e;function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._values=[],this._heap=new r}return a.prototype.type="Spa",a.prototype.isSpa=!0,a.prototype.set=function(e,t){if(this._values[e])this._values[e].value=t;else{var n=this._heap.insert(e,t);this._values[e]=n}},a.prototype.get=function(e){var t=this._values[e];return t?t.value:0},a.prototype.accumulate=function(e,n){var r=this._values[e];r?r.value=t(r.value,n):(r=this._heap.insert(e,n),this._values[e]=r)},a.prototype.forEach=function(e,t,r){var a=this._heap,i=this._values,s=[],o=a.extractMinimum();for(o&&s.push(o);o&&o.key<=t;)o.key>=e&&(n(o.value,0)||r(o.key,o.value,this)),(o=a.extractMinimum())&&s.push(o);for(var l=0;l{var t,n,r,{on:a,config:i,addScalar:s,subtract:o,multiplyScalar:l,divideScalar:u,pow:c,abs:p,fix:d,round:m,equal:h,isNumeric:f,format:y,number:g,Complex:b,BigNumber:v,Fraction:N}=e,T=g;function C(e,t){if(!(this instanceof C))throw new Error("Constructor must be called with the new operator");if(null!=e&&!f(e)&&!isComplex(e))throw new TypeError("First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined");if(void 0!==t&&("string"!=typeof t||""===t))throw new TypeError("Second parameter in Unit constructor must be a string");if(void 0!==t){var n=C.parse(t);this.units=n.units,this.dimensions=n.dimensions}else{this.units=[{unit:F,prefix:R.NONE,power:0}],this.dimensions=[];for(var r=0;r<_.length;r++)this.dimensions[r]=0}this.value=null!=e?this._normalize(e):null,this.fixPrefix=!1,this.skipAutomaticSimplification=!0}function A(){for(;" "===r||"\t"===r;)x()}function V(e){return e>="0"&&e<="9"}function x(){n++,r=t.charAt(n)}function S(e){n=e,r=t.charAt(n)}function w(){var e="",t=n;if("+"===r?x():"-"===r&&(e+=r,x()),!function(e){return e>="0"&&e<="9"||"."===e}(r))return S(t),null;if("."===r){if(e+=r,x(),!V(r))return S(t),null}else{for(;V(r);)e+=r,x();"."===r&&(e+=r,x())}for(;V(r);)e+=r,x();if("E"===r||"e"===r){var a="",i=n;if(a+=r,x(),"+"!==r&&"-"!==r||(a+=r,x()),!V(r))return S(i),e;for(e+=a;V(r);)e+=r,x()}return e}function E(){for(var e="";V(r)||C.isValidAlpha(r);)e+=r,x();var t=e.charAt(0);return C.isValidAlpha(t)?e:null}function D(e){return r===e?(x(),e):null}C.prototype.type="Unit",C.prototype.isUnit=!0,C.parse=function(e,a){if(a=a||{},n=-1,r="","string"!=typeof(t=e))throw new TypeError("Invalid argument in Unit.parse, string expected");var s=new C;s.units=[];var o=1,l=!1;x(),A();var u=w(),c=null;if(u){if("BigNumber"===i.number)c=new v(u);else if("Fraction"===i.number)try{c=new N(u)}catch(e){c=parseFloat(u)}else c=parseFloat(u);A(),D("*")?(o=1,l=!0):D("/")&&(o=-1,l=!0)}for(var p=[],d=1;;){for(A();"("===r;)p.push(o),d*=o,o=1,x(),A();var m;if(!r)break;var h=r;if(null===(m=E()))throw new SyntaxError('Unexpected "'+h+'" in "'+t+'" at index '+n.toString());var f=O(m);if(null===f)throw new SyntaxError('Unit "'+m+'" not found.');var y=o*d;if(A(),D("^")){A();var g=w();if(null===g)throw new SyntaxError('In "'+e+'", "^" must be followed by a floating-point number');y*=g}s.units.push({unit:f.unit,prefix:f.prefix,power:y});for(var b=0;b<_.length;b++)s.dimensions[b]+=(f.unit.dimensions[b]||0)*y;for(A();")"===r;){if(0===p.length)throw new SyntaxError('Unmatched ")" in "'+t+'" at index '+n.toString());d/=p.pop(),x(),A()}if(l=!1,D("*")?(o=1,l=!0):D("/")?(o=-1,l=!0):o=1,f.unit.base){var T=f.unit.base.key;L.auto[T]={unit:f.unit,prefix:f.prefix}}}if(A(),r)throw new SyntaxError('Could not parse: "'+e+'"');if(l)throw new SyntaxError('Trailing characters: "'+e+'"');if(0!==p.length)throw new SyntaxError('Unmatched "(" in "'+t+'"');if(0===s.units.length&&!a.allowNoUnits)throw new SyntaxError('"'+e+'" contains no units');return s.value=void 0!==c?s._normalize(c):null,s},C.prototype.clone=function(){var e=new C;e.fixPrefix=this.fixPrefix,e.skipAutomaticSimplification=this.skipAutomaticSimplification,e.value=clone$3(this.value),e.dimensions=this.dimensions.slice(0),e.units=[];for(var t=0;t1||Math.abs(this.units[0].power-1)>1e-15)},C.prototype._normalize=function(e){if(null==e||0===this.units.length)return e;for(var t=e,n=C._getNumberConverter(typeOf$1(e)),r=0;r{if(hasOwnProperty$2(k,e)){var t=k[e];return{unit:t,prefix:t.prefixes[""]}}for(var n in k)if(hasOwnProperty$2(k,n)&&endsWith(e,n)){var r=k[n],a=e.length-n.length,i=e.substring(0,a),s=hasOwnProperty$2(r.prefixes,i)?r.prefixes[i]:void 0;if(void 0!==s)return{unit:r,prefix:s}}return null}),{hasher:e=>e[0],limit:100});function I(e){return e.equalBase(M.NONE)&&null!==e.value&&!i.predictable?e.value:e}C.isValuelessUnit=function(e){return null!==O(e)},C.prototype.hasBase=function(e){if("string"==typeof e&&(e=M[e]),!e)return!1;for(var t=0;t<_.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},C.prototype.equalBase=function(e){for(var t=0;t<_.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},C.prototype.equals=function(e){return this.equalBase(e)&&h(this.value,e.value)},C.prototype.multiply=function(e){for(var t=this.clone(),n=0;n<_.length;n++)t.dimensions[n]=(this.dimensions[n]||0)+(e.dimensions[n]||0);for(var r=0;r1e-12&&(hasOwnProperty$2(z,o)?r.push({unit:z[o].unit,prefix:z[o].prefix,power:n.dimensions[s]||0}):i=!0)}r.length1e-12){if(!hasOwnProperty$2(L.si,r))throw new Error("Cannot express custom unit "+r+" in SI units");t.push({unit:L.si[r].unit,prefix:L.si[r].prefix,power:e.dimensions[n]||0})}}return e.units=t,e.fixPrefix=!0,e.skipAutomaticSimplification=!0,e},C.prototype.formatUnits=function(){for(var e="",t="",n=0,r=0,a=0;a0?(n++,e+=" "+this.units[a].prefix.name+this.units[a].unit.name,Math.abs(this.units[a].power-1)>1e-15&&(e+="^"+this.units[a].power)):this.units[a].power<0&&r++;if(r>0)for(var i=0;i0?(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,Math.abs(this.units[i].power+1)>1e-15&&(t+="^"+-this.units[i].power)):(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,t+="^"+this.units[i].power));e=e.substr(1),t=t.substr(1),n>1&&r>0&&(e="("+e+")"),r>1&&n>0&&(t="("+t+")");var s=e;return n>0&&r>0&&(s+=" / "),s+t},C.prototype.format=function(e){var t=this.skipAutomaticSimplification||null===this.value?this.clone():this.simplify(),n=!1;for(var r in void 0!==t.value&&null!==t.value&&isComplex(t.value)&&(n=Math.abs(t.value.re)<1e-14),t.units)hasOwnProperty$2(t.units,r)&&t.units[r].unit&&("VA"===t.units[r].unit.name&&n?t.units[r].unit=k.VAR:"VAR"!==t.units[r].unit.name||n||(t.units[r].unit=k.VA));1!==t.units.length||t.fixPrefix||Math.abs(t.units[0].power-Math.round(t.units[0].power))<1e-14&&(t.units[0].prefix=t._bestPrefix());var a=t._denormalize(t.value),i=null!==t.value?y(a,e||{}):"",s=t.formatUnits();return t.value&&isComplex(t.value)&&(i="("+i+")"),s.length>0&&i.length>0&&(i+=" "),i+s},C.prototype._bestPrefix=function(){if(1!==this.units.length)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");if(Math.abs(this.units[0].power-Math.round(this.units[0].power))>=1e-14)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");var e=null!==this.value?p(this.value):0,t=p(this.units[0].unit.value),n=this.units[0].prefix;if(0===e)return n;var r=this.units[0].power,a=Math.log(e/Math.pow(n.value*t,r))/Math.LN10-1.2;if(a>-2.200001&&a<1.800001)return n;a=Math.abs(a);var i=this.units[0].unit.prefixes;for(var s in i)if(hasOwnProperty$2(i,s)){var o=i[s];if(o.scientific){var l=Math.abs(Math.log(e/Math.pow(o.value*t,r))/Math.LN10-1.2);(l0))},k={meter:{name:"meter",base:M.LENGTH,prefixes:R.LONG,value:1,offset:0},inch:{name:"inch",base:M.LENGTH,prefixes:R.NONE,value:.0254,offset:0},foot:{name:"foot",base:M.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yard:{name:"yard",base:M.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mile:{name:"mile",base:M.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},link:{name:"link",base:M.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rod:{name:"rod",base:M.LENGTH,prefixes:R.NONE,value:5.0292,offset:0},chain:{name:"chain",base:M.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},angstrom:{name:"angstrom",base:M.LENGTH,prefixes:R.NONE,value:1e-10,offset:0},m:{name:"m",base:M.LENGTH,prefixes:R.SHORT,value:1,offset:0},in:{name:"in",base:M.LENGTH,prefixes:R.NONE,value:.0254,offset:0},ft:{name:"ft",base:M.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yd:{name:"yd",base:M.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mi:{name:"mi",base:M.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},li:{name:"li",base:M.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rd:{name:"rd",base:M.LENGTH,prefixes:R.NONE,value:5.02921,offset:0},ch:{name:"ch",base:M.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},mil:{name:"mil",base:M.LENGTH,prefixes:R.NONE,value:254e-7,offset:0},m2:{name:"m2",base:M.SURFACE,prefixes:R.SQUARED,value:1,offset:0},sqin:{name:"sqin",base:M.SURFACE,prefixes:R.NONE,value:64516e-8,offset:0},sqft:{name:"sqft",base:M.SURFACE,prefixes:R.NONE,value:.09290304,offset:0},sqyd:{name:"sqyd",base:M.SURFACE,prefixes:R.NONE,value:.83612736,offset:0},sqmi:{name:"sqmi",base:M.SURFACE,prefixes:R.NONE,value:2589988.110336,offset:0},sqrd:{name:"sqrd",base:M.SURFACE,prefixes:R.NONE,value:25.29295,offset:0},sqch:{name:"sqch",base:M.SURFACE,prefixes:R.NONE,value:404.6873,offset:0},sqmil:{name:"sqmil",base:M.SURFACE,prefixes:R.NONE,value:6.4516e-10,offset:0},acre:{name:"acre",base:M.SURFACE,prefixes:R.NONE,value:4046.86,offset:0},hectare:{name:"hectare",base:M.SURFACE,prefixes:R.NONE,value:1e4,offset:0},m3:{name:"m3",base:M.VOLUME,prefixes:R.CUBIC,value:1,offset:0},L:{name:"L",base:M.VOLUME,prefixes:R.SHORT,value:.001,offset:0},l:{name:"l",base:M.VOLUME,prefixes:R.SHORT,value:.001,offset:0},litre:{name:"litre",base:M.VOLUME,prefixes:R.LONG,value:.001,offset:0},cuin:{name:"cuin",base:M.VOLUME,prefixes:R.NONE,value:16387064e-12,offset:0},cuft:{name:"cuft",base:M.VOLUME,prefixes:R.NONE,value:.028316846592,offset:0},cuyd:{name:"cuyd",base:M.VOLUME,prefixes:R.NONE,value:.764554857984,offset:0},teaspoon:{name:"teaspoon",base:M.VOLUME,prefixes:R.NONE,value:5e-6,offset:0},tablespoon:{name:"tablespoon",base:M.VOLUME,prefixes:R.NONE,value:15e-6,offset:0},drop:{name:"drop",base:M.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},gtt:{name:"gtt",base:M.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},minim:{name:"minim",base:M.VOLUME,prefixes:R.NONE,value:6.161152e-8,offset:0},fluiddram:{name:"fluiddram",base:M.VOLUME,prefixes:R.NONE,value:36966911e-13,offset:0},fluidounce:{name:"fluidounce",base:M.VOLUME,prefixes:R.NONE,value:2957353e-11,offset:0},gill:{name:"gill",base:M.VOLUME,prefixes:R.NONE,value:.0001182941,offset:0},cc:{name:"cc",base:M.VOLUME,prefixes:R.NONE,value:1e-6,offset:0},cup:{name:"cup",base:M.VOLUME,prefixes:R.NONE,value:.0002365882,offset:0},pint:{name:"pint",base:M.VOLUME,prefixes:R.NONE,value:.0004731765,offset:0},quart:{name:"quart",base:M.VOLUME,prefixes:R.NONE,value:.0009463529,offset:0},gallon:{name:"gallon",base:M.VOLUME,prefixes:R.NONE,value:.003785412,offset:0},beerbarrel:{name:"beerbarrel",base:M.VOLUME,prefixes:R.NONE,value:.1173478,offset:0},oilbarrel:{name:"oilbarrel",base:M.VOLUME,prefixes:R.NONE,value:.1589873,offset:0},hogshead:{name:"hogshead",base:M.VOLUME,prefixes:R.NONE,value:.238481,offset:0},fldr:{name:"fldr",base:M.VOLUME,prefixes:R.NONE,value:36966911e-13,offset:0},floz:{name:"floz",base:M.VOLUME,prefixes:R.NONE,value:2957353e-11,offset:0},gi:{name:"gi",base:M.VOLUME,prefixes:R.NONE,value:.0001182941,offset:0},cp:{name:"cp",base:M.VOLUME,prefixes:R.NONE,value:.0002365882,offset:0},pt:{name:"pt",base:M.VOLUME,prefixes:R.NONE,value:.0004731765,offset:0},qt:{name:"qt",base:M.VOLUME,prefixes:R.NONE,value:.0009463529,offset:0},gal:{name:"gal",base:M.VOLUME,prefixes:R.NONE,value:.003785412,offset:0},bbl:{name:"bbl",base:M.VOLUME,prefixes:R.NONE,value:.1173478,offset:0},obl:{name:"obl",base:M.VOLUME,prefixes:R.NONE,value:.1589873,offset:0},g:{name:"g",base:M.MASS,prefixes:R.SHORT,value:.001,offset:0},gram:{name:"gram",base:M.MASS,prefixes:R.LONG,value:.001,offset:0},ton:{name:"ton",base:M.MASS,prefixes:R.SHORT,value:907.18474,offset:0},t:{name:"t",base:M.MASS,prefixes:R.SHORT,value:1e3,offset:0},tonne:{name:"tonne",base:M.MASS,prefixes:R.LONG,value:1e3,offset:0},grain:{name:"grain",base:M.MASS,prefixes:R.NONE,value:6479891e-11,offset:0},dram:{name:"dram",base:M.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},ounce:{name:"ounce",base:M.MASS,prefixes:R.NONE,value:.028349523125,offset:0},poundmass:{name:"poundmass",base:M.MASS,prefixes:R.NONE,value:.45359237,offset:0},hundredweight:{name:"hundredweight",base:M.MASS,prefixes:R.NONE,value:45.359237,offset:0},stick:{name:"stick",base:M.MASS,prefixes:R.NONE,value:.115,offset:0},stone:{name:"stone",base:M.MASS,prefixes:R.NONE,value:6.35029318,offset:0},gr:{name:"gr",base:M.MASS,prefixes:R.NONE,value:6479891e-11,offset:0},dr:{name:"dr",base:M.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},oz:{name:"oz",base:M.MASS,prefixes:R.NONE,value:.028349523125,offset:0},lbm:{name:"lbm",base:M.MASS,prefixes:R.NONE,value:.45359237,offset:0},cwt:{name:"cwt",base:M.MASS,prefixes:R.NONE,value:45.359237,offset:0},s:{name:"s",base:M.TIME,prefixes:R.SHORT,value:1,offset:0},min:{name:"min",base:M.TIME,prefixes:R.NONE,value:60,offset:0},h:{name:"h",base:M.TIME,prefixes:R.NONE,value:3600,offset:0},second:{name:"second",base:M.TIME,prefixes:R.LONG,value:1,offset:0},sec:{name:"sec",base:M.TIME,prefixes:R.LONG,value:1,offset:0},minute:{name:"minute",base:M.TIME,prefixes:R.NONE,value:60,offset:0},hour:{name:"hour",base:M.TIME,prefixes:R.NONE,value:3600,offset:0},day:{name:"day",base:M.TIME,prefixes:R.NONE,value:86400,offset:0},week:{name:"week",base:M.TIME,prefixes:R.NONE,value:604800,offset:0},month:{name:"month",base:M.TIME,prefixes:R.NONE,value:2629800,offset:0},year:{name:"year",base:M.TIME,prefixes:R.NONE,value:31557600,offset:0},decade:{name:"decade",base:M.TIME,prefixes:R.NONE,value:315576e3,offset:0},century:{name:"century",base:M.TIME,prefixes:R.NONE,value:315576e4,offset:0},millennium:{name:"millennium",base:M.TIME,prefixes:R.NONE,value:315576e5,offset:0},hertz:{name:"Hertz",base:M.FREQUENCY,prefixes:R.LONG,value:1,offset:0,reciprocal:!0},Hz:{name:"Hz",base:M.FREQUENCY,prefixes:R.SHORT,value:1,offset:0,reciprocal:!0},rad:{name:"rad",base:M.ANGLE,prefixes:R.SHORT,value:1,offset:0},radian:{name:"radian",base:M.ANGLE,prefixes:R.LONG,value:1,offset:0},deg:{name:"deg",base:M.ANGLE,prefixes:R.SHORT,value:null,offset:0},degree:{name:"degree",base:M.ANGLE,prefixes:R.LONG,value:null,offset:0},grad:{name:"grad",base:M.ANGLE,prefixes:R.SHORT,value:null,offset:0},gradian:{name:"gradian",base:M.ANGLE,prefixes:R.LONG,value:null,offset:0},cycle:{name:"cycle",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},arcsec:{name:"arcsec",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},arcmin:{name:"arcmin",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},A:{name:"A",base:M.CURRENT,prefixes:R.SHORT,value:1,offset:0},ampere:{name:"ampere",base:M.CURRENT,prefixes:R.LONG,value:1,offset:0},K:{name:"K",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:0},degC:{name:"degC",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:273.15},degF:{name:"degF",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:459.67},degR:{name:"degR",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:0},kelvin:{name:"kelvin",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:0},celsius:{name:"celsius",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:273.15},fahrenheit:{name:"fahrenheit",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:459.67},rankine:{name:"rankine",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:0},mol:{name:"mol",base:M.AMOUNT_OF_SUBSTANCE,prefixes:R.SHORT,value:1,offset:0},mole:{name:"mole",base:M.AMOUNT_OF_SUBSTANCE,prefixes:R.LONG,value:1,offset:0},cd:{name:"cd",base:M.LUMINOUS_INTENSITY,prefixes:R.SHORT,value:1,offset:0},candela:{name:"candela",base:M.LUMINOUS_INTENSITY,prefixes:R.LONG,value:1,offset:0},N:{name:"N",base:M.FORCE,prefixes:R.SHORT,value:1,offset:0},newton:{name:"newton",base:M.FORCE,prefixes:R.LONG,value:1,offset:0},dyn:{name:"dyn",base:M.FORCE,prefixes:R.SHORT,value:1e-5,offset:0},dyne:{name:"dyne",base:M.FORCE,prefixes:R.LONG,value:1e-5,offset:0},lbf:{name:"lbf",base:M.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},poundforce:{name:"poundforce",base:M.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},kip:{name:"kip",base:M.FORCE,prefixes:R.LONG,value:4448.2216,offset:0},kilogramforce:{name:"kilogramforce",base:M.FORCE,prefixes:R.NONE,value:9.80665,offset:0},J:{name:"J",base:M.ENERGY,prefixes:R.SHORT,value:1,offset:0},joule:{name:"joule",base:M.ENERGY,prefixes:R.SHORT,value:1,offset:0},erg:{name:"erg",base:M.ENERGY,prefixes:R.NONE,value:1e-7,offset:0},Wh:{name:"Wh",base:M.ENERGY,prefixes:R.SHORT,value:3600,offset:0},BTU:{name:"BTU",base:M.ENERGY,prefixes:R.BTU,value:1055.05585262,offset:0},eV:{name:"eV",base:M.ENERGY,prefixes:R.SHORT,value:1602176565e-28,offset:0},electronvolt:{name:"electronvolt",base:M.ENERGY,prefixes:R.LONG,value:1602176565e-28,offset:0},W:{name:"W",base:M.POWER,prefixes:R.SHORT,value:1,offset:0},watt:{name:"watt",base:M.POWER,prefixes:R.LONG,value:1,offset:0},hp:{name:"hp",base:M.POWER,prefixes:R.NONE,value:745.6998715386,offset:0},VAR:{name:"VAR",base:M.POWER,prefixes:R.SHORT,value:b.I,offset:0},VA:{name:"VA",base:M.POWER,prefixes:R.SHORT,value:1,offset:0},Pa:{name:"Pa",base:M.PRESSURE,prefixes:R.SHORT,value:1,offset:0},psi:{name:"psi",base:M.PRESSURE,prefixes:R.NONE,value:6894.75729276459,offset:0},atm:{name:"atm",base:M.PRESSURE,prefixes:R.NONE,value:101325,offset:0},bar:{name:"bar",base:M.PRESSURE,prefixes:R.SHORTLONG,value:1e5,offset:0},torr:{name:"torr",base:M.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmHg:{name:"mmHg",base:M.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmH2O:{name:"mmH2O",base:M.PRESSURE,prefixes:R.NONE,value:9.80665,offset:0},cmH2O:{name:"cmH2O",base:M.PRESSURE,prefixes:R.NONE,value:98.0665,offset:0},coulomb:{name:"coulomb",base:M.ELECTRIC_CHARGE,prefixes:R.LONG,value:1,offset:0},C:{name:"C",base:M.ELECTRIC_CHARGE,prefixes:R.SHORT,value:1,offset:0},farad:{name:"farad",base:M.ELECTRIC_CAPACITANCE,prefixes:R.LONG,value:1,offset:0},F:{name:"F",base:M.ELECTRIC_CAPACITANCE,prefixes:R.SHORT,value:1,offset:0},volt:{name:"volt",base:M.ELECTRIC_POTENTIAL,prefixes:R.LONG,value:1,offset:0},V:{name:"V",base:M.ELECTRIC_POTENTIAL,prefixes:R.SHORT,value:1,offset:0},ohm:{name:"ohm",base:M.ELECTRIC_RESISTANCE,prefixes:R.SHORTLONG,value:1,offset:0},henry:{name:"henry",base:M.ELECTRIC_INDUCTANCE,prefixes:R.LONG,value:1,offset:0},H:{name:"H",base:M.ELECTRIC_INDUCTANCE,prefixes:R.SHORT,value:1,offset:0},siemens:{name:"siemens",base:M.ELECTRIC_CONDUCTANCE,prefixes:R.LONG,value:1,offset:0},S:{name:"S",base:M.ELECTRIC_CONDUCTANCE,prefixes:R.SHORT,value:1,offset:0},weber:{name:"weber",base:M.MAGNETIC_FLUX,prefixes:R.LONG,value:1,offset:0},Wb:{name:"Wb",base:M.MAGNETIC_FLUX,prefixes:R.SHORT,value:1,offset:0},tesla:{name:"tesla",base:M.MAGNETIC_FLUX_DENSITY,prefixes:R.LONG,value:1,offset:0},T:{name:"T",base:M.MAGNETIC_FLUX_DENSITY,prefixes:R.SHORT,value:1,offset:0},b:{name:"b",base:M.BIT,prefixes:R.BINARY_SHORT,value:1,offset:0},bits:{name:"bits",base:M.BIT,prefixes:R.BINARY_LONG,value:1,offset:0},B:{name:"B",base:M.BIT,prefixes:R.BINARY_SHORT,value:8,offset:0},bytes:{name:"bytes",base:M.BIT,prefixes:R.BINARY_LONG,value:8,offset:0}},$={meters:"meter",inches:"inch",feet:"foot",yards:"yard",miles:"mile",links:"link",rods:"rod",chains:"chain",angstroms:"angstrom",lt:"l",litres:"litre",liter:"litre",liters:"litre",teaspoons:"teaspoon",tablespoons:"tablespoon",minims:"minim",fluiddrams:"fluiddram",fluidounces:"fluidounce",gills:"gill",cups:"cup",pints:"pint",quarts:"quart",gallons:"gallon",beerbarrels:"beerbarrel",oilbarrels:"oilbarrel",hogsheads:"hogshead",gtts:"gtt",grams:"gram",tons:"ton",tonnes:"tonne",grains:"grain",drams:"dram",ounces:"ounce",poundmasses:"poundmass",hundredweights:"hundredweight",sticks:"stick",lb:"lbm",lbs:"lbm",kips:"kip",kgf:"kilogramforce",acres:"acre",hectares:"hectare",sqfeet:"sqft",sqyard:"sqyd",sqmile:"sqmi",sqmiles:"sqmi",mmhg:"mmHg",mmh2o:"mmH2O",cmh2o:"cmH2O",seconds:"second",secs:"second",minutes:"minute",mins:"minute",hours:"hour",hr:"hour",hrs:"hour",days:"day",weeks:"week",months:"month",years:"year",decades:"decade",centuries:"century",millennia:"millennium",hertz:"hertz",radians:"radian",degrees:"degree",gradians:"gradian",cycles:"cycle",arcsecond:"arcsec",arcseconds:"arcsec",arcminute:"arcmin",arcminutes:"arcmin",BTUs:"BTU",watts:"watt",joules:"joule",amperes:"ampere",coulombs:"coulomb",volts:"volt",ohms:"ohm",farads:"farad",webers:"weber",teslas:"tesla",electronvolts:"electronvolt",moles:"mole",bit:"bits",byte:"bytes"};function B(e){if("BigNumber"===e.number){var t=createBigNumberPi(v);k.rad.value=new v(1),k.deg.value=t.div(180),k.grad.value=t.div(200),k.cycle.value=t.times(2),k.arcsec.value=t.div(648e3),k.arcmin.value=t.div(10800)}else k.rad.value=1,k.deg.value=Math.PI/180,k.grad.value=Math.PI/200,k.cycle.value=2*Math.PI,k.arcsec.value=Math.PI/648e3,k.arcmin.value=Math.PI/10800;k.radian.value=k.rad.value,k.degree.value=k.deg.value,k.gradian.value=k.grad.value}B(i),a&&a("config",(function(e,t){e.number!==t.number&&B(e)}));var L={si:{NONE:{unit:F,prefix:R.NONE[""]},LENGTH:{unit:k.m,prefix:R.SHORT[""]},MASS:{unit:k.g,prefix:R.SHORT.k},TIME:{unit:k.s,prefix:R.SHORT[""]},CURRENT:{unit:k.A,prefix:R.SHORT[""]},TEMPERATURE:{unit:k.K,prefix:R.SHORT[""]},LUMINOUS_INTENSITY:{unit:k.cd,prefix:R.SHORT[""]},AMOUNT_OF_SUBSTANCE:{unit:k.mol,prefix:R.SHORT[""]},ANGLE:{unit:k.rad,prefix:R.SHORT[""]},BIT:{unit:k.bits,prefix:R.SHORT[""]},FORCE:{unit:k.N,prefix:R.SHORT[""]},ENERGY:{unit:k.J,prefix:R.SHORT[""]},POWER:{unit:k.W,prefix:R.SHORT[""]},PRESSURE:{unit:k.Pa,prefix:R.SHORT[""]},ELECTRIC_CHARGE:{unit:k.C,prefix:R.SHORT[""]},ELECTRIC_CAPACITANCE:{unit:k.F,prefix:R.SHORT[""]},ELECTRIC_POTENTIAL:{unit:k.V,prefix:R.SHORT[""]},ELECTRIC_RESISTANCE:{unit:k.ohm,prefix:R.SHORT[""]},ELECTRIC_INDUCTANCE:{unit:k.H,prefix:R.SHORT[""]},ELECTRIC_CONDUCTANCE:{unit:k.S,prefix:R.SHORT[""]},MAGNETIC_FLUX:{unit:k.Wb,prefix:R.SHORT[""]},MAGNETIC_FLUX_DENSITY:{unit:k.T,prefix:R.SHORT[""]},FREQUENCY:{unit:k.Hz,prefix:R.SHORT[""]}}};L.cgs=JSON.parse(JSON.stringify(L.si)),L.cgs.LENGTH={unit:k.m,prefix:R.SHORT.c},L.cgs.MASS={unit:k.g,prefix:R.SHORT[""]},L.cgs.FORCE={unit:k.dyn,prefix:R.SHORT[""]},L.cgs.ENERGY={unit:k.erg,prefix:R.NONE[""]},L.us=JSON.parse(JSON.stringify(L.si)),L.us.LENGTH={unit:k.ft,prefix:R.NONE[""]},L.us.MASS={unit:k.lbm,prefix:R.NONE[""]},L.us.TEMPERATURE={unit:k.degF,prefix:R.NONE[""]},L.us.FORCE={unit:k.lbf,prefix:R.NONE[""]},L.us.ENERGY={unit:k.BTU,prefix:R.BTU[""]},L.us.POWER={unit:k.hp,prefix:R.NONE[""]},L.us.PRESSURE={unit:k.psi,prefix:R.NONE[""]},L.auto=JSON.parse(JSON.stringify(L.si));var z=L.auto;for(var U in C.setUnitSystem=function(e){if(!hasOwnProperty$2(L,e))throw new Error("Unit system "+e+" does not exist. Choices are: "+Object.keys(L).join(", "));z=L[e]},C.getUnitSystem=function(){for(var e in L)if(hasOwnProperty$2(L,e)&&L[e]===z)return e},C.typeConverters={BigNumber:function(e){return new v(e+"")},Fraction:function(e){return new N(e)},Complex:function(e){return e},number:function(e){return e}},C._getNumberConverter=function(e){if(!C.typeConverters[e])throw new TypeError('Unsupported type "'+e+'"');return C.typeConverters[e]},k)if(hasOwnProperty$2(k,U)){var j=k[U];j.dimensions=j.base.dimensions}for(var q in $)if(hasOwnProperty$2($,q)){var G=k[$[q]],H={};for(var W in G)hasOwnProperty$2(G,W)&&(H[W]=G[W]);H.name=q,k[q]=H}return C.isValidAlpha=function(e){return/^[a-zA-Z]$/.test(e)},C.createUnit=function(e,t){if("object"!=typeof e)throw new TypeError("createUnit expects first parameter to be of type 'Object'");if(t&&t.override)for(var n in e)if(hasOwnProperty$2(e,n)&&C.deleteUnit(n),e[n].aliases)for(var r=0;r0&&!C.isValidAlpha(r)&&!V(r))throw new Error('Invalid unit name (only alphanumeric characters are allowed): "'+e+'"')}}(e);var a,i,s,o=null,l=[],u=0;if(t&&"Unit"===t.type)o=t.clone();else if("string"==typeof t)""!==t&&(a=t);else{if("object"!=typeof t)throw new TypeError('Cannot create unit "'+e+'" from "'+t.toString()+'": expecting "string" or "Unit" or "Object"');a=t.definition,i=t.prefixes,u=t.offset,s=t.baseName,t.aliases&&(l=t.aliases.valueOf())}if(l)for(var c=0;c1e-12){h=!1;break}if(h){d=!0,p.base=M[m];break}}if(!d){s=s||e+"_STUFF";var y={dimensions:o.dimensions.slice(0)};y.key=s,M[s]=y,z[s]={unit:p,prefix:R.NONE[""]},p.base=M[s]}}else{if(s=s||e+"_STUFF",_.indexOf(s)>=0)throw new Error('Cannot create new base unit "'+e+'": a base unit with that name already exists (and cannot be overridden)');for(var g in _.push(s),M)hasOwnProperty$2(M,g)&&(M[g].dimensions[_.length-1]=0);for(var b={dimensions:[]},v=0;v<_.length;v++)b.dimensions[v]=0;b.dimensions[_.length-1]=1,b.key=s,M[s]=b,p={name:e,value:1,dimensions:M[s].dimensions.slice(0),prefixes:i,offset:u,base:M[s]},z[s]={unit:p,prefix:R.NONE[""]}}C.UNITS[e]=p;for(var N=0;N{var{typed:t,Unit:n}=e;return t(name$2a,{Unit:function(e){return e.clone()},string:function(e){return n.isValuelessUnit(e)?new n(null,e):n.parse(e,{allowNoUnits:!0})},"number | BigNumber | Fraction | Complex, string":function(e,t){return new n(e,t)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$29="sparse",dependencies$29=["typed","SparseMatrix"],createSparse=factory(name$29,dependencies$29,(e=>{var{typed:t,SparseMatrix:n}=e;return t(name$29,{"":function(){return new n([])},string:function(e){return new n([],e)},"Array | Matrix":function(e){return new n(e)},"Array | Matrix, string":function(e,t){return new n(e,t)}})})),name$28="createUnit",dependencies$28=["typed","Unit"],createCreateUnit=factory(name$28,dependencies$28,(e=>{var{typed:t,Unit:n}=e;return t(name$28,{"Object, Object":function(e,t){return n.createUnit(e,t)},Object:function(e){return n.createUnit(e,{})},"string, Unit | string | Object, Object":function(e,t,r){var a={};return a[e]=t,n.createUnit(a,r)},"string, Unit | string | Object":function(e,t){var r={};return r[e]=t,n.createUnit(r,{})},string:function(e){var t={};return t[e]={},n.createUnit(t,{})}})})),name$27="acos",dependencies$27=["typed","config","Complex"],createAcos=factory(name$27,dependencies$27,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$27,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.acos(e):new r(e,0).acos()},Complex:function(e){return e.acos()},BigNumber:function(e){return e.acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$26="acosh",dependencies$26=["typed","config","Complex"],createAcosh=factory(name$26,dependencies$26,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$26,{number:function(e){return e>=1||n.predictable?acoshNumber(e):e<=-1?new r(Math.log(Math.sqrt(e*e-1)-e),Math.PI):new r(e,0).acosh()},Complex:function(e){return e.acosh()},BigNumber:function(e){return e.acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$25="acot",dependencies$25=["typed","BigNumber"],createAcot=factory(name$25,dependencies$25,(e=>{var{typed:t,BigNumber:n}=e;return t(name$25,{number:acotNumber,Complex:function(e){return e.acot()},BigNumber:function(e){return new n(1).div(e).atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$24="acoth",dependencies$24=["typed","config","Complex","BigNumber"],createAcoth=factory(name$24,dependencies$24,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$24,{number:function(e){return e>=1||e<=-1||n.predictable?acothNumber(e):new r(e,0).acoth()},Complex:function(e){return e.acoth()},BigNumber:function(e){return new a(1).div(e).atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$23="acsc",dependencies$23=["typed","config","Complex","BigNumber"],createAcsc=factory(name$23,dependencies$23,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$23,{number:function(e){return e<=-1||e>=1||n.predictable?acscNumber(e):new r(e,0).acsc()},Complex:function(e){return e.acsc()},BigNumber:function(e){return new a(1).div(e).asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$22="acsch",dependencies$22=["typed","BigNumber"],createAcsch=factory(name$22,dependencies$22,(e=>{var{typed:t,BigNumber:n}=e;return t(name$22,{number:acschNumber,Complex:function(e){return e.acsch()},BigNumber:function(e){return new n(1).div(e).asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$21="asec",dependencies$21=["typed","config","Complex","BigNumber"],createAsec=factory(name$21,dependencies$21,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$21,{number:function(e){return e<=-1||e>=1||n.predictable?asecNumber(e):new r(e,0).asec()},Complex:function(e){return e.asec()},BigNumber:function(e){return new a(1).div(e).acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$20="asech",dependencies$20=["typed","config","Complex","BigNumber"],createAsech=factory(name$20,dependencies$20,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$20,{number:function(e){if(e<=1&&e>=-1||n.predictable){var t=1/e;if(t>0||n.predictable)return asechNumber(e);var a=Math.sqrt(t*t-1);return new r(Math.log(a-t),Math.PI)}return new r(e,0).asech()},Complex:function(e){return e.asech()},BigNumber:function(e){return new a(1).div(e).acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1$="asin",dependencies$1$=["typed","config","Complex"],createAsin=factory(name$1$,dependencies$1$,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1$,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.asin(e):new r(e,0).asin()},Complex:function(e){return e.asin()},BigNumber:function(e){return e.asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1_="asinh",dependencies$1_=["typed"],createAsinh=factory(name$1_,dependencies$1_,(e=>{var{typed:t}=e;return t("asinh",{number:asinhNumber,Complex:function(e){return e.asinh()},BigNumber:function(e){return e.asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Z="atan",dependencies$1Z=["typed"],createAtan=factory(name$1Z,dependencies$1Z,(e=>{var{typed:t}=e;return t("atan",{number:function(e){return Math.atan(e)},Complex:function(e){return e.atan()},BigNumber:function(e){return e.atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Y="atan2",dependencies$1Y=["typed","matrix","equalScalar","BigNumber","DenseMatrix"],createAtan2=factory(name$1Y,dependencies$1Y,(e=>{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm03({typed:t}),l=createAlgorithm09({typed:t,equalScalar:r}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$1Y,{"number, number":Math.atan2,"BigNumber, BigNumber":function(e,t){return a.atan2(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return c(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return d(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})})),name$1X="atanh",dependencies$1X=["typed","config","Complex"],createAtanh=factory(name$1X,dependencies$1X,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1X,{number:function(e){return e<=1&&e>=-1||n.predictable?atanhNumber(e):new r(e,0).atanh()},Complex:function(e){return e.atanh()},BigNumber:function(e){return e.atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1W="cos",dependencies$1W=["typed"],createCos=factory(name$1W,dependencies$1W,(e=>{var{typed:t}=e;return t(name$1W,{number:Math.cos,Complex:function(e){return e.cos()},BigNumber:function(e){return e.cos()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cos is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1V="cosh",dependencies$1V=["typed"],createCosh=factory(name$1V,dependencies$1V,(e=>{var{typed:t}=e;return t(name$1V,{number:cosh$3,Complex:function(e){return e.cosh()},BigNumber:function(e){return e.cosh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cosh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1U="cot",dependencies$1U=["typed","BigNumber"],createCot=factory(name$1U,dependencies$1U,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1U,{number:cotNumber,Complex:function(e){return e.cot()},BigNumber:function(e){return new n(1).div(e.tan())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cot is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1T="coth",dependencies$1T=["typed","BigNumber"],createCoth=factory(name$1T,dependencies$1T,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1T,{number:cothNumber,Complex:function(e){return e.coth()},BigNumber:function(e){return new n(1).div(e.tanh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function coth is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1S="csc",dependencies$1S=["typed","BigNumber"],createCsc=factory(name$1S,dependencies$1S,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1S,{number:cscNumber,Complex:function(e){return e.csc()},BigNumber:function(e){return new n(1).div(e.sin())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csc is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1R="csch",dependencies$1R=["typed","BigNumber"],createCsch=factory(name$1R,dependencies$1R,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1R,{number:cschNumber,Complex:function(e){return e.csch()},BigNumber:function(e){return new n(1).div(e.sinh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csch is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Q="sec",dependencies$1Q=["typed","BigNumber"],createSec=factory(name$1Q,dependencies$1Q,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1Q,{number:secNumber,Complex:function(e){return e.sec()},BigNumber:function(e){return new n(1).div(e.cos())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sec is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1P="sech",dependencies$1P=["typed","BigNumber"],createSech=factory(name$1P,dependencies$1P,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1P,{number:sechNumber,Complex:function(e){return e.sech()},BigNumber:function(e){return new n(1).div(e.cosh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sech is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1O="sin",dependencies$1O=["typed"],createSin=factory(name$1O,dependencies$1O,(e=>{var{typed:t}=e;return t(name$1O,{number:Math.sin,Complex:function(e){return e.sin()},BigNumber:function(e){return e.sin()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sin is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1N="sinh",dependencies$1N=["typed"],createSinh=factory(name$1N,dependencies$1N,(e=>{var{typed:t}=e;return t(name$1N,{number:sinhNumber,Complex:function(e){return e.sinh()},BigNumber:function(e){return e.sinh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sinh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1M="tan",dependencies$1M=["typed"],createTan=factory(name$1M,dependencies$1M,(e=>{var{typed:t}=e;return t(name$1M,{number:Math.tan,Complex:function(e){return e.tan()},BigNumber:function(e){return e.tan()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tan is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1L="tanh",dependencies$1L=["typed"],createTanh=factory(name$1L,dependencies$1L,(e=>{var{typed:t}=e;return t("tanh",{number:tanh$3,Complex:function(e){return e.tanh()},BigNumber:function(e){return e.tanh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tanh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1K="setCartesian",dependencies$1K=["typed","size","subset","compareNatural","Index","DenseMatrix"],createSetCartesian=factory(name$1K,dependencies$1K,(e=>{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1K,{"Array | Matrix, Array | Matrix":function(e,t){var o=[];if(0!==r(n(e),new i(0))&&0!==r(n(t),new i(0))){var l=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),u=flatten$4(Array.isArray(t)?t:t.toArray()).sort(a);o=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1J,{"Array | Matrix, Array | Matrix":function(e,t){var o;if(0===r(n(e),new i(0)))o=[];else{if(0===r(n(t),new i(0)))return flatten$4(e.toArray());var l,u=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),c=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));o=[];for(var p=0;p{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1I,{"Array | Matrix":function(e){var t;if(0===r(n(e),new i(0)))t=[];else{var o=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a);(t=[]).push(o[0]);for(var l=1;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1H,{"Array | Matrix, Array | Matrix":function(e,t){var o;if(0===r(n(e),new i(0))||0===r(n(t),new i(0)))o=[];else{var l=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),u=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));o=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1G,{"Array | Matrix, Array | Matrix":function(e,t){if(0===r(n(e),new i(0)))return!0;if(0===r(n(t),new i(0)))return!1;for(var s,o=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),l=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a)),u=0;u{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1F,{"number | BigNumber | Fraction | Complex, Array | Matrix":function(e,t){if(0===r(n(t),new i(0)))return 0;for(var s=flatten$4(Array.isArray(t)?t:t.toArray()),o=0,l=0;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1E,{"Array | Matrix":function(e){if(0===r(n(e),new i(0)))return[];for(var t=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),o=[],l=0;l.toString(2).length<=t.length;)o.push(s(t,l.toString(2).split("").reverse())),l++;return function(e){for(var t=[],n=e.length-1;n>0;n--)for(var r=0;re[r+1].length&&(t=e[r],e[r]=e[r+1],e[r+1]=t);return e}(o)}});function s(e,t){for(var n=[],r=0;r{var{typed:t,compareNatural:n}=e;return t(name$1D,{"Array | Matrix":function(e){return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length},"Array | Matrix, boolean":function(e,t){if(!1===t||0===e.length)return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length;for(var r=flatten$4(Array.isArray(e)?e:e.toArray()).sort(n),a=1,i=1;i{var{typed:t,size:n,concat:r,subset:a,setDifference:i,Index:s}=e;return t(name$1C,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new s(0)))return flatten$4(t);if(0===a(n(t),new s(0)))return flatten$4(e);var o=flatten$4(e),l=flatten$4(t);return r(i(o,l),i(l,o))}})})),name$1B="setUnion",dependencies$1B=["typed","size","concat","subset","setIntersect","setSymDifference","Index"],createSetUnion=factory(name$1B,dependencies$1B,(e=>{var{typed:t,size:n,concat:r,subset:a,setIntersect:i,setSymDifference:s,Index:o}=e;return t(name$1B,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new o(0)))return flatten$4(t);if(0===a(n(t),new o(0)))return flatten$4(e);var l=flatten$4(e),u=flatten$4(t);return r(s(l,u),i(l,u))}})})),name$1A="add",dependencies$1A=["typed","matrix","addScalar","equalScalar","DenseMatrix","SparseMatrix"],createAdd=factory(name$1A,dependencies$1A,(e=>{var{typed:t,matrix:n,addScalar:r,equalScalar:a,DenseMatrix:i,SparseMatrix:s}=e,o=createAlgorithm01({typed:t}),l=createAlgorithm04({typed:t,equalScalar:a}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$1A,extend$2({"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,r)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,r,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,r,!0)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return p(e,t,r,!1)},"SparseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, DenseMatrix":function(e,t){return p(t,e,r,!0)},"any, SparseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return p(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,r,!0).valueOf()},"any, any":r,"any, any, ...any":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,abs:n,addScalar:r,divideScalar:a,multiplyScalar:i,sqrt:s,smaller:o,isPositive:l}=e;return t(name$1z,{"... number | BigNumber":function(e){for(var t=0,u=0,c=0;c{var{typed:t,abs:n,add:r,pow:a,conj:i,sqrt:s,multiply:o,equalScalar:l,larger:u,smaller:c,matrix:p,ctranspose:d,eigs:m}=e;return t(name$1y,{number:Math.abs,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},boolean:function(e){return Math.abs(e)},Array:function(e){return y(p(e),2)},Matrix:function(e){return y(e,2)},"number | Complex | BigNumber | boolean, number | BigNumber | string":function(e){return this(e)},"Array, number | BigNumber | string":function(e,t){return y(p(e),t)},"Matrix, number | BigNumber | string":function(e,t){return y(e,t)}});function h(e,t){if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=0;return e.forEach((function(e){var r=n(e);u(r,t)&&(t=r)}),!0),t}(e);if(t===Number.NEGATIVE_INFINITY||"-inf"===t)return function(e){var t;return e.forEach((function(e){var r=n(e);t&&!c(r,t)||(t=r)}),!0),t||0}(e);if("fro"===t)return y(e,2);if("number"==typeof t&&!isNaN(t)){if(!l(t,0)){var i=0;return e.forEach((function(e){i=r(a(n(e),t),i)}),!0),a(i,1/t)}return Number.POSITIVE_INFINITY}throw new Error("Unsupported parameter value")}function f(e,t){if(1===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var s=i[1],o=r(t[s]||0,n(e));u(o,a)&&(a=o),t[s]=o}),!0),a}(e);if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var s=i[0],o=r(t[s]||0,n(e));u(o,a)&&(a=o),t[s]=o}),!0),a}(e);if("fro"===t)return function(e){var t=0;return e.forEach((function(e,n){t=r(t,o(e,i(e)))})),n(s(t))}(e);if(2===t)return function(e){var t=e.size();if(t[0]!==t[1])throw new RangeError("Invalid matrix dimensions");var r=d(e),a=o(r,e),i=m(a).values.toArray(),l=i[i.length-1];return n(s(l))}(e);throw new Error("Unsupported parameter value "+t)}function y(e,t){var n=e.size();if(1===n.length)return h(e,t);if(2===n.length){if(n[0]&&n[1])return f(e,t);throw new RangeError("Invalid matrix dimensions")}}})),name$1x="dot",dependencies$1x=["typed","addScalar","multiplyScalar","conj","size"],createDot=factory(name$1x,dependencies$1x,(e=>{var{typed:t,addScalar:n,multiplyScalar:r,conj:a,size:i}=e;return t(name$1x,{"Array | DenseMatrix, Array | DenseMatrix":function(e,i){var l=s(e,i),u=isMatrix(e)?e._data:e,c=isMatrix(e)?e._datatype:void 0,p=isMatrix(i)?i._data:i,d=isMatrix(i)?i._datatype:void 0,m=2===o(e).length,h=2===o(i).length,f=n,y=r;if(c&&d&&c===d&&"string"==typeof c){var g=c;f=t.find(n,[g,g]),y=t.find(r,[g,g])}if(!m&&!h){for(var b=y(a(u[0]),p[0]),v=1;vf?m++:h===f&&(u=c(u,p(i[d],l[m])),d++,m++)}return u}});function s(e,t){var n,r,a=o(e),i=o(t);if(1===a.length)n=a[0];else{if(2!==a.length||1!==a[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+a.join(", ")+")");n=a[0]}if(1===i.length)r=i[0];else{if(2!==i.length||1!==i[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+i.join(", ")+")");r=i[0]}if(n!==r)throw new RangeError("Vectors must have equal length ("+n+" != "+r+")");if(0===n)throw new RangeError("Cannot calculate the dot product of empty vectors");return n}function o(e){return isMatrix(e)?e.size():i(e)}})),name$1w="trace",dependencies$1w=["typed","matrix","add"],createTrace=factory(name$1w,dependencies$1w,(e=>{var{typed:t,matrix:n,add:r}=e;return t("trace",{Array:function(e){return a(n(e))},SparseMatrix:function(e){var t=e._values,n=e._index,a=e._ptr,i=e._size,s=i[0],o=i[1];if(s===o){var l=0;if(t.length>0)for(var u=0;uu)break}return l}throw new RangeError("Matrix must be square (size: "+format$1(i)+")")},DenseMatrix:a,any:clone$3});function a(e){var t=e._size,n=e._data;switch(t.length){case 1:if(1===t[0])return clone$3(n[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0];if(a===t[1]){for(var i=0,s=0;s{var{typed:t,Index:n}=e;return t(name$1v,{"...number | string | BigNumber | Range | Array | Matrix":function(e){var t=e.map((function(e){return isBigNumber(e)?e.toNumber():Array.isArray(e)||isMatrix(e)?e.map((function(e){return isBigNumber(e)?e.toNumber():e})):e})),r=new n;return n.apply(r,t),r}})})),keywords=new Set(["end"]),name$1u="Node",dependencies$1u=["mathWithTransform"],createNode=factory(name$1u,dependencies$1u,(e=>{var{mathWithTransform:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator")}return n.prototype.evaluate=function(e){return this.compile().evaluate(e)},n.prototype.type="Node",n.prototype.isNode=!0,n.prototype.comment="",n.prototype.compile=function(){var e=this._compile(t,{}),n={};return{evaluate:function(t){var r=createMap$1(t);return function(e){for(var t of[...keywords])if(e.has(t))throw new Error('Scope contains an illegal symbol, "'+t+'" is a reserved keyword')}(r),e(r,n,null)}}},n.prototype._compile=function(e,t){throw new Error("Method _compile should be implemented by type "+this.type)},n.prototype.forEach=function(e){throw new Error("Cannot run forEach on a Node interface")},n.prototype.map=function(e){throw new Error("Cannot run map on a Node interface")},n.prototype._ifNode=function(e){if(!isNode(e))throw new TypeError("Callback function must return a Node");return e},n.prototype.traverse=function(e){e(this,null,null),function e(t,n){t.forEach((function(t,r,a){n(t,r,a),e(t,n)}))}(this,e)},n.prototype.transform=function(e){return function t(n,r,a){var i=e(n,r,a);return i!==n?i:n.map(t)}(this,null,null)},n.prototype.filter=function(e){var t=[];return this.traverse((function(n,r,a){e(n,r,a)&&t.push(n)})),t},n.prototype.clone=function(){throw new Error("Cannot clone a Node interface")},n.prototype.cloneDeep=function(){return this.map((function(e){return e.cloneDeep()}))},n.prototype.equals=function(e){return!!e&&deepStrictEqual(this,e)},n.prototype.toString=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toString(e)},n.prototype.toJSON=function(){throw new Error("Cannot serialize object: toJSON not implemented by "+this.type)},n.prototype.toHTML=function(e){var t=this._getCustomString(e);return void 0!==t?t:this.toHTML(e)},n.prototype._toString=function(){throw new Error("_toString not implemented for "+this.type)},n.prototype.toTex=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toTex(e)},n.prototype._toTex=function(e){throw new Error("_toTex not implemented for "+this.type)},n.prototype._getCustomString=function(e){if(e&&"object"==typeof e)switch(typeof e.handler){case"object":case"undefined":return;case"function":return e.handler(this,e);default:throw new TypeError("Object or function expected as callback")}},n.prototype.getIdentifier=function(){return this.type},n.prototype.getContent=function(){return this},n}),{isClass:!0,isNode:!0});function errorTransform(e){return e&&e.isIndexError?new IndexError(e.index+1,e.min+1,void 0!==e.max?e.max+1:void 0):e}function accessFactory(e){var{subset:t}=e;return function(e,n){try{if(Array.isArray(e))return t(e,n);if(e&&"function"==typeof e.subset)return e.subset(n);if("string"==typeof e)return t(e,n);if("object"==typeof e){if(!n.isObjectProperty())throw new TypeError("Cannot apply a numeric index as object property");return getSafeProperty(e,n.getObjectProperty())}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var name$1t="AccessorNode",dependencies$1t=["subset","Node"],createAccessorNode=factory(name$1t,dependencies$1t,(e=>{var{subset:t,Node:n}=e,r=accessFactory({subset:t});function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "object"');if(!isIndexNode(t))throw new TypeError('IndexNode expected for parameter "index"');this.object=e||null,this.index=t,Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function i(e){return!(isAccessorNode(e)||isArrayNode(e)||isConstantNode(e)||isFunctionNode(e)||isObjectNode(e)||isParenthesisNode(e)||isSymbolNode(e))}return a.prototype=new n,a.prototype.type="AccessorNode",a.prototype.isAccessorNode=!0,a.prototype._compile=function(e,t){var n=this.object._compile(e,t),a=this.index._compile(e,t);if(this.index.isObjectProperty()){var i=this.index.getObjectProperty();return function(e,t,r){return getSafeProperty(n(e,t,r),i)}}return function(e,t,i){var s=n(e,t,i),o=a(e,t,s);return r(s,o)}},a.prototype.forEach=function(e){e(this.object,"object",this),e(this.index,"index",this)},a.prototype.map=function(e){return new a(this._ifNode(e(this.object,"object",this)),this._ifNode(e(this.index,"index",this)))},a.prototype.clone=function(){return new a(this.object,this.index)},a.prototype._toString=function(e){var t=this.object.toString(e);return i(this.object)&&(t="("+t+")"),t+this.index.toString(e)},a.prototype.toHTML=function(e){var t=this.object.toHTML(e);return i(this.object)&&(t='('+t+')'),t+this.index.toHTML(e)},a.prototype._toTex=function(e){var t=this.object.toTex(e);return i(this.object)&&(t="\\left(' + object + '\\right)"),t+this.index.toTex(e)},a.prototype.toJSON=function(){return{mathjs:"AccessorNode",object:this.object,index:this.index}},a.fromJSON=function(e){return new a(e.object,e.index)},a}),{isClass:!0,isNode:!0}),name$1s="ArrayNode",dependencies$1s=["Node"],createArrayNode=factory(name$1s,dependencies$1s,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.items=e||[],!Array.isArray(this.items)||!this.items.every(isNode))throw new TypeError("Array containing Nodes expected")}return n.prototype=new t,n.prototype.type="ArrayNode",n.prototype.isArrayNode=!0,n.prototype._compile=function(e,t){var n=map$2(this.items,(function(n){return n._compile(e,t)}));if("Array"!==e.config.matrix){var r=e.matrix;return function(e,t,a){return r(map$2(n,(function(n){return n(e,t,a)})))}}return function(e,t,r){return map$2(n,(function(n){return n(e,t,r)}))}},n.prototype.forEach=function(e){for(var t=0;t['+this.items.map((function(t){return t.toHTML(e)})).join(',')+']'},n.prototype._toTex=function(e){return function t(n,r){var a=n.some(isArrayNode)&&!n.every(isArrayNode),i=r||a,s=i?"&":"\\\\",o=n.map((function(n){return n.items?t(n.items,!r):n.toTex(e)})).join(s);return a||!i||i&&!r?"\\begin{bmatrix}"+o+"\\end{bmatrix}":o}(this.items,!1)},n}),{isClass:!0,isNode:!0});function assignFactory(e){var{subset:t,matrix:n}=e;return function(e,r,a){try{if(Array.isArray(e))return n(e).subset(r,a).valueOf();if(e&&"function"==typeof e.subset)return e.subset(r,a);if("string"==typeof e)return t(e,r,a);if("object"==typeof e){if(!r.isObjectProperty())throw TypeError("Cannot apply a numeric index as object property");return setSafeProperty(e,r.getObjectProperty(),a),e}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var properties=[{AssignmentNode:{},FunctionAssignmentNode:{}},{ConditionalNode:{latexLeftParens:!1,latexRightParens:!1,latexParens:!1}},{"OperatorNode:or":{associativity:"left",associativeWith:[]}},{"OperatorNode:xor":{associativity:"left",associativeWith:[]}},{"OperatorNode:and":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitOr":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitXor":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitAnd":{associativity:"left",associativeWith:[]}},{"OperatorNode:equal":{associativity:"left",associativeWith:[]},"OperatorNode:unequal":{associativity:"left",associativeWith:[]},"OperatorNode:smaller":{associativity:"left",associativeWith:[]},"OperatorNode:larger":{associativity:"left",associativeWith:[]},"OperatorNode:smallerEq":{associativity:"left",associativeWith:[]},"OperatorNode:largerEq":{associativity:"left",associativeWith:[]},RelationalNode:{associativity:"left",associativeWith:[]}},{"OperatorNode:leftShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightArithShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightLogShift":{associativity:"left",associativeWith:[]}},{"OperatorNode:to":{associativity:"left",associativeWith:[]}},{RangeNode:{}},{"OperatorNode:add":{associativity:"left",associativeWith:["OperatorNode:add","OperatorNode:subtract"]},"OperatorNode:subtract":{associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]},"OperatorNode:divide":{associativity:"left",associativeWith:[],latexLeftParens:!1,latexRightParens:!1,latexParens:!1},"OperatorNode:dotMultiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","OperatorNode:dotMultiply","OperatorNode:doDivide"]},"OperatorNode:dotDivide":{associativity:"left",associativeWith:[]},"OperatorNode:mod":{associativity:"left",associativeWith:[]}},{"OperatorNode:unaryPlus":{associativity:"right"},"OperatorNode:unaryMinus":{associativity:"right"},"OperatorNode:bitNot":{associativity:"right"},"OperatorNode:not":{associativity:"right"}},{"OperatorNode:pow":{associativity:"right",associativeWith:[],latexRightParens:!1},"OperatorNode:dotPow":{associativity:"right",associativeWith:[]}},{"OperatorNode:factorial":{associativity:"left"}},{"OperatorNode:transpose":{associativity:"left"}}];function getPrecedence(e,t){var n=e;"keep"!==t&&(n=e.getContent());for(var r=n.getIdentifier(),a=0;a{var{subset:t,matrix:n,Node:r}=e,a=accessFactory({subset:t}),i=assignFactory({subset:t,matrix:n});function s(e,t,n){if(!(this instanceof s))throw new SyntaxError("Constructor must be called with the new operator");if(this.object=e,this.index=n?t:null,this.value=n||t,!isSymbolNode(e)&&!isAccessorNode(e))throw new TypeError('SymbolNode or AccessorNode expected as "object"');if(isSymbolNode(e)&&"end"===e.name)throw new Error('Cannot assign to symbol "end"');if(this.index&&!isIndexNode(this.index))throw new TypeError('IndexNode expected as "index"');if(!isNode(this.value))throw new TypeError('Node expected as "value"');Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function o(e,t){t||(t="keep");var n=getPrecedence(e,t),r=getPrecedence(e.value,t);return"all"===t||null!==r&&r<=n}return s.prototype=new r,s.prototype.type="AssignmentNode",s.prototype.isAssignmentNode=!0,s.prototype._compile=function(e,t){var n=this.object._compile(e,t),r=this.index?this.index._compile(e,t):null,s=this.value._compile(e,t),o=this.object.name;if(this.index){if(this.index.isObjectProperty()){var l=this.index.getObjectProperty();return function(e,t,r){var a=n(e,t,r),i=s(e,t,r);return setSafeProperty(a,l,i),i}}if(isSymbolNode(this.object))return function(e,t,a){var l=n(e,t,a),u=s(e,t,a),c=r(e,t,l);return e.set(o,i(l,c,u)),u};var u=this.object.object._compile(e,t);if(this.object.index.isObjectProperty()){var c=this.object.index.getObjectProperty();return function(e,t,n){var a=u(e,t,n),o=getSafeProperty(a,c),l=r(e,t,o),p=s(e,t,n);return setSafeProperty(a,c,i(o,l,p)),p}}var p=this.object.index._compile(e,t);return function(e,t,n){var o=u(e,t,n),l=p(e,t,o),c=a(o,l),d=r(e,t,c),m=s(e,t,n);return i(o,l,i(c,d,m)),m}}if(!isSymbolNode(this.object))throw new TypeError("SymbolNode expected as object");return function(e,t,n){var r=s(e,t,n);return e.set(o,r),r}},s.prototype.forEach=function(e){e(this.object,"object",this),this.index&&e(this.index,"index",this),e(this.value,"value",this)},s.prototype.map=function(e){return new s(this._ifNode(e(this.object,"object",this)),this.index?this._ifNode(e(this.index,"index",this)):null,this._ifNode(e(this.value,"value",this)))},s.prototype.clone=function(){return new s(this.object,this.index,this.value)},s.prototype._toString=function(e){var t=this.object.toString(e),n=this.index?this.index.toString(e):"",r=this.value.toString(e);return o(this,e&&e.parenthesis)&&(r="("+r+")"),t+n+" = "+r},s.prototype.toJSON=function(){return{mathjs:"AssignmentNode",object:this.object,index:this.index,value:this.value}},s.fromJSON=function(e){return new s(e.object,e.index,e.value)},s.prototype.toHTML=function(e){var t=this.object.toHTML(e),n=this.index?this.index.toHTML(e):"",r=this.value.toHTML(e);return o(this,e&&e.parenthesis)&&(r='('+r+')'),t+n+'='+r},s.prototype._toTex=function(e){var t=this.object.toTex(e),n=this.index?this.index.toTex(e):"",r=this.value.toTex(e);return o(this,e&&e.parenthesis)&&(r="\\left(".concat(r,"\\right)")),t+n+":="+r},s}),{isClass:!0,isNode:!0}),name$1q="BlockNode",dependencies$1q=["ResultSet","Node"],createBlockNode=factory(name$1q,dependencies$1q,(e=>{var{ResultSet:t,Node:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new Error("Array expected");this.blocks=e.map((function(e){var t=e&&e.node,n=!e||void 0===e.visible||e.visible;if(!isNode(t))throw new TypeError('Property "node" must be a Node');if("boolean"!=typeof n)throw new TypeError('Property "visible" must be a boolean');return{node:t,visible:n}}))}return r.prototype=new n,r.prototype.type="BlockNode",r.prototype.isBlockNode=!0,r.prototype._compile=function(e,n){var r=map$2(this.blocks,(function(t){return{evaluate:t.node._compile(e,n),visible:t.visible}}));return function(e,n,a){var i=[];return forEach$1(r,(function(t){var r=t.evaluate(e,n,a);t.visible&&i.push(r)})),new t(i)}},r.prototype.forEach=function(e){for(var t=0;t;')})).join('
')},r.prototype._toTex=function(e){return this.blocks.map((function(t){return t.node.toTex(e)+(t.visible?"":";")})).join("\\;\\;\n")},r}),{isClass:!0,isNode:!0}),name$1p="ConditionalNode",dependencies$1p=["Node"],createConditionalNode=factory(name$1p,dependencies$1p,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Parameter condition must be a Node");if(!isNode(t))throw new TypeError("Parameter trueExpr must be a Node");if(!isNode(r))throw new TypeError("Parameter falseExpr must be a Node");this.condition=e,this.trueExpr=t,this.falseExpr=r}return n.prototype=new t,n.prototype.type="ConditionalNode",n.prototype.isConditionalNode=!0,n.prototype._compile=function(e,t){var n=this.condition._compile(e,t),r=this.trueExpr._compile(e,t),a=this.falseExpr._compile(e,t);return function(e,t,i){return function(e){if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return!!e;if(e){if(isBigNumber(e))return!e.isZero();if(isComplex(e))return!(!e.re&&!e.im);if(isUnit(e))return!!e.value}if(null==e)return!1;throw new TypeError('Unsupported type of condition "'+typeOf$1(e)+'"')}(n(e,t,i))?r(e,t,i):a(e,t,i)}},n.prototype.forEach=function(e){e(this.condition,"condition",this),e(this.trueExpr,"trueExpr",this),e(this.falseExpr,"falseExpr",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.condition,"condition",this)),this._ifNode(e(this.trueExpr,"trueExpr",this)),this._ifNode(e(this.falseExpr,"falseExpr",this)))},n.prototype.clone=function(){return new n(this.condition,this.trueExpr,this.falseExpr)},n.prototype._toString=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toString(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r="("+r+")");var i=this.trueExpr.toString(e),s=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==s&&s<=n)&&(i="("+i+")");var o=this.falseExpr.toString(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(o="("+o+")"),r+" ? "+i+" : "+o},n.prototype.toJSON=function(){return{mathjs:"ConditionalNode",condition:this.condition,trueExpr:this.trueExpr,falseExpr:this.falseExpr}},n.fromJSON=function(e){return new n(e.condition,e.trueExpr,e.falseExpr)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toHTML(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r='('+r+')');var i=this.trueExpr.toHTML(e),s=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==s&&s<=n)&&(i='('+i+')');var o=this.falseExpr.toHTML(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(o='('+o+')'),r+'?'+i+':'+o},n.prototype._toTex=function(e){return"\\begin{cases} {"+this.trueExpr.toTex(e)+"}, &\\quad{\\text{if }\\;"+this.condition.toTex(e)+"}\\\\{"+this.falseExpr.toTex(e)+"}, &\\quad{\\text{otherwise}}\\end{cases}"},n}),{isClass:!0,isNode:!0}),_extends=Object.assign||function(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},n=t.preserveFormatting,r=void 0!==n&&n,a=t.escapeMapFn,i=void 0===a?defaultEscapeMapFn:a,s=String(e),o="",l=i(_extends({},defaultEscapes),r?_extends({},formatEscapes):{}),u=Object.keys(l),c=function(){var e=!1;u.forEach((function(t,n){e||s.length>=t.length&&s.slice(0,t.length)===t&&(o+=l[u[n]],s=s.slice(t.length,s.length),e=!0)})),e||(o+=s.slice(0,1),s=s.slice(1,s.length))};s;)c();return o},latexSymbols={Alpha:"A",alpha:"\\alpha",Beta:"B",beta:"\\beta",Gamma:"\\Gamma",gamma:"\\gamma",Delta:"\\Delta",delta:"\\delta",Epsilon:"E",epsilon:"\\epsilon",varepsilon:"\\varepsilon",Zeta:"Z",zeta:"\\zeta",Eta:"H",eta:"\\eta",Theta:"\\Theta",theta:"\\theta",vartheta:"\\vartheta",Iota:"I",iota:"\\iota",Kappa:"K",kappa:"\\kappa",varkappa:"\\varkappa",Lambda:"\\Lambda",lambda:"\\lambda",Mu:"M",mu:"\\mu",Nu:"N",nu:"\\nu",Xi:"\\Xi",xi:"\\xi",Omicron:"O",omicron:"o",Pi:"\\Pi",pi:"\\pi",varpi:"\\varpi",Rho:"P",rho:"\\rho",varrho:"\\varrho",Sigma:"\\Sigma",sigma:"\\sigma",varsigma:"\\varsigma",Tau:"T",tau:"\\tau",Upsilon:"\\Upsilon",upsilon:"\\upsilon",Phi:"\\Phi",phi:"\\phi",varphi:"\\varphi",Chi:"X",chi:"\\chi",Psi:"\\Psi",psi:"\\psi",Omega:"\\Omega",omega:"\\omega",true:"\\mathrm{True}",false:"\\mathrm{False}",i:"i",inf:"\\infty",Inf:"\\infty",infinity:"\\infty",Infinity:"\\infty",oo:"\\infty",lim:"\\lim",undefined:"\\mathbf{?}"},latexOperators={transpose:"^\\top",ctranspose:"^H",factorial:"!",pow:"^",dotPow:".^\\wedge",unaryPlus:"+",unaryMinus:"-",bitNot:"\\~",not:"\\neg",multiply:"\\cdot",divide:"\\frac",dotMultiply:".\\cdot",dotDivide:".:",mod:"\\mod",add:"+",subtract:"-",to:"\\rightarrow",leftShift:"<<",rightArithShift:">>",rightLogShift:">>>",equal:"=",unequal:"\\neq",smaller:"<",larger:">",smallerEq:"\\leq",largerEq:"\\geq",bitAnd:"\\&",bitXor:"\\underline{|}",bitOr:"|",and:"\\wedge",xor:"\\veebar",or:"\\vee"},latexFunctions={abs:{1:"\\left|${args[0]}\\right|"},add:{2:"\\left(${args[0]}".concat(latexOperators.add,"${args[1]}\\right)")},cbrt:{1:"\\sqrt[3]{${args[0]}}"},ceil:{1:"\\left\\lceil${args[0]}\\right\\rceil"},cube:{1:"\\left(${args[0]}\\right)^3"},divide:{2:"\\frac{${args[0]}}{${args[1]}}"},dotDivide:{2:"\\left(${args[0]}".concat(latexOperators.dotDivide,"${args[1]}\\right)")},dotMultiply:{2:"\\left(${args[0]}".concat(latexOperators.dotMultiply,"${args[1]}\\right)")},dotPow:{2:"\\left(${args[0]}".concat(latexOperators.dotPow,"${args[1]}\\right)")},exp:{1:"\\exp\\left(${args[0]}\\right)"},expm1:"\\left(e".concat(latexOperators.pow,"{${args[0]}}-1\\right)"),fix:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},floor:{1:"\\left\\lfloor${args[0]}\\right\\rfloor"},gcd:"\\gcd\\left(${args}\\right)",hypot:"\\hypot\\left(${args}\\right)",log:{1:"\\ln\\left(${args[0]}\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}\\right)"},log10:{1:"\\log_{10}\\left(${args[0]}\\right)"},log1p:{1:"\\ln\\left(${args[0]}+1\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}+1\\right)"},log2:"\\log_{2}\\left(${args[0]}\\right)",mod:{2:"\\left(${args[0]}".concat(latexOperators.mod,"${args[1]}\\right)")},multiply:{2:"\\left(${args[0]}".concat(latexOperators.multiply,"${args[1]}\\right)")},norm:{1:"\\left\\|${args[0]}\\right\\|",2:void 0},nthRoot:{2:"\\sqrt[${args[1]}]{${args[0]}}"},nthRoots:{2:"\\{y : $y^{args[1]} = {${args[0]}}\\}"},pow:{2:"\\left(${args[0]}\\right)".concat(latexOperators.pow,"{${args[1]}}")},round:{1:"\\left\\lfloor${args[0]}\\right\\rceil",2:void 0},sign:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},sqrt:{1:"\\sqrt{${args[0]}}"},square:{1:"\\left(${args[0]}\\right)^2"},subtract:{2:"\\left(${args[0]}".concat(latexOperators.subtract,"${args[1]}\\right)")},unaryMinus:{1:"".concat(latexOperators.unaryMinus,"\\left(${args[0]}\\right)")},unaryPlus:{1:"".concat(latexOperators.unaryPlus,"\\left(${args[0]}\\right)")},bitAnd:{2:"\\left(${args[0]}".concat(latexOperators.bitAnd,"${args[1]}\\right)")},bitNot:{1:latexOperators.bitNot+"\\left(${args[0]}\\right)"},bitOr:{2:"\\left(${args[0]}".concat(latexOperators.bitOr,"${args[1]}\\right)")},bitXor:{2:"\\left(${args[0]}".concat(latexOperators.bitXor,"${args[1]}\\right)")},leftShift:{2:"\\left(${args[0]}".concat(latexOperators.leftShift,"${args[1]}\\right)")},rightArithShift:{2:"\\left(${args[0]}".concat(latexOperators.rightArithShift,"${args[1]}\\right)")},rightLogShift:{2:"\\left(${args[0]}".concat(latexOperators.rightLogShift,"${args[1]}\\right)")},bellNumbers:{1:"\\mathrm{B}_{${args[0]}}"},catalan:{1:"\\mathrm{C}_{${args[0]}}"},stirlingS2:{2:"\\mathrm{S}\\left(${args}\\right)"},arg:{1:"\\arg\\left(${args[0]}\\right)"},conj:{1:"\\left(${args[0]}\\right)^*"},im:{1:"\\Im\\left\\lbrace${args[0]}\\right\\rbrace"},re:{1:"\\Re\\left\\lbrace${args[0]}\\right\\rbrace"},and:{2:"\\left(${args[0]}".concat(latexOperators.and,"${args[1]}\\right)")},not:{1:latexOperators.not+"\\left(${args[0]}\\right)"},or:{2:"\\left(${args[0]}".concat(latexOperators.or,"${args[1]}\\right)")},xor:{2:"\\left(${args[0]}".concat(latexOperators.xor,"${args[1]}\\right)")},cross:{2:"\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)"},ctranspose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.ctranspose)},det:{1:"\\det\\left(${args[0]}\\right)"},dot:{2:"\\left(${args[0]}\\cdot${args[1]}\\right)"},expm:{1:"\\exp\\left(${args[0]}\\right)"},inv:{1:"\\left(${args[0]}\\right)^{-1}"},pinv:{1:"\\left(${args[0]}\\right)^{+}"},sqrtm:{1:"{${args[0]}}".concat(latexOperators.pow,"{\\frac{1}{2}}")},trace:{1:"\\mathrm{tr}\\left(${args[0]}\\right)"},transpose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.transpose)},combinations:{2:"\\binom{${args[0]}}{${args[1]}}"},combinationsWithRep:{2:"\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)"},factorial:{1:"\\left(${args[0]}\\right)".concat(latexOperators.factorial)},gamma:{1:"\\Gamma\\left(${args[0]}\\right)"},lgamma:{1:"\\ln\\Gamma\\left(${args[0]}\\right)"},equal:{2:"\\left(${args[0]}".concat(latexOperators.equal,"${args[1]}\\right)")},larger:{2:"\\left(${args[0]}".concat(latexOperators.larger,"${args[1]}\\right)")},largerEq:{2:"\\left(${args[0]}".concat(latexOperators.largerEq,"${args[1]}\\right)")},smaller:{2:"\\left(${args[0]}".concat(latexOperators.smaller,"${args[1]}\\right)")},smallerEq:{2:"\\left(${args[0]}".concat(latexOperators.smallerEq,"${args[1]}\\right)")},unequal:{2:"\\left(${args[0]}".concat(latexOperators.unequal,"${args[1]}\\right)")},erf:{1:"erf\\left(${args[0]}\\right)"},max:"\\max\\left(${args}\\right)",min:"\\min\\left(${args}\\right)",variance:"\\mathrm{Var}\\left(${args}\\right)",acos:{1:"\\cos^{-1}\\left(${args[0]}\\right)"},acosh:{1:"\\cosh^{-1}\\left(${args[0]}\\right)"},acot:{1:"\\cot^{-1}\\left(${args[0]}\\right)"},acoth:{1:"\\coth^{-1}\\left(${args[0]}\\right)"},acsc:{1:"\\csc^{-1}\\left(${args[0]}\\right)"},acsch:{1:"\\mathrm{csch}^{-1}\\left(${args[0]}\\right)"},asec:{1:"\\sec^{-1}\\left(${args[0]}\\right)"},asech:{1:"\\mathrm{sech}^{-1}\\left(${args[0]}\\right)"},asin:{1:"\\sin^{-1}\\left(${args[0]}\\right)"},asinh:{1:"\\sinh^{-1}\\left(${args[0]}\\right)"},atan:{1:"\\tan^{-1}\\left(${args[0]}\\right)"},atan2:{2:"\\mathrm{atan2}\\left(${args}\\right)"},atanh:{1:"\\tanh^{-1}\\left(${args[0]}\\right)"},cos:{1:"\\cos\\left(${args[0]}\\right)"},cosh:{1:"\\cosh\\left(${args[0]}\\right)"},cot:{1:"\\cot\\left(${args[0]}\\right)"},coth:{1:"\\coth\\left(${args[0]}\\right)"},csc:{1:"\\csc\\left(${args[0]}\\right)"},csch:{1:"\\mathrm{csch}\\left(${args[0]}\\right)"},sec:{1:"\\sec\\left(${args[0]}\\right)"},sech:{1:"\\mathrm{sech}\\left(${args[0]}\\right)"},sin:{1:"\\sin\\left(${args[0]}\\right)"},sinh:{1:"\\sinh\\left(${args[0]}\\right)"},tan:{1:"\\tan\\left(${args[0]}\\right)"},tanh:{1:"\\tanh\\left(${args[0]}\\right)"},to:{2:"\\left(${args[0]}".concat(latexOperators.to,"${args[1]}\\right)")},numeric:function(e,t){return e.args[0].toTex()},number:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"},string:{0:'\\mathtt{""}',1:"\\mathrm{string}\\left(${args[0]}\\right)"},bignumber:{0:"0",1:"\\left(${args[0]}\\right)"},complex:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i,"\\cdot\\left(${args[1]}\\right)\\right)")},matrix:{0:"\\begin{bmatrix}\\end{bmatrix}",1:"\\left(${args[0]}\\right)",2:"\\left(${args[0]}\\right)"},sparse:{0:"\\begin{bsparse}\\end{bsparse}",1:"\\left(${args[0]}\\right)"},unit:{1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"}},defaultTemplate="\\mathrm{${name}}\\left(${args}\\right)",latexUnits={deg:"^\\circ"};function escapeLatex(e){return dist(e,{preserveFormatting:!0})}function toSymbol(e,t){return(t=void 0!==t&&t)?hasOwnProperty$2(latexUnits,e)?latexUnits[e]:"\\mathrm{"+escapeLatex(e)+"}":hasOwnProperty$2(latexSymbols,e)?latexSymbols[e]:escapeLatex(e)}var name$1o="ConstantNode",dependencies$1o=["Node"],createConstantNode=factory(name$1o,dependencies$1o,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this.value=e}return n.prototype=new t,n.prototype.type="ConstantNode",n.prototype.isConstantNode=!0,n.prototype._compile=function(e,t){var n=this.value;return function(){return n}},n.prototype.forEach=function(e){},n.prototype.map=function(e){return this.clone()},n.prototype.clone=function(){return new n(this.value)},n.prototype._toString=function(e){return format$1(this.value,e)},n.prototype.toHTML=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"number":case"BigNumber":case"Fraction":return''+t+"";case"string":return''+t+"";case"boolean":return''+t+"";case"null":return''+t+"";case"undefined":return''+t+"";default:return''+t+""}},n.prototype.toJSON=function(){return{mathjs:"ConstantNode",value:this.value}},n.fromJSON=function(e){return new n(e.value)},n.prototype._toTex=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"string":return"\\mathtt{"+escapeLatex(t)+"}";case"number":case"BigNumber":if(!isFinite(this.value))return this.value.valueOf()<0?"-\\infty":"\\infty";var n=t.toLowerCase().indexOf("e");return-1!==n?t.substring(0,n)+"\\cdot10^{"+t.substring(n+1)+"}":t;case"Fraction":return this.value.toLatex();default:return t}},n}),{isClass:!0,isNode:!0}),name$1n="FunctionAssignmentNode",dependencies$1n=["typed","Node"],createFunctionAssignmentNode=factory(name$1n,dependencies$1n,(e=>{var{typed:t,Node:n}=e;function r(e,t,n){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');if(!Array.isArray(t))throw new TypeError('Array containing strings or objects expected for parameter "params"');if(!isNode(n))throw new TypeError('Node expected for parameter "expr"');if(keywords.has(e))throw new Error('Illegal function name, "'+e+'" is a reserved keyword');this.name=e,this.params=t.map((function(e){return e&&e.name||e})),this.types=t.map((function(e){return e&&e.type||"any"})),this.expr=n}function a(e,t){var n=getPrecedence(e,t),r=getPrecedence(e.expr,t);return"all"===t||null!==r&&r<=n}return r.prototype=new n,r.prototype.type="FunctionAssignmentNode",r.prototype.isFunctionAssignmentNode=!0,r.prototype._compile=function(e,n){var r=Object.create(n);forEach$1(this.params,(function(e){r[e]=!0}));var a=this.expr._compile(e,r),i=this.name,s=this.params,o=join(this.types,","),l=i+"("+join(this.params,", ")+")";return function(e,n,r){var u={};u[o]=function(){for(var t=Object.create(n),i=0;i'+escape$1(this.params[r])+"");var i=this.expr.toHTML(e);return a(this,t)&&(i='('+i+')'),''+escape$1(this.name)+'('+n.join(',')+')='+i},r.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=this.expr.toTex(e);return a(this,t)&&(n="\\left(".concat(n,"\\right)")),"\\mathrm{"+this.name+"}\\left("+this.params.map(toSymbol).join(",")+"\\right):="+n},r}),{isClass:!0,isNode:!0}),name$1m="IndexNode",dependencies$1m=["Node","size"],createIndexNode=factory(name$1m,dependencies$1m,(e=>{var{Node:t,size:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(this.dimensions=e,this.dotNotation=t||!1,!Array.isArray(e)||!e.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "dimensions"');if(this.dotNotation&&!this.isObjectProperty())throw new Error("dotNotation only applicable for object properties")}return r.prototype=new t,r.prototype.type="IndexNode",r.prototype.isIndexNode=!0,r.prototype._compile=function(e,t){var r=map$2(this.dimensions,(function(r,a){if(r.filter((e=>e.isSymbolNode&&"end"===e.name)).length>0){var i=Object.create(t);i.end=!0;var s=r._compile(e,i);return function(e,t,r){if(!isMatrix(r)&&!isArray$1(r)&&!isString$1(r))throw new TypeError('Cannot resolve "end": context must be a Matrix, Array, or string but is '+typeOf$1(r));var i=n(r).valueOf(),o=Object.create(t);return o.end=i[a],s(e,o,r)}}return r._compile(e,t)})),a=getSafeProperty(e,"index");return function(e,t,n){var i=map$2(r,(function(r){return r(e,t,n)}));return a(...i)}},r.prototype.forEach=function(e){for(var t=0;t.'+escape$1(this.getObjectProperty())+"":'['+t.join(',')+']'},r.prototype._toTex=function(e){var t=this.dimensions.map((function(t){return t.toTex(e)}));return this.dotNotation?"."+this.getObjectProperty():"_{"+t.join(",")+"}"},r}),{isClass:!0,isNode:!0}),name$1l="ObjectNode",dependencies$1l=["Node"],createObjectNode=factory(name$1l,dependencies$1l,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.properties=e||{},e&&("object"!=typeof e||!Object.keys(e).every((function(t){return isNode(e[t])}))))throw new TypeError("Object containing Nodes expected")}return n.prototype=new t,n.prototype.type="ObjectNode",n.prototype.isObjectNode=!0,n.prototype._compile=function(e,t){var n={};for(var r in this.properties)if(hasOwnProperty$2(this.properties,r)){var a=stringify(r),i=JSON.parse(a);if(!isSafeProperty(this.properties,i))throw new Error('No access to property "'+i+'"');n[i]=this.properties[r]._compile(e,t)}return function(e,t,r){var a={};for(var i in n)hasOwnProperty$2(n,i)&&(a[i]=n[i](e,t,r));return a}},n.prototype.forEach=function(e){for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&e(this.properties[t],"properties["+stringify(t)+"]",this)},n.prototype.map=function(e){var t={};for(var r in this.properties)hasOwnProperty$2(this.properties,r)&&(t[r]=this._ifNode(e(this.properties[r],"properties["+stringify(r)+"]",this)));return new n(t)},n.prototype.clone=function(){var e={};for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&(e[t]=this.properties[t]);return new n(e)},n.prototype._toString=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(stringify(n)+": "+this.properties[n].toString(e));return"{"+t.join(", ")+"}"},n.prototype.toJSON=function(){return{mathjs:"ObjectNode",properties:this.properties}},n.fromJSON=function(e){return new n(e.properties)},n.prototype.toHTML=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(''+escape$1(n)+':'+this.properties[n].toHTML(e));return'{'+t.join(',')+'}'},n.prototype._toTex=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push("\\mathbf{"+n+":} & "+this.properties[n].toTex(e)+"\\\\");return"\\left\\{\\begin{array}{ll}".concat(t.join("\n"),"\\end{array}\\right\\}")},n}),{isClass:!0,isNode:!0}),name$1k="OperatorNode",dependencies$1k=["Node"],createOperatorNode=factory(name$1k,dependencies$1k,(e=>{var{Node:t}=e;function n(e,t,r,a,i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('string expected for parameter "op"');if("string"!=typeof t)throw new TypeError('string expected for parameter "fn"');if(!Array.isArray(r)||!r.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.implicit=!0===a,this.isPercentage=!0===i,this.op=e,this.fn=t,this.args=r||[]}function r(e,t,n,r,a){var i,s=getPrecedence(e,t),o=getAssociativity(e,t);if("all"===t||r.length>2&&"OperatorNode:add"!==e.getIdentifier()&&"OperatorNode:multiply"!==e.getIdentifier())return r.map((function(e){switch(e.getContent().type){case"ArrayNode":case"ConstantNode":case"SymbolNode":case"ParenthesisNode":return!1;default:return!0}}));switch(r.length){case 0:i=[];break;case 1:var l=getPrecedence(r[0],t);if(a&&null!==l){var u,c;if("keep"===t?(u=r[0].getIdentifier(),c=e.getIdentifier()):(u=r[0].getContent().getIdentifier(),c=e.getContent().getIdentifier()),!1===properties[s][c].latexLeftParens){i=[!1];break}if(!1===properties[l][u].latexParens){i=[!1];break}}if(null===l){i=[!1];break}if(l<=s){i=[!0];break}i=[!1];break;case 2:var p,d,m=getPrecedence(r[0],t),h=isAssociativeWith(e,r[0],t);p=null!==m&&(m===s&&"right"===o&&!h||m=2&&"OperatorNode:multiply"===e.getIdentifier()&&e.implicit&&"auto"===t&&"hide"===n&&(i=r.map((function(e,t){var n="ParenthesisNode"===e.getIdentifier();return!(!i[t]&&!n)}))),i}return n.prototype=new t,n.prototype.type="OperatorNode",n.prototype.isOperatorNode=!0,n.prototype._compile=function(e,t){if("string"!=typeof this.fn||!isSafeMethod(e,this.fn))throw e[this.fn]?new Error('No access to function "'+this.fn+'"'):new Error("Function "+this.fn+' missing in provided namespace "math"');var n=getSafeProperty(e,this.fn),r=map$2(this.args,(function(n){return n._compile(e,t)}));if(1===r.length){var a=r[0];return function(e,t,r){return n(a(e,t,r))}}if(2===r.length){var i=r[0],s=r[1];return function(e,t,r){return n(i(e,t,r),s(e,t,r))}}return function(e,t,a){return n.apply(null,map$2(r,(function(n){return n(e,t,a)})))}},n.prototype.forEach=function(e){for(var t=0;t2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var p=a.map((function(t,n){return t=t.toString(e),i[n]&&(t="("+t+")"),t}));return this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?p.join(" "):p.join(" "+this.op+" ")}return this.fn+"("+this.args.join(", ")+")"},n.prototype.toJSON=function(){return{mathjs:"OperatorNode",op:this.op,fn:this.fn,args:this.args,implicit:this.implicit,isPercentage:this.isPercentage}},n.fromJSON=function(e){return new n(e.op,e.fn,e.args,e.implicit,e.isPercentage)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!1);if(1===a.length){var s=getAssociativity(this,t),o=a[0].toHTML(e);return i[0]&&(o='('+o+')'),"right"===s?''+escape$1(this.op)+""+o:o+''+escape$1(this.op)+""}if(2===a.length){var l=a[0].toHTML(e),u=a[1].toHTML(e);return i[0]&&(l='('+l+')'),i[1]&&(u='('+u+')'),this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?l+''+u:l+''+escape$1(this.op)+""+u}var c=a.map((function(t,n){return t=t.toHTML(e),i[n]&&(t='('+t+')'),t}));return a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())?this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?c.join(''):c.join(''+escape$1(this.op)+""):''+escape$1(this.fn)+'('+c.join(',')+')'},n.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!0),s=latexOperators[this.fn];if(s=void 0===s?this.op:s,1===a.length){var o=getAssociativity(this,t),l=a[0].toTex(e);return i[0]&&(l="\\left(".concat(l,"\\right)")),"right"===o?s+l:l+s}if(2===a.length){var u=a[0],c=u.toTex(e);i[0]&&(c="\\left(".concat(c,"\\right)"));var p,d=a[1].toTex(e);switch(i[1]&&(d="\\left(".concat(d,"\\right)")),p="keep"===t?u.getIdentifier():u.getContent().getIdentifier(),this.getIdentifier()){case"OperatorNode:divide":return s+"{"+c+"}{"+d+"}";case"OperatorNode:pow":switch(c="{"+c+"}",d="{"+d+"}",p){case"ConditionalNode":case"OperatorNode:divide":c="\\left(".concat(c,"\\right)")}break;case"OperatorNode:multiply":if(this.implicit&&"hide"===n)return c+"~"+d}return c+s+d}if(a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var m=a.map((function(t,n){return t=t.toTex(e),i[n]&&(t="\\left(".concat(t,"\\right)")),t}));return"OperatorNode:multiply"===this.getIdentifier()&&this.implicit?m.join("~"):m.join(s)}return"\\mathrm{"+this.fn+"}\\left("+a.map((function(t){return t.toTex(e)})).join(",")+"\\right)"},n.prototype.getIdentifier=function(){return this.type+":"+this.fn},n}),{isClass:!0,isNode:!0}),name$1j="ParenthesisNode",dependencies$1j=["Node"],createParenthesisNode=factory(name$1j,dependencies$1j,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "content"');this.content=e}return n.prototype=new t,n.prototype.type="ParenthesisNode",n.prototype.isParenthesisNode=!0,n.prototype._compile=function(e,t){return this.content._compile(e,t)},n.prototype.getContent=function(){return this.content.getContent()},n.prototype.forEach=function(e){e(this.content,"content",this)},n.prototype.map=function(e){return new n(e(this.content,"content",this))},n.prototype.clone=function(){return new n(this.content)},n.prototype._toString=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"("+this.content.toString(e)+")":this.content.toString(e)},n.prototype.toJSON=function(){return{mathjs:"ParenthesisNode",content:this.content}},n.fromJSON=function(e){return new n(e.content)},n.prototype.toHTML=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?'('+this.content.toHTML(e)+')':this.content.toHTML(e)},n.prototype._toTex=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"\\left(".concat(this.content.toTex(e),"\\right)"):this.content.toTex(e)},n}),{isClass:!0,isNode:!0}),name$1i="RangeNode",dependencies$1i=["Node"],createRangeNode=factory(name$1i,dependencies$1i,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Node expected");if(!isNode(t))throw new TypeError("Node expected");if(r&&!isNode(r))throw new TypeError("Node expected");if(arguments.length>3)throw new Error("Too many arguments");this.start=e,this.end=t,this.step=r||null}function r(e,t){var n=getPrecedence(e,t),r={},a=getPrecedence(e.start,t);if(r.start=null!==a&&a<=n||"all"===t,e.step){var i=getPrecedence(e.step,t);r.step=null!==i&&i<=n||"all"===t}var s=getPrecedence(e.end,t);return r.end=null!==s&&s<=n||"all"===t,r}return n.prototype=new t,n.prototype.type="RangeNode",n.prototype.isRangeNode=!0,n.prototype.needsEnd=function(){return this.filter((function(e){return isSymbolNode(e)&&"end"===e.name})).length>0},n.prototype._compile=function(e,t){var n=e.range,r=this.start._compile(e,t),a=this.end._compile(e,t);if(this.step){var i=this.step._compile(e,t);return function(e,t,s){return n(r(e,t,s),a(e,t,s),i(e,t,s))}}return function(e,t,i){return n(r(e,t,i),a(e,t,i))}},n.prototype.forEach=function(e){e(this.start,"start",this),e(this.end,"end",this),this.step&&e(this.step,"step",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.start,"start",this)),this._ifNode(e(this.end,"end",this)),this.step&&this._ifNode(e(this.step,"step",this)))},n.prototype.clone=function(){return new n(this.start,this.end,this.step&&this.step)},n.prototype._toString=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toString(e);if(n.start&&(a="("+a+")"),t=a,this.step){var i=this.step.toString(e);n.step&&(i="("+i+")"),t+=":"+i}var s=this.end.toString(e);return n.end&&(s="("+s+")"),t+":"+s},n.prototype.toJSON=function(){return{mathjs:"RangeNode",start:this.start,end:this.end,step:this.step}},n.fromJSON=function(e){return new n(e.start,e.end,e.step)},n.prototype.toHTML=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toHTML(e);if(n.start&&(a='('+a+')'),t=a,this.step){var i=this.step.toHTML(e);n.step&&(i='('+i+')'),t+=':'+i}var s=this.end.toHTML(e);return n.end&&(s='('+s+')'),t+':'+s},n.prototype._toTex=function(e){var t=r(this,e&&e.parenthesis?e.parenthesis:"keep"),n=this.start.toTex(e);if(t.start&&(n="\\left(".concat(n,"\\right)")),this.step){var a=this.step.toTex(e);t.step&&(a="\\left(".concat(a,"\\right)")),n+=":"+a}var i=this.end.toTex(e);return t.end&&(i="\\left(".concat(i,"\\right)")),n+":"+i},n}),{isClass:!0,isNode:!0}),name$1h="RelationalNode",dependencies$1h=["Node"],createRelationalNode=factory(name$1h,dependencies$1h,(e=>{var{Node:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new TypeError("Parameter conditionals must be an array");if(!Array.isArray(t))throw new TypeError("Parameter params must be an array");if(e.length!==t.length-1)throw new TypeError("Parameter params must contain exactly one more element than parameter conditionals");this.conditionals=e,this.params=t}return n.prototype=new t,n.prototype.type="RelationalNode",n.prototype.isRelationalNode=!0,n.prototype._compile=function(e,t){var n=this,r=this.params.map((n=>n._compile(e,t)));return function(t,a,i){for(var s,o=r[0](t,a,i),l=0;le(t,"params["+n+"]",this)),this)},n.prototype.map=function(e){return new n(this.conditionals.slice(),this.params.map(((t,n)=>this._ifNode(e(t,"params["+n+"]",this))),this))},n.prototype.clone=function(){return new n(this.conditionals,this.params)},n.prototype._toString=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"("+r.toString(e)+")":r.toString(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],s=0;s('+r.toHTML(e)+')':r.toHTML(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],s=0;s'+escape$1(a[this.conditionals[s]])+""+r[s+1];return i},n.prototype._toTex=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"\\left("+r.toTex(e)+"\right)":r.toTex(e)})),a=r[0],i=0;i{var{math:t,Unit:n,Node:r}=e;function a(e){return!!n&&n.isValuelessUnit(e)}function i(e){if(!(this instanceof i))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');this.name=e}return i.prototype=new r,i.prototype.type="SymbolNode",i.prototype.isSymbolNode=!0,i.prototype._compile=function(e,t){var r=this.name;if(!0===t[r])return function(e,t,n){return t[r]};if(r in e)return function(t,n,a){return t.has(r)?t.get(r):getSafeProperty(e,r)};var s=a(r);return function(e,t,a){return e.has(r)?e.get(r):s?new n(null,r):i.onUndefinedSymbol(r)}},i.prototype.forEach=function(e){},i.prototype.map=function(e){return this.clone()},i.onUndefinedSymbol=function(e){throw new Error("Undefined symbol "+e)},i.prototype.clone=function(){return new i(this.name)},i.prototype._toString=function(e){return this.name},i.prototype.toHTML=function(e){var t=escape$1(this.name);return"true"===t||"false"===t?''+t+"":"i"===t?''+t+"":"Infinity"===t?''+t+"":"NaN"===t?''+t+"":"null"===t?''+t+"":"undefined"===t?''+t+"":''+t+""},i.prototype.toJSON=function(){return{mathjs:"SymbolNode",name:this.name}},i.fromJSON=function(e){return new i(e.name)},i.prototype._toTex=function(e){var n=!1;void 0===t[this.name]&&a(this.name)&&(n=!0);var r=toSymbol(this.name,n);return"\\"===r[0]?r:" "+r},i}),{isClass:!0,isNode:!0});function createSubScope(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{var{math:t,Node:n,SymbolNode:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if("string"==typeof e&&(e=new r(e)),!isNode(e))throw new TypeError('Node expected as parameter "fn"');if(!Array.isArray(t)||!t.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.fn=e,this.args=t||[],Object.defineProperty(this,"name",{get:function(){return this.fn.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}a.prototype=new n,a.prototype.type="FunctionNode",a.prototype.isFunctionNode=!0;var i=e=>format$1(e,{truncate:78});a.prototype._compile=function(e,t){if(!(this instanceof a))throw new TypeError("No valid FunctionNode");var n=this.args.map((n=>n._compile(e,t)));if(!isSymbolNode(this.fn)){if(isAccessorNode(this.fn)&&isIndexNode(this.fn.index)&&this.fn.index.isObjectProperty()){var r=this.fn.object._compile(e,t),s=this.fn.index.getObjectProperty(),o=this.args;return function(t,a,i){var l=r(t,a,i);if(validateSafeMethod(l,s),l[s]&&l[s].rawArgs)return l[s](o,e,createSubScope(t,a),t);var u=n.map((e=>e(t,a,i)));return l[s].apply(l,u)}}var l=this.fn.toString(),u=this.fn._compile(e,t),c=this.args;return function(t,r,a){var s=u(t,r,a);if("function"!=typeof s)throw new TypeError("Expression '".concat(l,"' did not evaluate to a function; value is:")+"\n ".concat(i(s)));if(s.rawArgs)return s(c,e,createSubScope(t,r),t);var o=n.map((e=>e(t,r,a)));return s.apply(s,o)}}var p=this.fn.name;if(t[p]){var d=this.args;return function(t,r,a){var s=r[p];if("function"!=typeof s)throw new TypeError("Argument '".concat(p,"' was not a function; received: ").concat(i(s)));if(s.rawArgs)return s(d,e,createSubScope(t,r),t);var o=n.map((e=>e(t,r,a)));return s.apply(s,o)}}var m=p in e?getSafeProperty(e,p):void 0,h="function"==typeof m&&!0===m.rawArgs,f=t=>{var n;if(t.has(p))n=t.get(p);else{if(!(p in e))return a.onUndefinedFunction(p);n=getSafeProperty(e,p)}if("function"==typeof n)return n;throw new TypeError("'".concat(p,"' is not a function; its value is:\n ").concat(i(n)))};if(h){var y=this.args;return function(t,n,r){return f(t)(y,e,createSubScope(t,n),t)}}switch(n.length){case 0:return function(e,t,n){return f(e)()};case 1:return function(e,t,r){return f(e)((0,n[0])(e,t,r))};case 2:return function(e,t,r){var a=f(e),i=n[0],s=n[1];return a(i(e,t,r),s(e,t,r))};default:return function(e,t,r){return f(e)(...n.map((n=>n(e,t,r))))}}},a.prototype.forEach=function(e){e(this.fn,"fn",this);for(var t=0;t'+escape$1(this.fn)+'('+t.join(',')+')'};var l=a.prototype.toTex;return a.prototype.toTex=function(e){var t;return e&&"object"==typeof e.handler&&hasOwnProperty$2(e.handler,this.name)&&(t=e.handler[this.name](this,e)),void 0!==t?t:l.call(this,e)},a.prototype._toTex=function(e){var n,r,a=this.args.map((function(t){return t.toTex(e)}));switch(latexFunctions[this.name]&&(n=latexFunctions[this.name]),!t[this.name]||"function"!=typeof t[this.name].toTex&&"object"!=typeof t[this.name].toTex&&"string"!=typeof t[this.name].toTex||(n=t[this.name].toTex),typeof n){case"function":r=n(this,e);break;case"string":r=o(n,this,e);break;case"object":switch(typeof n[a.length]){case"function":r=n[a.length](this,e);break;case"string":r=o(n[a.length],this,e)}}return void 0!==r?r:o(defaultTemplate,this,e)},a.prototype.getIdentifier=function(){return this.type+":"+this.name},a}),{isClass:!0,isNode:!0}),name$1e="parse",dependencies$1e=["typed","numeric","config","AccessorNode","ArrayNode","AssignmentNode","BlockNode","ConditionalNode","ConstantNode","FunctionAssignmentNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","RangeNode","RelationalNode","SymbolNode"],createParse=factory(name$1e,dependencies$1e,(e=>{var{typed:t,numeric:n,config:r,AccessorNode:a,ArrayNode:i,AssignmentNode:s,BlockNode:o,ConditionalNode:l,ConstantNode:u,FunctionAssignmentNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:h,ParenthesisNode:f,RangeNode:y,RelationalNode:g,SymbolNode:b}=e,v=t(name$1e,{string:function(e){return B(e,{})},"Array | Matrix":function(e){return N(e,{})},"string, Object":function(e,t){return B(e,void 0!==t.nodes?t.nodes:{})},"Array | Matrix, Object":N});function N(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=void 0!==t.nodes?t.nodes:{};return deepMap(e,(function(e){if("string"!=typeof e)throw new TypeError("String expected");return B(e,n)}))}var T=0,C=1,A=2,V=3,x=4,S={",":!0,"(":!0,")":!0,"[":!0,"]":!0,"{":!0,"}":!0,'"':!0,"'":!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"~":!0,"!":!0,"&":!0,"|":!0,"^|":!0,"=":!0,":":!0,"?":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0,"<<":!0,">>":!0,">>>":!0},w={mod:!0,to:!0,in:!0,and:!0,xor:!0,or:!0,not:!0},E={true:!0,false:!1,null:null,undefined:void 0},D=["NaN","Infinity"];function O(e,t){return e.expression.substr(e.index,t)}function I(e){return O(e,1)}function R(e){e.index++}function _(e){return e.expression.charAt(e.index-1)}function M(e){return e.expression.charAt(e.index+1)}function P(e){for(e.tokenType=T,e.token="",e.comment="";;){if("#"===I(e))for(;"\n"!==I(e)&&""!==I(e);)e.comment+=I(e),R(e);if(!v.isWhitespace(I(e),e.nestingLevel))break;R(e)}if(""!==I(e)){if("\n"===I(e)&&!e.nestingLevel)return e.tokenType=C,e.token=I(e),void R(e);var t=I(e),n=O(e,2),r=O(e,3);if(3===r.length&&S[r])return e.tokenType=C,e.token=r,R(e),R(e),void R(e);if(2===n.length&&S[n])return e.tokenType=C,e.token=n,R(e),void R(e);if(S[t])return e.tokenType=C,e.token=t,void R(e);if(v.isDigitDot(t)){e.tokenType=A;var a=O(e,2);if("0b"===a||"0o"===a||"0x"===a){for(e.token+=I(e),R(e),e.token+=I(e),R(e);v.isHexDigit(I(e));)e.token+=I(e),R(e);if("."===I(e))for(e.token+=".",R(e);v.isHexDigit(I(e));)e.token+=I(e),R(e);else if("i"===I(e))for(e.token+="i",R(e);v.isDigit(I(e));)e.token+=I(e),R(e);return}if("."===I(e)){if(e.token+=I(e),R(e),!v.isDigit(I(e)))return void(e.tokenType=C)}else{for(;v.isDigit(I(e));)e.token+=I(e),R(e);v.isDecimalMark(I(e),M(e))&&(e.token+=I(e),R(e))}for(;v.isDigit(I(e));)e.token+=I(e),R(e);if("E"===I(e)||"e"===I(e))if(v.isDigit(M(e))||"-"===M(e)||"+"===M(e)){if(e.token+=I(e),R(e),"+"!==I(e)&&"-"!==I(e)||(e.token+=I(e),R(e)),!v.isDigit(I(e)))throw oe(e,'Digit expected, got "'+I(e)+'"');for(;v.isDigit(I(e));)e.token+=I(e),R(e);if(v.isDecimalMark(I(e),M(e)))throw oe(e,'Digit expected, got "'+I(e)+'"')}else if("."===M(e))throw R(e),oe(e,'Digit expected, got "'+I(e)+'"')}else{if(!v.isAlpha(I(e),_(e),M(e))){for(e.tokenType=x;""!==I(e);)e.token+=I(e),R(e);throw oe(e,'Syntax error in part "'+e.token+'"')}for(;v.isAlpha(I(e),_(e),M(e))||v.isDigit(I(e));)e.token+=I(e),R(e);hasOwnProperty$2(w,e.token)?e.tokenType=C:e.tokenType=V}}else e.tokenType=C}function F(e){do{P(e)}while("\n"===e.token)}function k(e){e.nestingLevel++}function $(e){e.nestingLevel--}function B(e,t){var n={extraNodes:{},expression:"",comment:"",index:0,token:"",tokenType:T,nestingLevel:0,conditionalLevel:null};_extends$1(n,{expression:e,extraNodes:t}),P(n);var r=function(e){var t,n,r=[];for(""!==e.token&&"\n"!==e.token&&";"!==e.token&&((t=L(e)).comment=e.comment);"\n"===e.token||";"===e.token;)0===r.length&&t&&(n=";"!==e.token,r.push({node:t,visible:n})),P(e),"\n"!==e.token&&";"!==e.token&&""!==e.token&&((t=L(e)).comment=e.comment,n=";"!==e.token,r.push({node:t,visible:n}));return r.length>0?new o(r):(t||((t=new u(void 0)).comment=e.comment),t)}(n);if(""!==n.token)throw n.tokenType===C?le(n,"Unexpected operator "+n.token):oe(n,'Unexpected part "'+n.token+'"');return r}function L(e){var t,n,r,a,i=function(e){for(var t=function(e){for(var t=z(e);"or"===e.token;)F(e),t=new h("or","or",[t,z(e)]);return t}(e);"?"===e.token;){var n=e.conditionalLevel;e.conditionalLevel=e.nestingLevel,F(e);var r=t,a=L(e);if(":"!==e.token)throw oe(e,"False part of conditional expression expected");e.conditionalLevel=null,F(e);var i=L(e);t=new l(r,a,i),e.conditionalLevel=n}return t}(e);if("="===e.token){if(isSymbolNode(i))return t=i.name,F(e),r=L(e),new s(new b(t),r);if(isAccessorNode(i))return F(e),r=L(e),new s(i.object,i.index,r);if(isFunctionNode(i)&&isSymbolNode(i.fn)&&(a=!0,n=[],t=i.name,i.args.forEach((function(e,t){isSymbolNode(e)?n[t]=e.name:a=!1})),a))return F(e),r=L(e),new c(t,n,r);throw oe(e,"Invalid left hand side of assignment operator =")}return i}function z(e){for(var t=U(e);"xor"===e.token;)F(e),t=new h("xor","xor",[t,U(e)]);return t}function U(e){for(var t=j(e);"and"===e.token;)F(e),t=new h("and","and",[t,j(e)]);return t}function j(e){for(var t=q(e);"|"===e.token;)F(e),t=new h("|","bitOr",[t,q(e)]);return t}function q(e){for(var t=G(e);"^|"===e.token;)F(e),t=new h("^|","bitXor",[t,G(e)]);return t}function G(e){for(var t=H(e);"&"===e.token;)F(e),t=new h("&","bitAnd",[t,H(e)]);return t}function H(e){for(var t=[W(e)],n=[],r={"==":"equal","!=":"unequal","<":"smaller",">":"larger","<=":"smallerEq",">=":"largerEq"};hasOwnProperty$2(r,e.token);){var a={name:e.token,fn:r[e.token]};n.push(a),F(e),t.push(W(e))}return 1===t.length?t[0]:2===t.length?new h(n[0].name,n[0].fn,t):new g(n.map((e=>e.fn)),t)}function W(e){var t,n,r,a;t=K(e);for(var i={"<<":"leftShift",">>":"rightArithShift",">>>":"rightLogShift"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),a=[t,K(e)],t=new h(n,r,a);return t}function K(e){var t,n,r,a;t=Z(e);for(var i={to:"to",in:"to"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),"in"===n&&""===e.token?t=new h("*","multiply",[t,new b("in")],!0):(a=[t,Z(e)],t=new h(n,r,a));return t}function Z(e){var t,n=[];if(t=":"===e.token?new u(1):X(e),":"===e.token&&e.conditionalLevel!==e.nestingLevel){for(n.push(t);":"===e.token&&n.length<3;)F(e),")"===e.token||"]"===e.token||","===e.token||""===e.token?n.push(new b("end")):n.push(X(e));t=3===n.length?new y(n[0],n[2],n[1]):new y(n[0],n[1])}return t}function X(e){var t,n,r,a;t=Y(e);for(var i={"+":"add","-":"subtract"};hasOwnProperty$2(i,e.token);){r=i[n=e.token],F(e);var s=Y(e);a=s.isPercentage?[t,new h("*","multiply",[t,s])]:[t,s],t=new h(n,r,a)}return t}function Y(e){var t,n,r,a;n=t=Q(e);for(var i={"*":"multiply",".*":"dotMultiply","/":"divide","./":"dotDivide"};hasOwnProperty$2(i,e.token);)a=i[r=e.token],F(e),n=Q(e),t=new h(r,a,[t,n]);return t}function Q(e){var t,n;for(n=t=J(e);e.tokenType===V||"in"===e.token&&isConstantNode(t)||!(e.tokenType!==A||isConstantNode(n)||isOperatorNode(n)&&"!"!==n.op)||"("===e.token;)n=J(e),t=new h("*","multiply",[t,n],!0);return t}function J(e){for(var t=ee(e),n=t,r=[];"/"===e.token&&isConstantNode(n);){if(r.push(_extends$1({},e)),F(e),e.tokenType!==A){_extends$1(e,r.pop());break}if(r.push(_extends$1({},e)),F(e),e.tokenType!==V&&"("!==e.token){r.pop(),_extends$1(e,r.pop());break}_extends$1(e,r.pop()),r.pop(),n=ee(e),t=new h("/","divide",[t,n])}return t}function ee(e){var t,n,r,a;t=te(e);for(var i={"%":"mod",mod:"mod"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),"%"===n&&e.tokenType===C&&"("!==e.token?t=new h("/","divide",[t,new u(100)],!1,!0):(a=[t,te(e)],t=new h(n,r,a));return t}function te(e){var t,a,s,o={"-":"unaryMinus","+":"unaryPlus","~":"bitNot",not:"not"};return hasOwnProperty$2(o,e.token)?(s=o[e.token],t=e.token,F(e),a=[te(e)],new h(t,s,a)):function(e){var t,a,s,o;return t=function(e){var t,a,s;t=function(e){var t=[];if(e.tokenType===V&&hasOwnProperty$2(e.extraNodes,e.token)){var a=e.extraNodes[e.token];if(P(e),"("===e.token){if(t=[],k(e),P(e),")"!==e.token)for(t.push(L(e));","===e.token;)P(e),t.push(L(e));if(")"!==e.token)throw oe(e,"Parenthesis ) expected");$(e),P(e)}return new a(t)}return function(e){var t;return e.tokenType===V||e.tokenType===C&&e.token in w?(t=e.token,P(e),ne(e,hasOwnProperty$2(E,t)?new u(E[t]):-1!==D.indexOf(t)?new u(n(t,"number")):new b(t))):function(e){var t;return'"'===e.token?(t=re(e),ne(e,new u(t))):function(e){var t;return"'"===e.token?(t=ae(e),ne(e,new u(t))):function(e){var t,a,s,o;if("["===e.token){if(k(e),P(e),"]"!==e.token){var l=ie(e);if(";"===e.token){for(s=1,a=[l];";"===e.token;)P(e),a[s]=ie(e),s++;if("]"!==e.token)throw oe(e,"End of matrix ] expected");$(e),P(e),o=a[0].items.length;for(var c=1;c0},v.isDecimalMark=function(e,t){return"."===e&&"/"!==t&&"*"!==t&&"^"!==t},v.isDigitDot=function(e){return e>="0"&&e<="9"||"."===e},v.isDigit=function(e){return e>="0"&&e<="9"},v.isHexDigit=function(e){return e>="0"&&e<="9"||e>="a"&&e<="f"||e>="A"&&e<="F"},v})),name$1d="compile",dependencies$1d=["typed","parse"],createCompile=factory(name$1d,dependencies$1d,(e=>{var{typed:t,parse:n}=e;return t(name$1d,{string:function(e){return n(e).compile()},"Array | Matrix":function(e){return deepMap(e,(function(e){return n(e).compile()}))}})})),name$1c="evaluate",dependencies$1c=["typed","parse"],createEvaluate=factory(name$1c,dependencies$1c,(e=>{var{typed:t,parse:n}=e;return t(name$1c,{string:function(e){var t=createEmptyMap();return n(e).compile().evaluate(t)},"string, Map | Object":function(e,t){return n(e).compile().evaluate(t)},"Array | Matrix":function(e){var t=createEmptyMap();return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))},"Array | Matrix, Map | Object":function(e,t){return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))}})})),name$1b="Parser",dependencies$1b=["evaluate"],createParserClass=factory(name$1b,dependencies$1b,(e=>{var{evaluate:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");Object.defineProperty(this,"scope",{value:createEmptyMap(),writable:!1})}return n.prototype.type="Parser",n.prototype.isParser=!0,n.prototype.evaluate=function(e){return t(e,this.scope)},n.prototype.get=function(e){if(this.scope.has(e))return this.scope.get(e)},n.prototype.getAll=function(){return toObject(this.scope)},n.prototype.getAllAsMap=function(){return this.scope},n.prototype.set=function(e,t){return this.scope.set(e,t),t},n.prototype.remove=function(e){this.scope.delete(e)},n.prototype.clear=function(){this.scope.clear()},n}),{isClass:!0}),name$1a="parser",dependencies$1a=["typed","Parser"],createParser=factory(name$1a,dependencies$1a,(e=>{var{typed:t,Parser:n}=e;return t(name$1a,{"":function(){return new n}})})),name$19="lup",dependencies$19=["typed","matrix","abs","addScalar","divideScalar","multiplyScalar","subtract","larger","equalScalar","unaryMinus","DenseMatrix","SparseMatrix","Spa"],createLup=factory(name$19,dependencies$19,(e=>{var{typed:t,matrix:n,abs:r,addScalar:a,divideScalar:i,multiplyScalar:s,subtract:o,larger:l,equalScalar:u,unaryMinus:c,DenseMatrix:p,SparseMatrix:d,Spa:m}=e;return t(name$19,{DenseMatrix:function(e){return h(e)},SparseMatrix:function(e){return function(e){var t,n,a,o=e._size[0],p=e._size[1],h=Math.min(o,p),f=e._values,y=e._index,g=e._ptr,b=[],v=[],N=[],T=[o,h],C=[],A=[],V=[],x=[h,p],S=[],w=[];for(t=0;t0&&e.forEach(0,n-1,(function(t,n){d._forEachRow(t,b,v,N,(function(r,a){r>t&&e.accumulate(r,c(s(a,n)))}))}));var E=n,D=e.get(n),O=r(D);e.forEach(n+1,o-1,(function(e,t){var n=r(t);l(n,O)&&(E=e,O=n,D=t)})),n!==E&&(d._swapRows(n,E,T[1],b,v,N),d._swapRows(n,E,x[1],C,A,V),e.swap(n,E),function(e,t){var n=w[e],r=w[t];S[n]=t,S[r]=e,w[e]=r,w[t]=n}(n,E)),e.forEach(0,o-1,(function(e,t){e<=n?(C.push(t),A.push(e)):(t=i(t,D),u(t,0)||(b.push(t),v.push(e)))}))};for(n=0;n0)for(t=0;t{var{typed:t,matrix:n,zeros:r,identity:a,isZero:i,equal:s,sign:o,sqrt:l,conj:u,unaryMinus:c,addScalar:p,divideScalar:d,multiplyScalar:m,subtract:h,complex:f}=e;return _extends$1(t(name$18,{DenseMatrix:function(e){return g(e)},SparseMatrix:function(e){return function(e){throw new Error("qr not implemented for sparse matrices yet")}()},Array:function(e){var t=g(n(e));return{Q:t.Q.valueOf(),R:t.R.valueOf()}}}),{_denseQRimpl:y});function y(e){var t,n,f,y=e._size[0],g=e._size[1],b=a([y],"dense"),v=b._data,N=e.clone(),T=N._data,C=r([y],"");for(f=0;f0)for(var r="Complex"===n[0][0].type?f(0):0,a=0;a=0;){var l=n[s+o],u=n[r+l];-1===u?(o--,i[t++]=l):(n[r+l]=n[a+u],n[s+ ++o]=u)}return t}function csPost(e,t){if(!e)return null;var n,r=0,a=[],i=[],s=t,o=2*t;for(n=0;n=0;n--)-1!==e[n]&&(i[s+n]=i[0+e[n]],i[0+e[n]]=n);for(n=0;n{var{add:t,multiply:n,transpose:r}=e;return function(e,s){if(!s||e<=0||e>3)return null;var o=s._size,l=o[0],u=o[1],c=0,p=Math.max(16,10*Math.sqrt(u)),d=function(e,a,i,s,o){var l=r(a);if(1===e&&s===i)return t(a,l);if(2===e){for(var u=l._index,c=l._ptr,p=0,d=0;do))for(var h=c[d+1];ms)n[o+d]=0,n[a+d]=-1,p++,t[d]=csFlip(e),n[o+e]++;else{var h=n[l+m];-1!==h&&(u[h]=d),n[c+d]=n[l+m],n[l+m]=d}}return p}(u,O,_,$,k,B,p,M,F,z,P),q=0;jG?(b=f,v=K,N=_[0+f]-G):(v=O[b=D[K++]],N=_[0+b]),g=1;g<=N;g++)(T=_[M+(m=D[v++])])<=0||(W+=T,_[M+m]=-T,D[X++]=m,-1!==_[P+m]&&(z[_[P+m]]=z[m]),-1!==z[m]?_[P+z[m]]=_[P+m]:_[F+_[$+m]]=_[P+m]);b!==f&&(O[b]=csFlip(f),_[B+b]=0)}for(0!==G&&(I=X),_[$+f]=W,O[f]=Z,_[0+f]=X-Z,_[k+f]=-2,U=a(U,c,_,B,u),C=Z;C=U?_[B+b]-=T:0!==_[B+b]&&(_[B+b]=_[$+b]+Y)}for(C=Z;C0?(E+=Q,D[S++]=b,w+=b):(O[b]=csFlip(f),_[B+b]=0)}_[k+m]=S-V+1;var J=S,ee=V+_[0+m];for(K=x+1;K=0))for(m=_[L+(w=z[m])],_[L+w]=-1;-1!==m&&-1!==_[P+m];m=_[P+m],U++){for(N=_[0+m],A=_[k+m],K=O[m]+1;K<=O[m]+N-1;K++)_[B+D[K]]=U;var ne=m;for(h=_[P+m];-1!==h;){var re=_[0+h]===N&&_[k+h]===A;for(K=O[h]+1;re&&K<=O[h]+N-1;K++)_[B+D[K]]!==U&&(re=0);re?(O[h]=csFlip(m),_[M+m]+=_[M+h],_[M+h]=0,_[k+h]=-1,h=_[P+h],_[P+ne]=h):(ne=h,h=_[P+h])}}for(K=Z,C=Z;C=0;h--)_[M+h]>0||(_[P+h]=_[F+O[h]],_[F+O[h]]=h);for(b=u;b>=0;b--)_[M+b]<=0||-1!==O[b]&&(_[P+b]=_[F+O[b]],_[F+O[b]]=b);for(f=0,m=0;m<=u;m++)-1===O[m]&&(f=csTdfs(m,f,_,F,P,R,B));return R.splice(R.length-1,1),R};function a(e,t,n,r,a){if(e<2||e+t<0){for(var i=0;i{var{transpose:t}=e;return function(e,n,r,a){if(!e||!n||!r)return null;var i,s,o,l,u,c,p,d=e._size,m=d[0],h=d[1],f=4*h+(a?h+m+1:0),y=[],g=h,b=2*h,v=3*h,N=4*h,T=5*h+1;for(o=0;o=1&&C[s]++,2===S.jleaf&&C[S.q]--}-1!==n[s]&&(y[0+s]=n[s])}for(s=0;s{var{add:t,multiply:n,transpose:r}=e,a=createCsAmd({add:t,multiply:n,transpose:r}),i=createCsCounts({transpose:r});return function(e,t,n){var r,s=t._ptr,o=t._size[1],l={};if(l.q=a(e,t),e&&!l.q)return null;if(n){var u=e?csPermute(t,null,l.q,0):t;l.parent=csEtree(u,1);var c=csPost(l.parent,o);if(l.cp=i(u,l.parent,c,1),u&&l.parent&&l.cp&&function(e,t){var n=e._ptr,r=e._index,a=e._size,i=a[0],s=a[1];t.pinv=[],t.leftmost=[];var o,l,u,c,p,d=t.parent,m=t.pinv,h=t.leftmost,f=[],y=i,g=i+s,b=i+2*s;for(l=0;l=0;l--)for(c=n[l],p=n[l+1],u=c;u=0;o--)m[o]=-1,-1!==(l=h[o])&&(0==f[b+l]++&&(f[g+l]=o),f[0+o]=f[y+l],f[y+l]=o);for(t.lnz=0,t.m2=i,l=0;l=0;){e=r[p];var d=a?a[e]:e;csMarked(u,e)||(csMark(u,e),r[c+p]=d<0?0:csUnflip(u[d]));var m=1;for(s=r[c+p],o=d<0?0:csUnflip(u[d+1]);s{var{divideScalar:t,multiply:n,subtract:r}=e;return function(e,a,i,s,o,l,u){var c,p,d,m,h=e._values,f=e._index,y=e._ptr,g=e._size[1],b=a._values,v=a._index,N=a._ptr,T=csReach(e,a,i,s,l);for(c=T;c{var{abs:t,divideScalar:n,multiply:r,subtract:a,larger:i,largerEq:s,SparseMatrix:o}=e,l=createCsSpsolve({divideScalar:n,multiply:r,subtract:a});return function(e,a,u){if(!e)return null;var c,p=e._size[1],d=100,m=100;a&&(c=a.q,d=a.lnz||d,m=a.unz||m);var h,f,y=[],g=[],b=[],v=new o({values:y,index:g,ptr:b,size:[p,p]}),N=[],T=[],C=[],A=new o({values:N,index:T,ptr:C,size:[p,p]}),V=[],x=[],S=[];for(h=0;h{var{typed:t,abs:n,add:r,multiply:a,transpose:i,divideScalar:s,subtract:o,larger:l,largerEq:u,SparseMatrix:c}=e,p=createCsSqr({add:r,multiply:a,transpose:i}),d=createCsLu({abs:n,divideScalar:s,multiply:a,subtract:o,larger:l,largerEq:u,SparseMatrix:c});return t(name$12,{"SparseMatrix, number, number":function(e,t,n){if(!isInteger$1(t)||t<0||t>3)throw new Error("Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]");if(n<0||n>1)throw new Error("Partial pivoting threshold must be a number from 0 to 1");var r=p(t,e,!1),a=d(e,r,n);return{L:a.L,U:a.U,p:a.pinv,q:r.q,toString:function(){return"L: "+this.L.toString()+"\nU: "+this.U.toString()+"\np: "+this.p.toString()+(this.q?"\nq: "+this.q.toString():"")+"\n"}}}})}));function csIpvec(e,t){var n,r=t.length,a=[];if(e)for(n=0;n{var{typed:t,matrix:n,lup:r,slu:a,usolve:i,lsolve:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$11,{"Array, Array | Matrix":function(e,t){e=n(e);var a=r(e);return c(a.L,a.U,a.p,null,t).valueOf()},"DenseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix, number, number":function(e,t,n,r){var i=a(e,n,r);return c(i.L,i.U,i.p,i.q,t)},"Object, Array | Matrix":function(e,t){return c(e.L,e.U,e.p,e.q,t)}});function u(e){if(isMatrix(e))return e;if(isArray$1(e))return n(e);throw new TypeError("Invalid Matrix LU decomposition")}function c(e,t,n,r,a){e=u(e),t=u(t),n&&((a=l(e,a,!0))._data=csIpvec(n,a._data));var o=s(e,a),c=i(t,o);return r&&(c._data=csIpvec(r,c._data)),c}})),name$10="Help",dependencies$10=["parse"],createHelpClass=factory(name$10,dependencies$10,(e=>{var{parse:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!e)throw new Error('Argument "doc" missing');this.doc=e}return n.prototype.type="Help",n.prototype.isHelp=!0,n.prototype.toString=function(){var e=this.doc||{},n="\n";if(e.name&&(n+="Name: "+e.name+"\n\n"),e.category&&(n+="Category: "+e.category+"\n\n"),e.description&&(n+="Description:\n "+e.description+"\n\n"),e.syntax&&(n+="Syntax:\n "+e.syntax.join("\n ")+"\n\n"),e.examples){n+="Examples:\n";for(var r={},a=0;a"mathjs"!==e)).forEach((n=>{t[n]=e[n]})),new n(t)},n.prototype.valueOf=n.prototype.toString,n}),{isClass:!0}),name$$="Chain",dependencies$$=["?on","math"],createChainClass=factory(name$$,dependencies$$,(e=>{var{on:t,math:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");isChain(e)?this.value=e.value:this.value=e}function a(e,t){lazy(r.prototype,e,(function(){var e=t();if("function"==typeof e)return i(e)}))}function i(e){return function(){for(var t=[this.value],n=0;ne[t]))};for(var o in e)n(o)}};var s={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return r.createProxy(n),t&&t("import",(function(e,t,n){n||a(e,t)})),r}),{isClass:!0}),eDocs={name:"e",category:"Constants",syntax:["e"],description:"Euler's number, the base of the natural logarithm. Approximately equal to 2.71828",examples:["e","e ^ 2","exp(2)","log(e)"],seealso:["exp"]},falseDocs={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]},iDocs={name:"i",category:"Constants",syntax:["i"],description:"Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.",examples:["i","i * i","sqrt(-1)"],seealso:[]},InfinityDocs={name:"Infinity",category:"Constants",syntax:["Infinity"],description:"Infinity, a number which is larger than the maximum number that can be handled by a floating point number.",examples:["Infinity","1 / 0"],seealso:[]},LN10Docs={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]},LN2Docs={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]},LOG10EDocs={name:"LOG10E",category:"Constants",syntax:["LOG10E"],description:"Returns the base-10 logarithm of E, approximately equal to 0.434",examples:["LOG10E","log(e, 10)"],seealso:[]},LOG2EDocs={name:"LOG2E",category:"Constants",syntax:["LOG2E"],description:"Returns the base-2 logarithm of E, approximately equal to 1.442",examples:["LOG2E","log(e, 2)"],seealso:[]},NaNDocs={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]},nullDocs={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]},phiDocs={name:"phi",category:"Constants",syntax:["phi"],description:"Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...",examples:["phi"],seealso:[]},piDocs={name:"pi",category:"Constants",syntax:["pi"],description:"The number pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, and is approximately equal to 3.14159",examples:["pi","sin(pi/2)"],seealso:["tau"]},SQRT12Docs={name:"SQRT1_2",category:"Constants",syntax:["SQRT1_2"],description:"Returns the square root of 1/2, approximately equal to 0.707",examples:["SQRT1_2","sqrt(1/2)"],seealso:[]},SQRT2Docs={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]},tauDocs={name:"tau",category:"Constants",syntax:["tau"],description:"Tau is the ratio constant of a circle's circumference to radius, equal to 2 * pi, approximately 6.2832.",examples:["tau","2 * pi"],seealso:["pi"]},trueDocs={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]},versionDocs={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]},bignumberDocs={name:"bignumber",category:"Construction",syntax:["bignumber(x)"],description:"Create a big number from a number or string.",examples:["0.1 + 0.2","bignumber(0.1) + bignumber(0.2)",'bignumber("7.2")','bignumber("7.2e500")',"bignumber([0.1, 0.2, 0.3])"],seealso:["boolean","complex","fraction","index","matrix","string","unit"]},booleanDocs={name:"boolean",category:"Construction",syntax:["x","boolean(x)"],description:"Convert a string or number into a boolean.",examples:["boolean(0)","boolean(1)","boolean(3)",'boolean("true")','boolean("false")',"boolean([1, 0, 1, 1])"],seealso:["bignumber","complex","index","matrix","number","string","unit"]},complexDocs={name:"complex",category:"Construction",syntax:["complex()","complex(re, im)","complex(string)"],description:"Create a complex number.",examples:["complex()","complex(2, 3)",'complex("7 - 2i")'],seealso:["bignumber","boolean","index","matrix","number","string","unit"]},createUnitDocs={name:"createUnit",category:"Construction",syntax:["createUnit(definitions)","createUnit(name, definition)"],description:"Create a user-defined unit and register it with the Unit type.",examples:['createUnit("foo")','createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})','createUnit("mph", "1 mile/hour")'],seealso:["unit","splitUnit"]},fractionDocs={name:"fraction",category:"Construction",syntax:["fraction(num)","fraction(matrix)","fraction(num,den)","fraction({n: num, d: den})"],description:"Create a fraction from a number or from integer numerator and denominator.",examples:["fraction(0.125)","fraction(1, 3) + fraction(2, 5)","fraction({n: 333, d: 53})","fraction([sqrt(9), sqrt(10), sqrt(11)])"],seealso:["bignumber","boolean","complex","index","matrix","string","unit"]},indexDocs={name:"index",category:"Construction",syntax:["[start]","[start:end]","[start:step:end]","[start1, start 2, ...]","[start1:end1, start2:end2, ...]","[start1:step1:end1, start2:step2:end2, ...]"],description:"Create an index to get or replace a subset of a matrix",examples:["[]","[1, 2, 3]","A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[0:2, 0:2] = ones(2, 2)"],seealso:["bignumber","boolean","complex","matrix,","number","range","string","unit"]},matrixDocs={name:"matrix",category:"Construction",syntax:["[]","[a1, b1, ...; a2, b2, ...]","matrix()",'matrix("dense")',"matrix([...])"],description:"Create a matrix.",examples:["[]","[1, 2, 3]","[1, 2, 3; 4, 5, 6]","matrix()","matrix([3, 4])",'matrix([3, 4; 5, 6], "sparse")','matrix([3, 4; 5, 6], "sparse", "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","sparse"]},numberDocs={name:"number",category:"Construction",syntax:["x","number(x)","number(unit, valuelessUnit)"],description:"Create a number or convert a string or boolean into a number.",examples:["2","2e3","4.05","number(2)",'number("7.2")',"number(true)","number([true, false, true, true])",'number(unit("52cm"), "m")'],seealso:["bignumber","boolean","complex","fraction","index","matrix","string","unit"]},sparseDocs={name:"sparse",category:"Construction",syntax:["sparse()","sparse([a1, b1, ...; a1, b2, ...])",'sparse([a1, b1, ...; a1, b2, ...], "number")'],description:"Create a sparse matrix.",examples:["sparse()","sparse([3, 4; 5, 6])",'sparse([3, 0; 5, 0], "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","matrix"]},splitUnitDocs={name:"splitUnit",category:"Construction",syntax:["splitUnit(unit: Unit, parts: Unit[])"],description:"Split a unit in an array of units whose sum is equal to the original unit.",examples:['splitUnit(1 m, ["feet", "inch"])'],seealso:["unit","createUnit"]},stringDocs={name:"string",category:"Construction",syntax:['"text"',"string(x)"],description:"Create a string or convert a value to a string",examples:['"Hello World!"',"string(4.2)","string(3 + 2i)"],seealso:["bignumber","boolean","complex","index","matrix","number","unit"]},unitDocs={name:"unit",category:"Construction",syntax:["value unit","unit(value, unit)","unit(string)"],description:"Create a unit.",examples:["5.5 mm","3 inch",'unit(7.1, "kilogram")','unit("23 deg")'],seealso:["bignumber","boolean","complex","index","matrix","number","string"]},configDocs={name:"config",category:"Core",syntax:["config()","config(options)"],description:"Get configuration or change configuration.",examples:["config()","1/3 + 1/4",'config({number: "Fraction"})',"1/3 + 1/4"],seealso:[]},importDocs={name:"import",category:"Core",syntax:["import(functions)","import(functions, options)"],description:"Import functions or constants from an object.",examples:["import({myFn: f(x)=x^2, myConstant: 32 })","myFn(2)","myConstant"],seealso:[]},typedDocs={name:"typed",category:"Core",syntax:["typed(signatures)","typed(name, signatures)"],description:"Create a typed function.",examples:['double = typed({ "number": f(x)=x+x })',"double(2)",'double("hello")'],seealso:[]},derivativeDocs={name:"derivative",category:"Algebra",syntax:["derivative(expr, variable)","derivative(expr, variable, {simplify: boolean})"],description:"Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.",examples:['derivative("2x^3", "x")','derivative("2x^3", "x", {simplify: false})','derivative("2x^2 + 3x + 4", "x")','derivative("sin(2x)", "x")','f = parse("x^2 + x")','x = parse("x")',"df = derivative(f, x)","df.evaluate({x: 3})"],seealso:["simplify","parse","evaluate"]},leafCountDocs={name:"leafCount",category:"Algebra",syntax:["leafCount(expr)"],description:"Computes the number of leaves in the parse tree of the given expression",examples:['leafCount("e^(i*pi)-1")','leafCount(parse("{a: 22/7, b: 10^(1/2)}"))'],seealso:["simplify"]},lsolveDocs={name:"lsolve",category:"Algebra",syntax:["x=lsolve(L, b)"],description:"Finds one solution of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolveAll","lup","lusolve","usolve","matrix","sparse"]},lsolveAllDocs={name:"lsolveAll",category:"Algebra",syntax:["x=lsolveAll(L, b)"],description:"Finds all solutions of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolve","lup","lusolve","usolve","matrix","sparse"]},lupDocs={name:"lup",category:"Algebra",syntax:["lup(m)"],description:"Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U",examples:["lup([[2, 1], [1, 4]])","lup(matrix([[2, 1], [1, 4]]))","lup(sparse([[2, 1], [1, 4]]))"],seealso:["lusolve","lsolve","usolve","matrix","sparse","slu","qr"]},lusolveDocs={name:"lusolve",category:"Algebra",syntax:["x=lusolve(A, b)","x=lusolve(lu, b)"],description:"Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lusolve(a, b)"],seealso:["lup","slu","lsolve","usolve","matrix","sparse"]},qrDocs={name:"qr",category:"Algebra",syntax:["qr(A)"],description:"Calculates the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix.",examples:["qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])"],seealso:["lup","slu","matrix"]},rationalizeDocs={name:"rationalize",category:"Algebra",syntax:["rationalize(expr)","rationalize(expr, scope)","rationalize(expr, scope, detailed)"],description:"Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.",examples:['rationalize("2x/y - y/(x+1)")','rationalize("2x/y - y/(x+1)", true)'],seealso:["simplify"]},resolveDocs={name:"resolve",category:"Algebra",syntax:["resolve(node, scope)"],description:"Recursively substitute variables in an expression tree.",examples:['resolve(parse("1 + x"), { x: 7 })','resolve(parse("size(text)"), { text: "Hello World" })','resolve(parse("x + y"), { x: parse("3z") })','resolve(parse("3x"), { x: parse("y+z"), z: parse("w^y") })'],seealso:["simplify","evaluate"],mayThrow:["ReferenceError"]},simplifyDocs={name:"simplify",category:"Algebra",syntax:["simplify(expr)","simplify(expr, rules)"],description:"Simplify an expression tree.",examples:['simplify("3 + 2 / 4")','simplify("2x + x")','f = parse("x * (x + 2 + x)")',"simplified = simplify(f)","simplified.evaluate({x: 2})"],seealso:["simplifyCore","derivative","evaluate","parse","rationalize","resolve"]},simplifyCoreDocs={name:"simplifyCore",category:"Algebra",syntax:["simplifyCore(node)"],description:"Perform simple one-pass simplifications on an expression tree.",examples:['simplifyCore(parse("0*x"))','simplifyCore(parse("(x+0)*2"))'],seealso:["simplify","evaluate"]},sluDocs={name:"slu",category:"Algebra",syntax:["slu(A, order, threshold)"],description:"Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U",examples:["slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)"],seealso:["lusolve","lsolve","usolve","matrix","sparse","lup","qr"]},symbolicEqualDocs={name:"symbolicEqual",category:"Algebra",syntax:["symbolicEqual(expr1, expr2)","symbolicEqual(expr1, expr2, options)"],description:"Returns true if the difference of the expressions simplifies to 0",examples:['symbolicEqual("x*y","y*x")','symbolicEqual("abs(x^2)", "x^2")','symbolicEqual("abs(x)", "x", {context: {abs: {trivial: true}}})'],seealso:["simplify","evaluate"]},usolveDocs={name:"usolve",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolveAll","lup","lusolve","lsolve","matrix","sparse"]},usolveAllDocs={name:"usolveAll",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds all solutions of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolve","lup","lusolve","lsolve","matrix","sparse"]},absDocs={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]},addDocs={name:"add",category:"Operators",syntax:["x + y","add(x, y)"],description:"Add two values.",examples:["a = 2.1 + 3.6","a - 3.6","3 + 2i","3 cm + 2 inch",'"2.3" + "4"'],seealso:["subtract"]},cbrtDocs={name:"cbrt",category:"Arithmetic",syntax:["cbrt(x)","cbrt(x, allRoots)"],description:"Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned",examples:["cbrt(64)","cube(4)","cbrt(-8)","cbrt(2 + 3i)","cbrt(8i)","cbrt(8i, true)","cbrt(27 m^3)"],seealso:["square","sqrt","cube","multiply"]},ceilDocs={name:"ceil",category:"Arithmetic",syntax:["ceil(x)"],description:"Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.",examples:["ceil(3.2)","ceil(3.8)","ceil(-4.2)"],seealso:["floor","fix","round"]},cubeDocs={name:"cube",category:"Arithmetic",syntax:["cube(x)"],description:"Compute the cube of a value. The cube of x is x * x * x.",examples:["cube(2)","2^3","2 * 2 * 2"],seealso:["multiply","square","pow"]},divideDocs={name:"divide",category:"Operators",syntax:["x / y","divide(x, y)"],description:"Divide two values.",examples:["a = 2 / 3","a * 3","4.5 / 2","3 + 4 / 2","(3 + 4) / 2","18 km / 4.5"],seealso:["multiply"]},dotDivideDocs={name:"dotDivide",category:"Operators",syntax:["x ./ y","dotDivide(x, y)"],description:"Divide two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a ./ b"],seealso:["multiply","dotMultiply","divide"]},dotMultiplyDocs={name:"dotMultiply",category:"Operators",syntax:["x .* y","dotMultiply(x, y)"],description:"Multiply two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a .* b"],seealso:["multiply","divide","dotDivide"]},dotPowDocs={name:"dotPow",category:"Operators",syntax:["x .^ y","dotPow(x, y)"],description:"Calculates the power of x to y element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","a .^ 2"],seealso:["pow"]},expDocs={name:"exp",category:"Arithmetic",syntax:["exp(x)"],description:"Calculate the exponent of a value.",examples:["exp(1.3)","e ^ 1.3","log(exp(1.3))","x = 2.4","(exp(i*x) == cos(x) + i*sin(x)) # Euler's formula"],seealso:["expm","expm1","pow","log"]},expmDocs={name:"expm",category:"Arithmetic",syntax:["exp(x)"],description:"Compute the matrix exponential, expm(A) = e^A. The matrix must be square. Not to be confused with exp(a), which performs element-wise exponentiation.",examples:["expm([[0,2],[0,0]])"],seealso:["exp"]},expm1Docs={name:"expm1",category:"Arithmetic",syntax:["expm1(x)"],description:"Calculate the value of subtracting 1 from the exponential value.",examples:["expm1(2)","pow(e, 2) - 1","log(expm1(2) + 1)"],seealso:["exp","pow","log"]},fixDocs={name:"fix",category:"Arithmetic",syntax:["fix(x)"],description:"Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.",examples:["fix(3.2)","fix(3.8)","fix(-4.2)","fix(-4.8)"],seealso:["ceil","floor","round"]},floorDocs={name:"floor",category:"Arithmetic",syntax:["floor(x)"],description:"Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.",examples:["floor(3.2)","floor(3.8)","floor(-4.2)"],seealso:["ceil","fix","round"]},gcdDocs={name:"gcd",category:"Arithmetic",syntax:["gcd(a, b)","gcd(a, b, c, ...)"],description:"Compute the greatest common divisor.",examples:["gcd(8, 12)","gcd(-4, 6)","gcd(25, 15, -10)"],seealso:["lcm","xgcd"]},hypotDocs={name:"hypot",category:"Arithmetic",syntax:["hypot(a, b, c, ...)","hypot([a, b, c, ...])"],description:"Calculate the hypotenusa of a list with values. ",examples:["hypot(3, 4)","sqrt(3^2 + 4^2)","hypot(-2)","hypot([3, 4, 5])"],seealso:["abs","norm"]},invmodDocs={name:"invmod",category:"Arithmetic",syntax:["invmod(a, b)"],description:"Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation ax ≣ 1 (mod b)",examples:["invmod(8, 12)=NaN","invmod(7, 13)=2","math.invmod(15151, 15122)=10429"],seealso:["gcd","xgcd"]},lcmDocs={name:"lcm",category:"Arithmetic",syntax:["lcm(x, y)"],description:"Compute the least common multiple.",examples:["lcm(4, 6)","lcm(6, 21)","lcm(6, 21, 5)"],seealso:["gcd"]},logDocs={name:"log",category:"Arithmetic",syntax:["log(x)","log(x, base)"],description:"Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).",examples:["log(3.5)","a = log(2.4)","exp(a)","10 ^ 4","log(10000, 10)","log(10000) / log(10)","b = log(1024, 2)","2 ^ b"],seealso:["exp","log1p","log2","log10"]},log10Docs={name:"log10",category:"Arithmetic",syntax:["log10(x)"],description:"Compute the 10-base logarithm of a value.",examples:["log10(0.00001)","log10(10000)","10 ^ 4","log(10000) / log(10)","log(10000, 10)"],seealso:["exp","log"]},log1pDocs={name:"log1p",category:"Arithmetic",syntax:["log1p(x)","log1p(x, base)"],description:"Calculate the logarithm of a `value+1`",examples:["log1p(2.5)","exp(log1p(1.4))","pow(10, 4)","log1p(9999, 10)","log1p(9999) / log(10)"],seealso:["exp","log","log2","log10"]},log2Docs={name:"log2",category:"Arithmetic",syntax:["log2(x)"],description:"Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.",examples:["log2(0.03125)","log2(16)","log2(16) / log2(2)","pow(2, 4)"],seealso:["exp","log1p","log","log10"]},modDocs={name:"mod",category:"Operators",syntax:["x % y","x mod y","mod(x, y)"],description:"Calculates the modulus, the remainder of an integer division.",examples:["7 % 3","11 % 2","10 mod 4","isOdd(x) = x % 2","isOdd(2)","isOdd(3)"],seealso:["divide"]},multiplyDocs={name:"multiply",category:"Operators",syntax:["x * y","multiply(x, y)"],description:"multiply two values.",examples:["a = 2.1 * 3.4","a / 3.4","2 * 3 + 4","2 * (3 + 4)","3 * 2.1 km"],seealso:["divide"]},normDocs={name:"norm",category:"Arithmetic",syntax:["norm(x)","norm(x, p)"],description:"Calculate the norm of a number, vector or matrix.",examples:["abs(-3.5)","norm(-3.5)","norm(3 - 4i)","norm([1, 2, -3], Infinity)","norm([1, 2, -3], -Infinity)","norm([3, 4], 2)","norm([[1, 2], [3, 4]], 1)",'norm([[1, 2], [3, 4]], "inf")','norm([[1, 2], [3, 4]], "fro")']},nthRootDocs={name:"nthRoot",category:"Arithmetic",syntax:["nthRoot(a)","nthRoot(a, root)"],description:'Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation "x^root = A".',examples:["4 ^ 3","nthRoot(64, 3)","nthRoot(9, 2)","sqrt(9)"],seealso:["nthRoots","pow","sqrt"]},nthRootsDocs={name:"nthRoots",category:"Arithmetic",syntax:["nthRoots(A)","nthRoots(A, root)"],description:'Calculate the nth roots of a value. An nth root of a positive real number A, is a positive real solution of the equation "x^root = A". This function returns an array of complex values.',examples:["nthRoots(1)","nthRoots(1, 3)"],seealso:["sqrt","pow","nthRoot"]},powDocs={name:"pow",category:"Operators",syntax:["x ^ y","pow(x, y)"],description:"Calculates the power of x to y, x^y.",examples:["2^3","2*2*2","1 + e ^ (pi * i)","math.pow([[1, 2], [4, 3]], 2)","math.pow([[1, 2], [4, 3]], -1)"],seealso:["multiply","nthRoot","nthRoots","sqrt"]},roundDocs={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)"],description:"round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.",examples:["round(3.2)","round(3.8)","round(-4.2)","round(-4.8)","round(pi, 3)","round(123.45678, 2)"],seealso:["ceil","floor","fix"]},signDocs={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]},sqrtDocs={name:"sqrt",category:"Arithmetic",syntax:["sqrt(x)"],description:"Compute the square root value. If x = y * y, then y is the square root of x.",examples:["sqrt(25)","5 * 5","sqrt(-1)"],seealso:["square","sqrtm","multiply","nthRoot","nthRoots","pow"]},sqrtmDocs={name:"sqrtm",category:"Arithmetic",syntax:["sqrtm(x)"],description:"Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.",examples:["sqrtm([[1, 2], [3, 4]])"],seealso:["sqrt","abs","square","multiply"]},squareDocs={name:"square",category:"Arithmetic",syntax:["square(x)"],description:"Compute the square of a value. The square of x is x * x.",examples:["square(3)","sqrt(9)","3^2","3 * 3"],seealso:["multiply","pow","sqrt","cube"]},subtractDocs={name:"subtract",category:"Operators",syntax:["x - y","subtract(x, y)"],description:"subtract two values.",examples:["a = 5.3 - 2","a + 2","2/3 - 1/6","2 * 3 - 3","2.1 km - 500m"],seealso:["add"]},unaryMinusDocs={name:"unaryMinus",category:"Operators",syntax:["-x","unaryMinus(x)"],description:"Inverse the sign of a value. Converts booleans and strings to numbers.",examples:["-4.5","-(-5.6)",'-"22"'],seealso:["add","subtract","unaryPlus"]},unaryPlusDocs={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]},xgcdDocs={name:"xgcd",category:"Arithmetic",syntax:["xgcd(a, b)"],description:"Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.",examples:["xgcd(8, 12)","gcd(8, 12)","xgcd(36163, 21199)"],seealso:["gcd","lcm"]},bitAndDocs={name:"bitAnd",category:"Bitwise",syntax:["x & y","bitAnd(x, y)"],description:"Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0",examples:["5 & 3","bitAnd(53, 131)","[1, 12, 31] & 42"],seealso:["bitNot","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]},bitNotDocs={name:"bitNot",category:"Bitwise",syntax:["~x","bitNot(x)"],description:"Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.",examples:["~1","~2","bitNot([2, -3, 4])"],seealso:["bitAnd","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]},bitOrDocs={name:"bitOr",category:"Bitwise",syntax:["x | y","bitOr(x, y)"],description:"Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.",examples:["5 | 3","bitOr([1, 2, 3], 4)"],seealso:["bitAnd","bitNot","bitXor","leftShift","rightArithShift","rightLogShift"]},bitXorDocs={name:"bitXor",category:"Bitwise",syntax:["bitXor(x, y)"],description:"Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.",examples:["bitOr(1, 2)","bitXor([2, 3, 4], 4)"],seealso:["bitAnd","bitNot","bitOr","leftShift","rightArithShift","rightLogShift"]},leftShiftDocs={name:"leftShift",category:"Bitwise",syntax:["x << y","leftShift(x, y)"],description:"Bitwise left logical shift of a value x by y number of bits.",examples:["4 << 1","8 >> 1"],seealso:["bitAnd","bitNot","bitOr","bitXor","rightArithShift","rightLogShift"]},rightArithShiftDocs={name:"rightArithShift",category:"Bitwise",syntax:["x >> y","rightArithShift(x, y)"],description:"Bitwise right arithmetic shift of a value x by y number of bits.",examples:["8 >> 1","4 << 1","-12 >> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightLogShift"]},rightLogShiftDocs={name:"rightLogShift",category:"Bitwise",syntax:["x >>> y","rightLogShift(x, y)"],description:"Bitwise right logical shift of a value x by y number of bits.",examples:["8 >>> 1","4 << 1","-12 >>> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightArithShift"]},bellNumbersDocs={name:"bellNumbers",category:"Combinatorics",syntax:["bellNumbers(n)"],description:"The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["bellNumbers(3)","bellNumbers(8)"],seealso:["stirlingS2"]},catalanDocs={name:"catalan",category:"Combinatorics",syntax:["catalan(n)"],description:"The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["catalan(3)","catalan(8)"],seealso:["bellNumbers"]},compositionDocs={name:"composition",category:"Combinatorics",syntax:["composition(n, k)"],description:"The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.",examples:["composition(5, 3)"],seealso:["combinations"]},stirlingS2Docs={name:"stirlingS2",category:"Combinatorics",syntax:["stirlingS2(n, k)"],description:"he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.",examples:["stirlingS2(5, 3)"],seealso:["bellNumbers"]},argDocs={name:"arg",category:"Complex",syntax:["arg(x)"],description:"Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).",examples:["arg(2 + 2i)","atan2(3, 2)","arg(2 + 3i)"],seealso:["re","im","conj","abs"]},conjDocs={name:"conj",category:"Complex",syntax:["conj(x)"],description:"Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.",examples:["conj(2 + 3i)","conj(2 - 3i)","conj(-5.2i)"],seealso:["re","im","abs","arg"]},imDocs={name:"im",category:"Complex",syntax:["im(x)"],description:"Get the imaginary part of a complex number.",examples:["im(2 + 3i)","re(2 + 3i)","im(-5.2i)","im(2.4)"],seealso:["re","conj","abs","arg"]},reDocs={name:"re",category:"Complex",syntax:["re(x)"],description:"Get the real part of a complex number.",examples:["re(2 + 3i)","im(2 + 3i)","re(-5.2i)","re(2.4)"],seealso:["im","conj","abs","arg"]},evaluateDocs={name:"evaluate",category:"Expression",syntax:["evaluate(expression)","evaluate([expr1, expr2, expr3, ...])"],description:"Evaluate an expression or an array with expressions.",examples:['evaluate("2 + 3")','evaluate("sqrt(" + 4 + ")")'],seealso:[]},helpDocs={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]},distanceDocs={name:"distance",category:"Geometry",syntax:["distance([x1, y1], [x2, y2])","distance([[x1, y1], [x2, y2]])"],description:"Calculates the Euclidean distance between two points.",examples:["distance([0,0], [4,4])","distance([[0,0], [4,4]])"],seealso:[]},intersectDocs={name:"intersect",category:"Geometry",syntax:["intersect(expr1, expr2, expr3, expr4)","intersect(expr1, expr2, expr3)"],description:"Computes the intersection point of lines and/or planes.",examples:["intersect([0, 0], [10, 10], [10, 0], [0, 10])","intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])"],seealso:[]},andDocs={name:"and",category:"Logical",syntax:["x and y","and(x, y)"],description:"Logical and. Test whether two values are both defined with a nonzero/nonempty value.",examples:["true and false","true and true","2 and 4"],seealso:["not","or","xor"]},notDocs={name:"not",category:"Logical",syntax:["not x","not(x)"],description:"Logical not. Flips the boolean value of given argument.",examples:["not true","not false","not 2","not 0"],seealso:["and","or","xor"]},orDocs={name:"or",category:"Logical",syntax:["x or y","or(x, y)"],description:"Logical or. Test if at least one value is defined with a nonzero/nonempty value.",examples:["true or false","false or false","0 or 4"],seealso:["not","and","xor"]},xorDocs={name:"xor",category:"Logical",syntax:["x xor y","xor(x, y)"],description:"Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.",examples:["true xor false","false xor false","true xor true","0 xor 4"],seealso:["not","and","or"]},columnDocs={name:"column",category:"Matrix",syntax:["column(x, index)"],description:"Return a column from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","column(A, 1)","column(A, 2)"],seealso:["row","matrixFromColumns"]},concatDocs={name:"concat",category:"Matrix",syntax:["concat(A, B, C, ...)","concat(A, B, C, ..., dim)"],description:"Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.",examples:["A = [1, 2; 5, 6]","B = [3, 4; 7, 8]","concat(A, B)","concat(A, B, 1)","concat(A, B, 2)"],seealso:["det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},countDocs={name:"count",category:"Matrix",syntax:["count(x)"],description:"Count the number of elements of a matrix, array or string.",examples:["a = [1, 2; 3, 4; 5, 6]","count(a)","size(a)",'count("hello world")'],seealso:["size"]},crossDocs={name:"cross",category:"Matrix",syntax:["cross(A, B)"],description:"Calculate the cross product for two vectors in three dimensional space.",examples:["cross([1, 1, 0], [0, 1, 1])","cross([3, -3, 1], [4, 9, 2])","cross([2, 3, 4], [5, 6, 7])"],seealso:["multiply","dot"]},ctransposeDocs={name:"ctranspose",category:"Matrix",syntax:["x'","ctranspose(x)"],description:"Complex Conjugate and Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","ctranspose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]},detDocs={name:"det",category:"Matrix",syntax:["det(x)"],description:"Calculate the determinant of a matrix",examples:["det([1, 2; 3, 4])","det([-2, 2, 3; -1, 1, 3; 2, 0, -1])"],seealso:["concat","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},diagDocs={name:"diag",category:"Matrix",syntax:["diag(x)","diag(x, k)"],description:"Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.",examples:["diag(1:3)","diag(1:3, 1)","a = [1, 2, 3; 4, 5, 6; 7, 8, 9]","diag(a)"],seealso:["concat","det","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},diffDocs={name:"diff",category:"Matrix",syntax:["diff(arr)","diff(arr, dim)"],description:["Create a new matrix or array with the difference of the passed matrix or array.","Dim parameter is optional and used to indicant the dimension of the array/matrix to apply the difference","If no dimension parameter is passed it is assumed as dimension 0","Dimension is zero-based in javascript and one-based in the parser","Arrays must be 'rectangular' meaning arrays like [1, 2]","If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays"],examples:["diff([1, 2, 4, 7, 0])","diff([1, 2, 4, 7, 0], 0)","diff(matrix([1, 2, 4, 7, 0]))","diff([[1, 2], [3, 4]])","diff([[1, 2], [3, 4]], 0)","diff([[1, 2], [3, 4]], 1)","diff([[1, 2], [3, 4]], bignumber(1))","diff(matrix([[1, 2], [3, 4]]), 1)","diff([[1, 2], matrix([3, 4])], 1)"],seealso:["subtract","partitionSelect"]},dotDocs={name:"dot",category:"Matrix",syntax:["dot(A, B)","A * B"],description:"Calculate the dot product of two vectors. The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn",examples:["dot([2, 4, 1], [2, 2, 3])","[2, 4, 1] * [2, 2, 3]"],seealso:["multiply","cross"]},eigsDocs={name:"eigs",category:"Matrix",syntax:["eigs(x)"],description:"Calculate the eigenvalues and eigenvectors of a real symmetric matrix",examples:["eigs([[5, 2.3], [2.3, 1]])"],seealso:["inv"]},filterDocs={name:"filter",category:"Matrix",syntax:["filter(x, test)"],description:"Filter items in a matrix.",examples:["isPositive(x) = x > 0","filter([6, -2, -1, 4, 3], isPositive)","filter([6, -2, 0, 1, 0], x != 0)"],seealso:["sort","map","forEach"]},flattenDocs={name:"flatten",category:"Matrix",syntax:["flatten(x)"],description:"Flatten a multi dimensional matrix into a single dimensional matrix.",examples:["a = [1, 2, 3; 4, 5, 6]","size(a)","b = flatten(a)","size(b)"],seealso:["concat","resize","size","squeeze"]},forEachDocs={name:"forEach",category:"Matrix",syntax:["forEach(x, callback)"],description:"Iterates over all elements of a matrix/array, and executes the given callback function.",examples:["numberOfPets = {}","addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;",'forEach(["Dog","Cat","Cat"], addPet)',"numberOfPets"],seealso:["map","sort","filter"]},getMatrixDataTypeDocs={name:"getMatrixDataType",category:"Matrix",syntax:["getMatrixDataType(x)"],description:'Find the data type of all elements in a matrix or array, for example "number" if all items are a number and "Complex" if all values are complex numbers. If a matrix contains more than one data type, it will return "mixed".',examples:["getMatrixDataType([1, 2, 3])","getMatrixDataType([[5 cm], [2 inch]])",'getMatrixDataType([1, "text"])',"getMatrixDataType([1, bignumber(4)])"],seealso:["matrix","sparse","typeOf"]},identityDocs={name:"identity",category:"Matrix",syntax:["identity(n)","identity(m, n)","identity([m, n])"],description:"Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.",examples:["identity(3)","identity(3, 5)","a = [1, 2, 3; 4, 5, 6]","identity(size(a))"],seealso:["concat","det","diag","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]},invDocs={name:"inv",category:"Matrix",syntax:["inv(x)"],description:"Calculate the inverse of a matrix",examples:["inv([1, 2; 3, 4])","inv(4)","1 / 4"],seealso:["concat","det","diag","identity","ones","range","size","squeeze","subset","trace","transpose","zeros"]},pinvDocs={name:"pinv",category:"Matrix",syntax:["pinv(x)"],description:"Calculate the Moore–Penrose inverse of a matrix",examples:["pinv([1, 2; 3, 4])","pinv([[1, 0], [0, 1], [0, 1]])","pinv(4)"],seealso:["inv"]},kronDocs={name:"kron",category:"Matrix",syntax:["kron(x, y)"],description:"Calculates the kronecker product of 2 matrices or vectors.",examples:["kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])","kron([1,1], [2,3,4])"],seealso:["multiply","dot","cross"]},mapDocs={name:"map",category:"Matrix",syntax:["map(x, callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.",examples:["map([1, 2, 3], square)"],seealso:["filter","forEach"]},matrixFromColumnsDocs={name:"matrixFromColumns",category:"Matrix",syntax:["math.matrixFromColumns(...arr)","math.matrixFromColumns(row1, row2)","math.matrixFromColumns(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual columns.",examples:["matrixFromColumns([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromRows","matrixFromFunction","zeros"]},matrixFromFunctionDocs={name:"matrixFromFunction",category:"Matrix",syntax:["math.matrixFromFunction(size, fn)","math.matrixFromFunction(size, fn, format)","math.matrixFromFunction(size, fn, format, datatype)","math.matrixFromFunction(size, format, fn)","math.matrixFromFunction(size, format, datatype, fn)"],description:"Create a matrix by evaluating a generating function at each index.",examples:["f(I) = I[1] - I[2]","matrixFromFunction([3,3], f)","g(I) = I[1] - I[2] == 1 ? 4 : 0",'matrixFromFunction([100, 100], "sparse", g)',"matrixFromFunction([5], random)"],seealso:["matrix","matrixFromRows","matrixFromColumns","zeros"]},matrixFromRowsDocs={name:"matrixFromRows",category:"Matrix",syntax:["math.matrixFromRows(...arr)","math.matrixFromRows(row1, row2)","math.matrixFromRows(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual rows.",examples:["matrixFromRows([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromColumns","matrixFromFunction","zeros"]},onesDocs={name:"ones",category:"Matrix",syntax:["ones(m)","ones(m, n)","ones(m, n, p, ...)","ones([m])","ones([m, n])","ones([m, n, p, ...])"],description:"Create a matrix containing ones.",examples:["ones(3)","ones(3, 5)","ones([2,3]) * 4.5","a = [1, 2, 3; 4, 5, 6]","ones(size(a))"],seealso:["concat","det","diag","identity","inv","range","size","squeeze","subset","trace","transpose","zeros"]},partitionSelectDocs={name:"partitionSelect",category:"Matrix",syntax:["partitionSelect(x, k)","partitionSelect(x, k, compare)"],description:"Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.",examples:["partitionSelect([5, 10, 1], 2)",'partitionSelect(["C", "B", "A", "D"], 1)'],seealso:["sort"]},rangeDocs={name:"range",category:"Type",syntax:["start:end","start:step:end","range(start, end)","range(start, end, step)","range(string)"],description:"Create a range. Lower bound of the range is included, upper bound is excluded.",examples:["1:5","3:-1:-3","range(3, 7)","range(0, 12, 2)",'range("4:10")',"a = [1, 2, 3, 4; 5, 6, 7, 8]","a[1:2, 1:2]"],seealso:["concat","det","diag","identity","inv","ones","size","squeeze","subset","trace","transpose","zeros"]},reshapeDocs={name:"reshape",category:"Matrix",syntax:["reshape(x, sizes)"],description:"Reshape a multi dimensional array to fit the specified dimensions.",examples:["reshape([1, 2, 3, 4, 5, 6], [2, 3])","reshape([[1, 2], [3, 4]], [1, 4])","reshape([[1, 2], [3, 4]], [4])"],seealso:["size","squeeze","resize"]},resizeDocs={name:"resize",category:"Matrix",syntax:["resize(x, size)","resize(x, size, defaultValue)"],description:"Resize a matrix.",examples:["resize([1,2,3,4,5], [3])","resize([1,2,3], [5])","resize([1,2,3], [5], -1)","resize(2, [2, 3])",'resize("hello", [8], "!")'],seealso:["size","subset","squeeze","reshape"]},rotateDocs={name:"rotate",category:"Matrix",syntax:["rotate(w, theta)","rotate(w, theta, v)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotate([1, 0], math.pi / 2)",'rotate(matrix([1, 0]), unit("35deg"))','rotate([1, 0, 0], unit("90deg"), [0, 0, 1])','rotate(matrix([1, 0, 0]), unit("90deg"), matrix([0, 0, 1]))'],seealso:["matrix","rotationMatrix"]},rotationMatrixDocs={name:"rotationMatrix",category:"Matrix",syntax:["rotationMatrix(theta)","rotationMatrix(theta, v)","rotationMatrix(theta, v, format)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotationMatrix(pi / 2)",'rotationMatrix(unit("45deg"), [0, 0, 1])','rotationMatrix(1, matrix([0, 0, 1]), "sparse")'],seealso:["cos","sin"]},rowDocs={name:"row",category:"Matrix",syntax:["row(x, index)"],description:"Return a row from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","row(A, 1)","row(A, 2)"],seealso:["column","matrixFromRows"]},sizeDocs={name:"size",category:"Matrix",syntax:["size(x)"],description:"Calculate the size of a matrix.",examples:["size(2.3)",'size("hello world")',"a = [1, 2; 3, 4; 5, 6]","size(a)","size(1:6)"],seealso:["concat","count","det","diag","identity","inv","ones","range","squeeze","subset","trace","transpose","zeros"]},sortDocs={name:"sort",category:"Matrix",syntax:["sort(x)","sort(x, compare)"],description:'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',examples:["sort([5, 10, 1])",'sort(["C", "B", "A", "D"])',"sortByLength(a, b) = size(a)[1] - size(b)[1]",'sort(["Langdon", "Tom", "Sara"], sortByLength)','sort(["10", "1", "2"], "natural")'],seealso:["map","filter","forEach"]},squeezeDocs={name:"squeeze",category:"Matrix",syntax:["squeeze(x)"],description:"Remove inner and outer singleton dimensions from a matrix.",examples:["a = zeros(3,2,1)","size(squeeze(a))","b = zeros(1,1,3)","size(squeeze(b))"],seealso:["concat","det","diag","identity","inv","ones","range","size","subset","trace","transpose","zeros"]},subsetDocs={name:"subset",category:"Matrix",syntax:["value(index)","value(index) = replacement","subset(value, [index])","subset(value, [index], replacement)"],description:"Get or set a subset of the entries of a matrix or characters of a string. Indexes are one-based. There should be one index specification for each dimension of the target. Each specification can be a single index, a list of indices, or a range in colon notation `l:u`. In a range, both the lower bound l and upper bound u are included; and if a bound is omitted it defaults to the most extreme valid value. The cartesian product of the indices specified in each dimension determines the target of the operation.",examples:["d = [1, 2; 3, 4]","e = []","e[1, 1:2] = [5, 6]","e[2, :] = [7, 8]","f = d * e","f[2, 1]","f[:, 1]","f[[1,2], [1,3]] = [9, 10; 11, 12]","f"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","trace","transpose","zeros"]},traceDocs={name:"trace",category:"Matrix",syntax:["trace(A)"],description:"Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.",examples:["A = [1, 2, 3; -1, 2, 3; 2, 0, 3]","trace(A)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","transpose","zeros"]},transposeDocs={name:"transpose",category:"Matrix",syntax:["x'","transpose(x)"],description:"Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","transpose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]},zerosDocs={name:"zeros",category:"Matrix",syntax:["zeros(m)","zeros(m, n)","zeros(m, n, p, ...)","zeros([m])","zeros([m, n])","zeros([m, n, p, ...])"],description:"Create a matrix containing zeros.",examples:["zeros(3)","zeros(3, 5)","a = [1, 2, 3; 4, 5, 6]","zeros(size(a))"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose"]},fftDocs={name:"fft",category:"Matrix",syntax:["fft(x)"],description:"Calculate N-dimensional fourier transform",examples:["fft([[1, 0], [1, 0]])"],seealso:["ifft"]},ifftDocs={name:"ifft",category:"Matrix",syntax:["ifft(x)"],description:"Calculate N-dimensional inverse fourier transform",examples:["ifft([[2, 2], [0, 0]])"],seealso:["fft"]},combinationsDocs={name:"combinations",category:"Probability",syntax:["combinations(n, k)"],description:"Compute the number of combinations of n items taken k at a time",examples:["combinations(7, 5)"],seealso:["combinationsWithRep","permutations","factorial"]},combinationsWithRepDocs={name:"combinationsWithRep",category:"Probability",syntax:["combinationsWithRep(n, k)"],description:"Compute the number of combinations of n items taken k at a time with replacements.",examples:["combinationsWithRep(7, 5)"],seealso:["combinations","permutations","factorial"]},factorialDocs={name:"factorial",category:"Probability",syntax:["n!","factorial(n)"],description:"Compute the factorial of a value",examples:["5!","5 * 4 * 3 * 2 * 1","3!"],seealso:["combinations","combinationsWithRep","permutations","gamma"]},gammaDocs={name:"gamma",category:"Probability",syntax:["gamma(n)"],description:"Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.",examples:["gamma(4)","3!","gamma(1/2)","sqrt(pi)"],seealso:["factorial"]},lgammaDocs={name:"lgamma",category:"Probability",syntax:["lgamma(n)"],description:"Logarithm of the gamma function for real, positive numbers and complex numbers, using Lanczos approximation for numbers and Stirling series for complex numbers.",examples:["lgamma(4)","lgamma(1/2)","lgamma(math.i)","lgamma(complex(1.1, 2))"],seealso:["gamma"]},kldivergenceDocs={name:"kldivergence",category:"Probability",syntax:["kldivergence(x, y)"],description:"Calculate the Kullback-Leibler (KL) divergence between two distributions.",examples:["kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])"],seealso:[]},multinomialDocs={name:"multinomial",category:"Probability",syntax:["multinomial(A)"],description:"Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.",examples:["multinomial([1, 2, 1])"],seealso:["combinations","factorial"]},permutationsDocs={name:"permutations",category:"Probability",syntax:["permutations(n)","permutations(n, k)"],description:"Compute the number of permutations of n items taken k at a time",examples:["permutations(5)","permutations(5, 3)"],seealso:["combinations","combinationsWithRep","factorial"]},pickRandomDocs={name:"pickRandom",category:"Probability",syntax:["pickRandom(array)","pickRandom(array, number)","pickRandom(array, weights)","pickRandom(array, number, weights)","pickRandom(array, weights, number)"],description:"Pick a random entry from a given array.",examples:["pickRandom(0:10)","pickRandom([1, 3, 1, 6])","pickRandom([1, 3, 1, 6], 2)","pickRandom([1, 3, 1, 6], [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)"],seealso:["random","randomInt"]},randomDocs={name:"random",category:"Probability",syntax:["random()","random(max)","random(min, max)","random(size)","random(size, max)","random(size, min, max)"],description:"Return a random number.",examples:["random()","random(10, 20)","random([2, 3])"],seealso:["pickRandom","randomInt"]},randomIntDocs={name:"randomInt",category:"Probability",syntax:["randomInt(max)","randomInt(min, max)","randomInt(size)","randomInt(size, max)","randomInt(size, min, max)"],description:"Return a random integer number",examples:["randomInt(10, 20)","randomInt([2, 3], 10)"],seealso:["pickRandom","random"]},compareDocs={name:"compare",category:"Relational",syntax:["compare(x, y)"],description:"Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compare(2, 3)","compare(3, 2)","compare(2, 2)","compare(5cm, 40mm)","compare(2, [1, 2, 3])"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compareNatural","compareText"]},compareNaturalDocs={name:"compareNatural",category:"Relational",syntax:["compareNatural(x, y)"],description:"Compare two values of any type in a deterministic, natural way. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compareNatural(2, 3)","compareNatural(3, 2)","compareNatural(2, 2)","compareNatural(5cm, 40mm)",'compareNatural("2", "10")',"compareNatural(2 + 3i, 2 + 4i)","compareNatural([1, 2, 4], [1, 2, 3])","compareNatural([1, 5], [1, 2, 3])","compareNatural([1, 2], [1, 2])","compareNatural({a: 2}, {a: 4})"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare","compareText"]},compareTextDocs={name:"compareText",category:"Relational",syntax:["compareText(x, y)"],description:"Compare two strings lexically. Comparison is case sensitive. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:['compareText("B", "A")','compareText("A", "B")','compareText("A", "A")','compareText("2", "10")','compare("2", "10")',"compare(2, 10)",'compareNatural("2", "10")','compareText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural"]},deepEqualDocs={name:"deepEqual",category:"Relational",syntax:["deepEqual(x, y)"],description:"Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.",examples:["deepEqual([1,3,4], [1,3,4])","deepEqual([1,3,4], [1,3])"],seealso:["equal","unequal","smaller","larger","smallerEq","largerEq","compare"]},equalDocs={name:"equal",category:"Relational",syntax:["x == y","equal(x, y)"],description:"Check equality of two values. Returns true if the values are equal, and false if not.",examples:["2+2 == 3","2+2 == 4","a = 3.2","b = 6-2.8","a == b","50cm == 0.5m"],seealso:["unequal","smaller","larger","smallerEq","largerEq","compare","deepEqual","equalText"]},equalTextDocs={name:"equalText",category:"Relational",syntax:["equalText(x, y)"],description:"Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.",examples:['equalText("Hello", "Hello")','equalText("a", "A")','equal("2e3", "2000")','equalText("2e3", "2000")','equalText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural","compareText","equal"]},largerDocs={name:"larger",category:"Relational",syntax:["x > y","larger(x, y)"],description:"Check if value x is larger than y. Returns true if x is larger than y, and false if not.",examples:["2 > 3","5 > 2*2","a = 3.3","b = 6-2.8","(a > b)","(b < a)","5 cm > 2 inch"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare"]},largerEqDocs={name:"largerEq",category:"Relational",syntax:["x >= y","largerEq(x, y)"],description:"Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.",examples:["2 >= 1+1","2 > 1+1","a = 3.2","b = 6-2.8","(a >= b)"],seealso:["equal","unequal","smallerEq","smaller","compare"]},smallerDocs={name:"smaller",category:"Relational",syntax:["x < y","smaller(x, y)"],description:"Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.",examples:["2 < 3","5 < 2*2","a = 3.3","b = 6-2.8","(a < b)","5 cm < 2 inch"],seealso:["equal","unequal","larger","smallerEq","largerEq","compare"]},smallerEqDocs={name:"smallerEq",category:"Relational",syntax:["x <= y","smallerEq(x, y)"],description:"Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.",examples:["2 <= 1+1","2 < 1+1","a = 3.2","b = 6-2.8","(a <= b)"],seealso:["equal","unequal","larger","smaller","largerEq","compare"]},unequalDocs={name:"unequal",category:"Relational",syntax:["x != y","unequal(x, y)"],description:"Check unequality of two values. Returns true if the values are unequal, and false if they are equal.",examples:["2+2 != 3","2+2 != 4","a = 3.2","b = 6-2.8","a != b","50cm != 0.5m","5 cm != 2 inch"],seealso:["equal","smaller","larger","smallerEq","largerEq","compare","deepEqual"]},setCartesianDocs={name:"setCartesian",category:"Set",syntax:["setCartesian(set1, set2)"],description:"Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays and the values will be sorted in ascending order before the operation.",examples:["setCartesian([1, 2], [3, 4])"],seealso:["setUnion","setIntersect","setDifference","setPowerset"]},setDifferenceDocs={name:"setDifference",category:"Set",syntax:["setDifference(set1, set2)"],description:"Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setDifference([1, 2, 3, 4], [3, 4, 5, 6])","setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setSymDifference"]},setDistinctDocs={name:"setDistinct",category:"Set",syntax:["setDistinct(set)"],description:"Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setDistinct([1, 1, 1, 2, 2, 3])"],seealso:["setMultiplicity"]},setIntersectDocs={name:"setIntersect",category:"Set",syntax:["setIntersect(set1, set2)"],description:"Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIntersect([1, 2, 3, 4], [3, 4, 5, 6])","setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setDifference"]},setIsSubsetDocs={name:"setIsSubset",category:"Set",syntax:["setIsSubset(set1, set2)"],description:"Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIsSubset([1, 2], [3, 4, 5, 6])","setIsSubset([3, 4], [3, 4, 5, 6])"],seealso:["setUnion","setIntersect","setDifference"]},setMultiplicityDocs={name:"setMultiplicity",category:"Set",syntax:["setMultiplicity(element, set)"],description:"Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setMultiplicity(1, [1, 2, 2, 4])","setMultiplicity(2, [1, 2, 2, 4])"],seealso:["setDistinct","setSize"]},setPowersetDocs={name:"setPowerset",category:"Set",syntax:["setPowerset(set)"],description:"Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setPowerset([1, 2, 3])"],seealso:["setCartesian"]},setSizeDocs={name:"setSize",category:"Set",syntax:["setSize(set)","setSize(set, unique)"],description:'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.',examples:["setSize([1, 2, 2, 4])","setSize([1, 2, 2, 4], true)"],seealso:["setUnion","setIntersect","setDifference"]},setSymDifferenceDocs={name:"setSymDifference",category:"Set",syntax:["setSymDifference(set1, set2)"],description:"Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])","setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setDifference"]},setUnionDocs={name:"setUnion",category:"Set",syntax:["setUnion(set1, set2)"],description:"Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setUnion([1, 2, 3, 4], [3, 4, 5, 6])","setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setIntersect","setDifference"]},erfDocs={name:"erf",category:"Special",syntax:["erf(x)"],description:"Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x",examples:["erf(0.2)","erf(-0.5)","erf(4)"],seealso:[]},madDocs={name:"mad",category:"Statistics",syntax:["mad(a, b, c, ...)","mad(A)"],description:"Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.",examples:["mad(10, 20, 30)","mad([1, 2, 3])"],seealso:["mean","median","std","abs"]},maxDocs={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dim)"],description:"Compute the maximum value of a list of values.",examples:["max(2, 3, 4, 1)","max([2, 3, 4, 1])","max([2, 5; 4, 3])","max([2, 5; 4, 3], 1)","max([2, 5; 4, 3], 2)","max(2.7, 7.1, -4.5, 2.0, 4.1)","min(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["mean","median","min","prod","std","sum","variance"]},meanDocs={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dim)"],description:"Compute the arithmetic mean of a list of values.",examples:["mean(2, 3, 4, 1)","mean([2, 3, 4, 1])","mean([2, 5; 4, 3])","mean([2, 5; 4, 3], 1)","mean([2, 5; 4, 3], 2)","mean([1.0, 2.7, 3.2, 4.0])"],seealso:["max","median","min","prod","std","sum","variance"]},medianDocs={name:"median",category:"Statistics",syntax:["median(a, b, c, ...)","median(A)"],description:"Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.",examples:["median(5, 2, 7)","median([3, -1, 5, 7])"],seealso:["max","mean","min","prod","std","sum","variance","quantileSeq"]},minDocs={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dim)"],description:"Compute the minimum value of a list of values.",examples:["min(2, 3, 4, 1)","min([2, 3, 4, 1])","min([2, 5; 4, 3])","min([2, 5; 4, 3], 1)","min([2, 5; 4, 3], 2)","min(2.7, 7.1, -4.5, 2.0, 4.1)","max(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["max","mean","median","prod","std","sum","variance"]},modeDocs={name:"mode",category:"Statistics",syntax:["mode(a, b, c, ...)","mode(A)","mode(A, a, b, B, c, ...)"],description:"Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.",examples:["mode(2, 1, 4, 3, 1)","mode([1, 2.7, 3.2, 4, 2.7])","mode(1, 4, 6, 1, 6)"],seealso:["max","mean","min","median","prod","std","sum","variance"]},prodDocs={name:"prod",category:"Statistics",syntax:["prod(a, b, c, ...)","prod(A)"],description:"Compute the product of all values.",examples:["prod(2, 3, 4)","prod([2, 3, 4])","prod([2, 5; 4, 3])"],seealso:["max","mean","min","median","min","std","sum","variance"]},quantileSeqDocs={name:"quantileSeq",category:"Statistics",syntax:["quantileSeq(A, prob[, sorted])","quantileSeq(A, [prob1, prob2, ...][, sorted])","quantileSeq(A, N[, sorted])"],description:"Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probablity are: Number, BigNumber. \n\nIn case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.",examples:["quantileSeq([3, -1, 5, 7], 0.5)","quantileSeq([3, -1, 5, 7], [1/3, 2/3])","quantileSeq([3, -1, 5, 7], 2)","quantileSeq([-1, 3, 5, 7], 0.5, true)"],seealso:["mean","median","min","max","prod","std","sum","variance"]},stdDocs={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, normalization)"],description:'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["std(2, 4, 6)","std([2, 4, 6, 8])",'std([2, 4, 6, 8], "uncorrected")','std([2, 4, 6, 8], "biased")',"std([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","prod","sum","variance"]},cumSumDocs={name:"cumsum",category:"Statistics",syntax:["cumsum(a, b, c, ...)","cumsum(A)"],description:"Compute the cumulative sum of all values.",examples:["cumsum(2, 3, 4, 1)","cumsum([2, 3, 4, 1])","cumsum([1, 2; 3, 4])","cumsum([1, 2; 3, 4], 1)","cumsum([1, 2; 3, 4], 2)"],seealso:["max","mean","median","min","prod","std","sum","variance"]},sumDocs={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)"],description:"Compute the sum of all values.",examples:["sum(2, 3, 4, 1)","sum([2, 3, 4, 1])","sum([2, 5; 4, 3])"],seealso:["max","mean","median","min","prod","std","sum","variance"]},varianceDocs={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, normalization)"],description:'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["variance(2, 4, 6)","variance([2, 4, 6, 8])",'variance([2, 4, 6, 8], "uncorrected")','variance([2, 4, 6, 8], "biased")',"variance([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","std","sum"]},acosDocs={name:"acos",category:"Trigonometry",syntax:["acos(x)"],description:"Compute the inverse cosine of a value in radians.",examples:["acos(0.5)","acos(cos(2.3))"],seealso:["cos","atan","asin"]},acoshDocs={name:"acosh",category:"Trigonometry",syntax:["acosh(x)"],description:"Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.",examples:["acosh(1.5)"],seealso:["cosh","asinh","atanh"]},acotDocs={name:"acot",category:"Trigonometry",syntax:["acot(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acot(0.5)","acot(cot(0.5))","acot(2)"],seealso:["cot","atan"]},acothDocs={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.",examples:["acoth(2)","acoth(0.5)"],seealso:["acsch","asech"]},acscDocs={name:"acsc",category:"Trigonometry",syntax:["acsc(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acsc(2)","acsc(csc(0.5))","acsc(0.5)"],seealso:["csc","asin","asec"]},acschDocs={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]},asecDocs={name:"asec",category:"Trigonometry",syntax:["asec(x)"],description:"Calculate the inverse secant of a value.",examples:["asec(0.5)","asec(sec(0.5))","asec(2)"],seealso:["acos","acot","acsc"]},asechDocs={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]},asinDocs={name:"asin",category:"Trigonometry",syntax:["asin(x)"],description:"Compute the inverse sine of a value in radians.",examples:["asin(0.5)","asin(sin(0.5))"],seealso:["sin","acos","atan"]},asinhDocs={name:"asinh",category:"Trigonometry",syntax:["asinh(x)"],description:"Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.",examples:["asinh(0.5)"],seealso:["acosh","atanh"]},atanDocs={name:"atan",category:"Trigonometry",syntax:["atan(x)"],description:"Compute the inverse tangent of a value in radians.",examples:["atan(0.5)","atan(tan(0.5))"],seealso:["tan","acos","asin"]},atan2Docs={name:"atan2",category:"Trigonometry",syntax:["atan2(y, x)"],description:"Computes the principal value of the arc tangent of y/x in radians.",examples:["atan2(2, 2) / pi","angle = 60 deg in rad","x = cos(angle)","y = sin(angle)","atan2(y, x)"],seealso:["sin","cos","tan"]},atanhDocs={name:"atanh",category:"Trigonometry",syntax:["atanh(x)"],description:"Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.",examples:["atanh(0.5)"],seealso:["acosh","asinh"]},cosDocs={name:"cos",category:"Trigonometry",syntax:["cos(x)"],description:"Compute the cosine of x in radians.",examples:["cos(2)","cos(pi / 4) ^ 2","cos(180 deg)","cos(60 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["acos","sin","tan"]},coshDocs={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]},cotDocs={name:"cot",category:"Trigonometry",syntax:["cot(x)"],description:"Compute the cotangent of x in radians. Defined as 1/tan(x)",examples:["cot(2)","1 / tan(2)"],seealso:["sec","csc","tan"]},cothDocs={name:"coth",category:"Trigonometry",syntax:["coth(x)"],description:"Compute the hyperbolic cotangent of x in radians.",examples:["coth(2)","1 / tanh(2)"],seealso:["sech","csch","tanh"]},cscDocs={name:"csc",category:"Trigonometry",syntax:["csc(x)"],description:"Compute the cosecant of x in radians. Defined as 1/sin(x)",examples:["csc(2)","1 / sin(2)"],seealso:["sec","cot","sin"]},cschDocs={name:"csch",category:"Trigonometry",syntax:["csch(x)"],description:"Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)",examples:["csch(2)","1 / sinh(2)"],seealso:["sech","coth","sinh"]},secDocs={name:"sec",category:"Trigonometry",syntax:["sec(x)"],description:"Compute the secant of x in radians. Defined as 1/cos(x)",examples:["sec(2)","1 / cos(2)"],seealso:["cot","csc","cos"]},sechDocs={name:"sech",category:"Trigonometry",syntax:["sech(x)"],description:"Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)",examples:["sech(2)","1 / cosh(2)"],seealso:["coth","csch","cosh"]},sinDocs={name:"sin",category:"Trigonometry",syntax:["sin(x)"],description:"Compute the sine of x in radians.",examples:["sin(2)","sin(pi / 4) ^ 2","sin(90 deg)","sin(30 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["asin","cos","tan"]},sinhDocs={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]},tanDocs={name:"tan",category:"Trigonometry",syntax:["tan(x)"],description:"Compute the tangent of x in radians.",examples:["tan(0.5)","sin(0.5) / cos(0.5)","tan(pi / 4)","tan(45 deg)"],seealso:["atan","sin","cos"]},tanhDocs={name:"tanh",category:"Trigonometry",syntax:["tanh(x)"],description:"Compute the hyperbolic tangent of x in radians.",examples:["tanh(0.5)","sinh(0.5) / cosh(0.5)"],seealso:["sinh","cosh"]},toDocs={name:"to",category:"Units",syntax:["x to unit","to(x, unit)"],description:"Change the unit of a value.",examples:["5 inch to cm","3.2kg to g","16 bytes in bits"],seealso:[]},binDocs={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]},cloneDocs={name:"clone",category:"Utils",syntax:["clone(x)"],description:"Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices",examples:["clone(3.5)","clone(2 - 4i)","clone(45 deg)","clone([1, 2; 3, 4])",'clone("hello world")'],seealso:[]},formatDocs={name:"format",category:"Utils",syntax:["format(value)","format(value, precision)"],description:"Format a value of any type as string.",examples:["format(2.3)","format(3 - 4i)","format([])","format(pi, 3)"],seealso:["print"]},hasNumericValueDocs={name:"hasNumericValue",category:"Utils",syntax:["hasNumericValue(x)"],description:"Test whether a value is an numeric value. In case of a string, true is returned if the string contains a numeric value.",examples:["hasNumericValue(2)",'hasNumericValue("2")','isNumeric("2")',"hasNumericValue(0)","hasNumericValue(bignumber(500))","hasNumericValue(fraction(0.125))","hasNumericValue(2 + 3i)",'hasNumericValue([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","isNumeric"]},hexDocs={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]},isIntegerDocs={name:"isInteger",category:"Utils",syntax:["isInteger(x)"],description:"Test whether a value is an integer number.",examples:["isInteger(2)","isInteger(3.5)","isInteger([3, 0.5, -2])"],seealso:["isNegative","isNumeric","isPositive","isZero"]},isNaNDocs={name:"isNaN",category:"Utils",syntax:["isNaN(x)"],description:"Test whether a value is NaN (not a number)",examples:["isNaN(2)","isNaN(0 / 0)","isNaN(NaN)","isNaN(Infinity)"],seealso:["isNegative","isNumeric","isPositive","isZero"]},isNegativeDocs={name:"isNegative",category:"Utils",syntax:["isNegative(x)"],description:"Test whether a value is negative: smaller than zero.",examples:["isNegative(2)","isNegative(0)","isNegative(-4)","isNegative([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isPositive","isZero"]},isNumericDocs={name:"isNumeric",category:"Utils",syntax:["isNumeric(x)"],description:"Test whether a value is a numeric value. Returns true when the input is a number, BigNumber, Fraction, or boolean.",examples:["isNumeric(2)",'isNumeric("2")','hasNumericValue("2")',"isNumeric(0)","isNumeric(bignumber(500))","isNumeric(fraction(0.125))","isNumeric(2 + 3i)",'isNumeric([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","hasNumericValue"]},isPositiveDocs={name:"isPositive",category:"Utils",syntax:["isPositive(x)"],description:"Test whether a value is positive: larger than zero.",examples:["isPositive(2)","isPositive(0)","isPositive(-4)","isPositive([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},isPrimeDocs={name:"isPrime",category:"Utils",syntax:["isPrime(x)"],description:"Test whether a value is prime: has no divisors other than itself and one.",examples:["isPrime(3)","isPrime(-2)","isPrime([2, 17, 100])"],seealso:["isInteger","isNumeric","isNegative","isZero"]},isZeroDocs={name:"isZero",category:"Utils",syntax:["isZero(x)"],description:"Test whether a value is zero.",examples:["isZero(2)","isZero(0)","isZero(-4)","isZero([3, 0, -2, 0])"],seealso:["isInteger","isNumeric","isNegative","isPositive"]},numericDocs={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "BigNumber")','numeric("4", "Fraction)','numeric(4, "Fraction")','numeric(fraction(2, 5), "number)'],seealso:["number","fraction","bignumber","string","format"]},octDocs={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]},printDocs={name:"print",category:"Utils",syntax:["print(template, values)","print(template, values, precision)"],description:"Interpolate values into a string template.",examples:['print("Lucy is $age years old", {age: 5})','print("The value of pi is $pi", {pi: pi}, 3)','print("Hello, $user.name!", {user: {name: "John"}})','print("Values: $0, $1, $2", [6, 9, 4])'],seealso:["format"]},typeOfDocs={name:"typeOf",category:"Utils",syntax:["typeOf(x)"],description:"Get the type of a variable.",examples:["typeOf(3.5)","typeOf(2 - 4i)","typeOf(45 deg)",'typeOf("hello world")'],seealso:["getMatrixDataType"]},embeddedDocs={bignumber:bignumberDocs,boolean:booleanDocs,complex:complexDocs,createUnit:createUnitDocs,fraction:fractionDocs,index:indexDocs,matrix:matrixDocs,number:numberDocs,sparse:sparseDocs,splitUnit:splitUnitDocs,string:stringDocs,unit:unitDocs,e:eDocs,E:eDocs,false:falseDocs,i:iDocs,Infinity:InfinityDocs,LN2:LN2Docs,LN10:LN10Docs,LOG2E:LOG2EDocs,LOG10E:LOG10EDocs,NaN:NaNDocs,null:nullDocs,pi:piDocs,PI:piDocs,phi:phiDocs,SQRT1_2:SQRT12Docs,SQRT2:SQRT2Docs,tau:tauDocs,true:trueDocs,version:versionDocs,speedOfLight:{description:"Speed of light in vacuum",examples:["speedOfLight"]},gravitationConstant:{description:"Newtonian constant of gravitation",examples:["gravitationConstant"]},planckConstant:{description:"Planck constant",examples:["planckConstant"]},reducedPlanckConstant:{description:"Reduced Planck constant",examples:["reducedPlanckConstant"]},magneticConstant:{description:"Magnetic constant (vacuum permeability)",examples:["magneticConstant"]},electricConstant:{description:"Electric constant (vacuum permeability)",examples:["electricConstant"]},vacuumImpedance:{description:"Characteristic impedance of vacuum",examples:["vacuumImpedance"]},coulomb:{description:"Coulomb's constant",examples:["coulomb"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Borh magneton",examples:["bohrMagneton"]},conductanceQuantum:{description:"Conductance quantum",examples:["conductanceQuantum"]},inverseConductanceQuantum:{description:"Inverse conductance quantum",examples:["inverseConductanceQuantum"]},magneticFluxQuantum:{description:"Magnetic flux quantum",examples:["magneticFluxQuantum"]},nuclearMagneton:{description:"Nuclear magneton",examples:["nuclearMagneton"]},klitzing:{description:"Von Klitzing constant",examples:["klitzing"]},bohrRadius:{description:"Borh radius",examples:["bohrRadius"]},classicalElectronRadius:{description:"Classical electron radius",examples:["classicalElectronRadius"]},electronMass:{description:"Electron mass",examples:["electronMass"]},fermiCoupling:{description:"Fermi coupling constant",examples:["fermiCoupling"]},fineStructure:{description:"Fine-structure constant",examples:["fineStructure"]},hartreeEnergy:{description:"Hartree energy",examples:["hartreeEnergy"]},protonMass:{description:"Proton mass",examples:["protonMass"]},deuteronMass:{description:"Deuteron Mass",examples:["deuteronMass"]},neutronMass:{description:"Neutron mass",examples:["neutronMass"]},quantumOfCirculation:{description:"Quantum of circulation",examples:["quantumOfCirculation"]},rydberg:{description:"Rydberg constant",examples:["rydberg"]},thomsonCrossSection:{description:"Thomson cross section",examples:["thomsonCrossSection"]},weakMixingAngle:{description:"Weak mixing angle",examples:["weakMixingAngle"]},efimovFactor:{description:"Efimov factor",examples:["efimovFactor"]},atomicMass:{description:"Atomic mass constant",examples:["atomicMass"]},avogadro:{description:"Avogadro's number",examples:["avogadro"]},boltzmann:{description:"Boltzmann constant",examples:["boltzmann"]},faraday:{description:"Faraday constant",examples:["faraday"]},firstRadiation:{description:"First radiation constant",examples:["firstRadiation"]},loschmidt:{description:"Loschmidt constant at T=273.15 K and p=101.325 kPa",examples:["loschmidt"]},gasConstant:{description:"Gas constant",examples:["gasConstant"]},molarPlanckConstant:{description:"Molar Planck constant",examples:["molarPlanckConstant"]},molarVolume:{description:"Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa",examples:["molarVolume"]},sackurTetrode:{description:"Sackur-Tetrode constant at T=1 K and p=101.325 kPa",examples:["sackurTetrode"]},secondRadiation:{description:"Second radiation constant",examples:["secondRadiation"]},stefanBoltzmann:{description:"Stefan-Boltzmann constant",examples:["stefanBoltzmann"]},wienDisplacement:{description:"Wien displacement law constant",examples:["wienDisplacement"]},molarMass:{description:"Molar mass constant",examples:["molarMass"]},molarMassC12:{description:"Molar mass constant of carbon-12",examples:["molarMassC12"]},gravity:{description:"Standard acceleration of gravity (standard acceleration of free-fall on Earth)",examples:["gravity"]},planckLength:{description:"Planck length",examples:["planckLength"]},planckMass:{description:"Planck mass",examples:["planckMass"]},planckTime:{description:"Planck time",examples:["planckTime"]},planckCharge:{description:"Planck charge",examples:["planckCharge"]},planckTemperature:{description:"Planck temperature",examples:["planckTemperature"]},derivative:derivativeDocs,lsolve:lsolveDocs,lsolveAll:lsolveAllDocs,lup:lupDocs,lusolve:lusolveDocs,leafCount:leafCountDocs,resolve:resolveDocs,simplify:simplifyDocs,simplifyCore:simplifyCoreDocs,symbolicEqual:symbolicEqualDocs,rationalize:rationalizeDocs,slu:sluDocs,usolve:usolveDocs,usolveAll:usolveAllDocs,qr:qrDocs,abs:absDocs,add:addDocs,cbrt:cbrtDocs,ceil:ceilDocs,cube:cubeDocs,divide:divideDocs,dotDivide:dotDivideDocs,dotMultiply:dotMultiplyDocs,dotPow:dotPowDocs,exp:expDocs,expm:expmDocs,expm1:expm1Docs,fix:fixDocs,floor:floorDocs,gcd:gcdDocs,hypot:hypotDocs,lcm:lcmDocs,log:logDocs,log2:log2Docs,log1p:log1pDocs,log10:log10Docs,mod:modDocs,multiply:multiplyDocs,norm:normDocs,nthRoot:nthRootDocs,nthRoots:nthRootsDocs,pow:powDocs,round:roundDocs,sign:signDocs,sqrt:sqrtDocs,sqrtm:sqrtmDocs,square:squareDocs,subtract:subtractDocs,unaryMinus:unaryMinusDocs,unaryPlus:unaryPlusDocs,xgcd:xgcdDocs,invmod:invmodDocs,bitAnd:bitAndDocs,bitNot:bitNotDocs,bitOr:bitOrDocs,bitXor:bitXorDocs,leftShift:leftShiftDocs,rightArithShift:rightArithShiftDocs,rightLogShift:rightLogShiftDocs,bellNumbers:bellNumbersDocs,catalan:catalanDocs,composition:compositionDocs,stirlingS2:stirlingS2Docs,config:configDocs,import:importDocs,typed:typedDocs,arg:argDocs,conj:conjDocs,re:reDocs,im:imDocs,evaluate:evaluateDocs,help:helpDocs,distance:distanceDocs,intersect:intersectDocs,and:andDocs,not:notDocs,or:orDocs,xor:xorDocs,concat:concatDocs,count:countDocs,cross:crossDocs,column:columnDocs,ctranspose:ctransposeDocs,det:detDocs,diag:diagDocs,diff:diffDocs,dot:dotDocs,getMatrixDataType:getMatrixDataTypeDocs,identity:identityDocs,filter:filterDocs,flatten:flattenDocs,forEach:forEachDocs,inv:invDocs,pinv:pinvDocs,eigs:eigsDocs,kron:kronDocs,matrixFromFunction:matrixFromFunctionDocs,matrixFromRows:matrixFromRowsDocs,matrixFromColumns:matrixFromColumnsDocs,map:mapDocs,ones:onesDocs,partitionSelect:partitionSelectDocs,range:rangeDocs,resize:resizeDocs,reshape:reshapeDocs,rotate:rotateDocs,rotationMatrix:rotationMatrixDocs,row:rowDocs,size:sizeDocs,sort:sortDocs,squeeze:squeezeDocs,subset:subsetDocs,trace:traceDocs,transpose:transposeDocs,zeros:zerosDocs,fft:fftDocs,ifft:ifftDocs,combinations:combinationsDocs,combinationsWithRep:combinationsWithRepDocs,factorial:factorialDocs,gamma:gammaDocs,kldivergence:kldivergenceDocs,lgamma:lgammaDocs,multinomial:multinomialDocs,permutations:permutationsDocs,pickRandom:pickRandomDocs,random:randomDocs,randomInt:randomIntDocs,compare:compareDocs,compareNatural:compareNaturalDocs,compareText:compareTextDocs,deepEqual:deepEqualDocs,equal:equalDocs,equalText:equalTextDocs,larger:largerDocs,largerEq:largerEqDocs,smaller:smallerDocs,smallerEq:smallerEqDocs,unequal:unequalDocs,setCartesian:setCartesianDocs,setDifference:setDifferenceDocs,setDistinct:setDistinctDocs,setIntersect:setIntersectDocs,setIsSubset:setIsSubsetDocs,setMultiplicity:setMultiplicityDocs,setPowerset:setPowersetDocs,setSize:setSizeDocs,setSymDifference:setSymDifferenceDocs,setUnion:setUnionDocs,erf:erfDocs,cumsum:cumSumDocs,mad:madDocs,max:maxDocs,mean:meanDocs,median:medianDocs,min:minDocs,mode:modeDocs,prod:prodDocs,quantileSeq:quantileSeqDocs,std:stdDocs,sum:sumDocs,variance:varianceDocs,acos:acosDocs,acosh:acoshDocs,acot:acotDocs,acoth:acothDocs,acsc:acscDocs,acsch:acschDocs,asec:asecDocs,asech:asechDocs,asin:asinDocs,asinh:asinhDocs,atan:atanDocs,atanh:atanhDocs,atan2:atan2Docs,cos:cosDocs,cosh:coshDocs,cot:cotDocs,coth:cothDocs,csc:cscDocs,csch:cschDocs,sec:secDocs,sech:sechDocs,sin:sinDocs,sinh:sinhDocs,tan:tanDocs,tanh:tanhDocs,to:toDocs,clone:cloneDocs,format:formatDocs,bin:binDocs,oct:octDocs,hex:hexDocs,isNaN:isNaNDocs,isInteger:isIntegerDocs,isNegative:isNegativeDocs,isNumeric:isNumericDocs,hasNumericValue:hasNumericValueDocs,isPositive:isPositiveDocs,isPrime:isPrimeDocs,isZero:isZeroDocs,print:printDocs,typeOf:typeOfDocs,numeric:numericDocs},name$_="help",dependencies$_=["typed","mathWithTransform","Help"],createHelp=factory(name$_,dependencies$_,(e=>{var{typed:t,mathWithTransform:n,Help:r}=e;return t(name$_,{any:function(e){var t,a=e;if("string"!=typeof e)for(t in n)if(hasOwnProperty$2(n,t)&&e===n[t]){a=t;break}var i=getSafeProperty(embeddedDocs,a);if(!i){var s="function"==typeof a?a.name:a;throw new Error('No documentation found on "'+s+'"')}return new r(i)}})})),name$Z="chain",dependencies$Z=["typed","Chain"],createChain=factory(name$Z,dependencies$Z,(e=>{var{typed:t,Chain:n}=e;return t(name$Z,{"":function(){return new n},any:function(e){return new n(e)}})})),name$Y="det",dependencies$Y=["typed","matrix","subtract","multiply","divideScalar","isZero","unaryMinus"],createDet=factory(name$Y,dependencies$Y,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a,divideScalar:i,isZero:s,unaryMinus:o}=e;return t(name$Y,{any:function(e){return clone$3(e)},"Array | Matrix":function(e){var t;switch((t=isMatrix(e)?e.size():Array.isArray(e)?(e=n(e)).size():[]).length){case 0:return clone$3(e);case 1:if(1===t[0])return clone$3(e.valueOf()[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var l=t[0];if(l===t[1])return function(e,t,n){if(1===t)return clone$3(e[0][0]);if(2===t)return r(a(e[0][0],e[1][1]),a(e[1][0],e[0][1]));for(var l=!1,u=new Array(t).fill(0).map(((e,t)=>t)),c=0;c{var{typed:t,matrix:n,divideScalar:r,addScalar:a,multiply:i,unaryMinus:s,det:o,identity:l,abs:u}=e;return t(name$X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return isMatrix(e)?n([r(1,e.valueOf()[0])]):[r(1,e[0])];throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0],i=t[1];if(a===i)return isMatrix(e)?n(c(e.valueOf(),a,i),e.storage()):c(e,a,i);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return r(1,e)}});function c(e,t,n){var c,p,d,m,h;if(1===t){if(0===(m=e[0][0]))throw Error("Cannot calculate inverse, determinant is zero");return[[r(1,m)]]}if(2===t){var f=o(e);if(0===f)throw Error("Cannot calculate inverse, determinant is zero");return[[r(e[1][1],f),r(s(e[0][1]),f)],[r(s(e[1][0]),f),r(e[0][0],f)]]}var y=e.concat();for(c=0;cv&&(v=u(y[c][b]),N=c),c++;if(0===v)throw Error("Cannot calculate inverse, determinant is zero");(c=N)!==b&&(h=y[b],y[b]=y[c],y[c]=h,h=g[b],g[b]=g[c],g[c]=h);var T=y[b],C=g[b];for(c=0;c{var{typed:t,matrix:n,inv:r,deepEqual:a,equal:i,dotDivide:s,dot:o,ctranspose:l,divideScalar:u,multiply:c,add:p,Complex:d}=e;return t(name$W,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:return f(e)?l(e):1===t[0]?r(e):s(l(e),o(e,e));case 2:if(f(e))return l(e);var a=t[0],i=t[1];if(a===i)try{return r(e)}catch(e){if(!(e instanceof Error&&e.message.match(/Cannot calculate inverse, determinant is zero/)))throw e}return isMatrix(e)?n(m(e.valueOf(),a,i),e.storage()):m(e,a,i);default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return i(e,0)?clone$3(e):u(1,e)}});function m(e,t,n){var{C:a,F:i}=function(e,t,n){var r=function(e,t,n){for(var r=clone$3(e),a=0,i=0;ie.filter(((e,n)=>n!h(o(r[t],r[t]))));return{C:a,F:i}}(e,t,n),u=c(r(c(l(a),a)),l(a)),d=c(l(i),r(c(i,l(i))));return c(d,u)}function h(e){return i(p(e,d(1,1)),p(0,d(1,1)))}function f(e){return a(p(e,d(1,1)),p(c(e,0),d(1,1)))}}));function createComplexEigs(e){var{addScalar:t,subtract:n,flatten:r,multiply:a,multiplyScalar:i,divideScalar:s,sqrt:o,abs:l,bignumber:u,diag:c,inv:p,qr:d,usolve:m,usolveAll:h,equal:f,complex:y,larger:g,smaller:b,matrixFromColumns:v,dot:N}=e;function T(e,r,a,s){var l=t(e,s),u=n(i(e,s),i(r,a)),c=i(l,.5),p=i(o(n(i(l,l),i(4,u))),.5);return[t(c,p),n(c,p)]}function C(e,t,r,a,i,s,o,c){var p="BigNumber"===c,d="Complex"===c,m=p?u(0):d?y(0):0,h=p?u(1):d?y(1):1;if(b(l(r),o))return[[h,m],[m,h]];if(g(l(n(i,s)),o))return[[n(i,a),n(s,a)],[r,r]];var f=n(e,i),v=n(t,i),N=n(r,i),T=n(a,i);return b(l(v),o)?[[f,h],[N,m]]:[[v,m],[T,h]]}function A(e,t){for(var n=0;n=5)return null;for(o=0;;){var l=m(e,i);if(b(E(w(i,[l])),r))break;if(++o>=10)return null;i=D(l)}return i}function S(e,t,n){var r="BigNumber"===n,a="Complex"===n,i=Array(e).fill(0).map((e=>2*Math.random()-1));return r&&(i=i.map((e=>u(e)))),a&&(i=i.map((e=>y(e)))),D(i=w(i,t),n)}function w(e,t){for(var r of t)e=n(e,a(s(N(r,e),N(r,r)),r));return e}function E(e){return l(o(N(e,e)))}function D(e,t){var n="Complex"===t,r="BigNumber"===t?u(1):n?y(1):1;return a(s(r,E(e)),e)}return function(e,o,m,N,S){void 0===S&&(S=!0);var w=function(e,n,r,a,o){var p,d="BigNumber"===a,m="Complex"===a,h=d?u(0):0,v=d?u(1):m?y(1):1,N=d?u(1):1,T=d?u(10):2,C=i(T,T);o&&(p=Array(n).fill(v));for(var A=!1;!A;){A=!0;for(var V=0;V1&&(x=c(Array(v-1).fill(h)))),v-=1,f.pop();for(var I=0;I2&&(x=c(Array(v-2).fill(h)))),v-=2,f.pop(),f.pop();for(var _=0;_+n(l(e),l(t)))),S>100){var M=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+g.join(", "));throw M.values=g,M.vectors=[],M}var P=o?a(V,function(e,t){for(var n=[],r=0;ra(f,e))),E.push(...c.map((e=>r(e))))},M=0;M2&&void 0!==arguments[2]?arguments[2]:t.epsilon,i=arguments.length>3?arguments[3]:void 0;if("number"===i)return function(e,t){for(var n,r=e.length,a=Math.abs(t/r),i=new Array(r),s=0;s=Math.abs(a);){var l=o[0][0],u=o[0][1];e=b(e,n=m(e[l][l],e[u][u],e[l][u]),l,u),i=f(i,n,l,u),o=v(e)}for(var c=C(r,0),p=0;p=a(i);){var u=l[0][0],c=l[0][1];e=g(e,n=h(e[u][u],e[c][c],e[u][c]),u,c),s=y(s,n,u,c),l=N(e)}for(var p=C(r,0),d=0;d{var{config:t,typed:n,matrix:r,addScalar:a,subtract:i,equal:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:p,divideScalar:d,inv:m,bignumber:h,multiply:f,add:y,larger:g,column:b,flatten:v,number:N,complex:T,sqrt:C,diag:A,qr:V,usolve:x,usolveAll:S,im:w,re:E,smaller:D,matrixFromColumns:O,dot:I}=e,R=createRealSymmetric({config:t,addScalar:a,subtract:i,column:b,flatten:v,equal:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:p,inv:m,bignumber:h,complex:T,multiply:f,add:y}),_=createComplexEigs({config:t,addScalar:a,subtract:i,multiply:f,multiplyScalar:p,flatten:v,divideScalar:d,sqrt:C,abs:o,bignumber:h,diag:A,qr:V,inv:m,usolve:x,usolveAll:S,equal:s,complex:T,larger:g,smaller:D,matrixFromColumns:O,dot:I});return n("eigs",{Array:function(e){return M(r(e))},"Array, number|BigNumber":function(e,t){return M(r(e),t)},Matrix:function(e){var{values:t,vectors:n}=M(e);return{values:r(t),vectors:r(n)}},"Matrix, number|BigNumber":function(e,t){var{values:n,vectors:a}=M(e,t);return{values:r(n),vectors:r(a)}}});function M(e,n){void 0===n&&(n=t.epsilon);var r=e.size();if(2!==r.length||r[0]!==r[1])throw new RangeError("Matrix must be square (size: "+format$1(r)+")");var a=e.toArray(),s=r[0];if(function(e,t,n){for(var r=0;r{var{typed:t,abs:n,add:r,identity:a,inv:i,multiply:s}=e;return t(name$U,{Matrix:function(e){var t=e.size();if(2!==t.length||t[0]!==t[1])throw new RangeError("Matrix must be square (size: "+format$1(t)+")");for(var l=t[0],u=function(e){for(var t=e.size()[0],r=0,a=0;a1&&(g=s(g,m),b=-b),h=r(h,s(y=y*(p-v+1)/((2*p-v+1)*v),g)),f=r(f,s(y*b,g));for(var N=s(i(f),h),T=0;T{var{typed:t,abs:n,add:r,multiply:a,sqrt:i,subtract:s,inv:o,size:l,max:u,identity:c}=e,p=1e-6;return t(name$T,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return i(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:if(t[0]===t[1])return function(e){var t,i=0,d=e,m=c(l(e));do{var h=d;if(d=a(.5,r(h,o(m))),m=a(.5,r(m,o(h))),(t=u(n(s(d,h))))>p&&++i>1e3)throw new Error("computing square root of matrix: iterative method could not converge")}while(t>p);return d}(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be at most two dimensional (size: "+format$1(t)+")")}}})})),name$S="divide",dependencies$S=["typed","matrix","multiply","equalScalar","divideScalar","inv"],createDivide=factory(name$S,dependencies$S,(e=>{var{typed:t,matrix:n,multiply:r,equalScalar:a,divideScalar:i,inv:s}=e,o=createAlgorithm11({typed:t,equalScalar:a}),l=createAlgorithm14({typed:t});return t("divide",extend$2({"Array | Matrix, Array | Matrix":function(e,t){return r(e,s(t))},"DenseMatrix, any":function(e,t){return l(e,t,i,!1)},"SparseMatrix, any":function(e,t){return o(e,t,i,!1)},"Array, any":function(e,t){return l(n(e),t,i,!1).valueOf()},"any, Array | Matrix":function(e,t){return r(e,s(t))}},i.signatures))})),name$R="distance",dependencies$R=["typed","addScalar","subtract","divideScalar","multiplyScalar","unaryMinus","sqrt","abs"],createDistance=factory(name$R,dependencies$R,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,unaryMinus:s,sqrt:o,abs:l}=e;return t(name$R,{"Array, Array, Array":function(e,t,n){if(2===e.length&&2===t.length&&2===n.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!c(t))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!c(n))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");var o=i(r(n[1],n[0]),r(t[1],t[0])),l=a(a(o,o),t[0]),u=s(a(o,t[0])),p=e[1];return f(e[0],e[1],l,u,p)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(e,t,n){if(2===Object.keys(e).length&&2===Object.keys(t).length&&2===Object.keys(n).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!c(t))throw new TypeError("Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers");if(!c(n))throw new TypeError("Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"lineOnePtX"in t&&"lineOnePtY"in t&&"lineTwoPtX"in n&&"lineTwoPtY"in n){var o=i(r(n.lineTwoPtY,n.lineTwoPtX),r(t.lineOnePtY,t.lineOnePtX)),l=a(a(o,o),t.lineOnePtX),u=s(a(o,t.lineOnePtX)),p=e.pointX;return f(e.pointX,e.pointY,l,u,p)}throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(e,t){if(2===e.length&&3===t.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!p(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return f(e[0],e[1],t[0],t[1],t[2])}if(3===e.length&&6===t.length){if(!p(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!m(t))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return y(e[0],e[1],e[2],t[0],t[1],t[2],t[3],t[4],t[5])}if(e.length===t.length&&e.length>0){if(!d(e))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!d(t))throw new TypeError("All values of an array should be numbers or BigNumbers");return g(e,t)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(e,t){if(2===Object.keys(e).length&&3===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"xCoeffLine"in t&&"yCoeffLine"in t&&"constant"in t)return f(e.pointX,e.pointY,t.xCoeffLine,t.yCoeffLine,t.constant);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&6===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!m(t))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"x0"in t&&"y0"in t&&"z0"in t&&"a"in t&&"b"in t&&"c"in t)return y(e.pointX,e.pointY,e.pointZ,t.x0,t.y0,t.z0,t.a,t.b,t.c);throw new TypeError("Key names do not match")}if(2===Object.keys(e).length&&2===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!c(t))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointTwoX"in t&&"pointTwoY"in t)return g([e.pointOneX,e.pointOneY],[t.pointTwoX,t.pointTwoY]);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&3===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointOneZ"in e&&"pointTwoX"in t&&"pointTwoY"in t&&"pointTwoZ"in t)return g([e.pointOneX,e.pointOneY,e.pointOneZ],[t.pointTwoX,t.pointTwoY,t.pointTwoZ]);throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},Array:function(e){if(!function(e){if(2===e[0].length&&u(e[0][0])&&u(e[0][1])){if(e.some((e=>2!==e.length||!u(e[0])||!u(e[1]))))return!1}else{if(!(3===e[0].length&&u(e[0][0])&&u(e[0][1])&&u(e[0][2])))return!1;if(e.some((e=>3!==e.length||!u(e[0])||!u(e[1])||!u(e[2]))))return!1}return!0}(e))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return function(e){for(var t=[],n=[],r=[],a=0;a{var{typed:t,config:n,abs:r,add:a,addScalar:i,matrix:s,multiply:o,multiplyScalar:l,divideScalar:u,subtract:c,smaller:p,equalScalar:d,flatten:m,isZero:h,isNumeric:f}=e;return t("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":g,"Matrix, Matrix, Matrix":function(e,t,n){var r=y(e.valueOf(),t.valueOf(),n.valueOf());return null===r?null:s(r)},"Matrix, Matrix, Matrix, Matrix":function(e,t,n,r){var a=g(e.valueOf(),t.valueOf(),n.valueOf(),r.valueOf());return null===a?null:s(a)}});function y(e,t,n){if(e=b(e),t=b(t),n=b(n),!N(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!N(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!function(e){return 4===e.length&&f(e[0])&&f(e[1])&&f(e[2])&&f(e[3])}(n))throw new TypeError("Array with 4 numbers expected as third argument");return function(e,t,n,r,a,s,o,p,d,m){var h=l(e,o),f=l(r,o),y=l(t,p),g=l(a,p),b=l(n,d),v=l(s,d),N=c(c(c(m,h),y),b),T=c(c(c(i(i(f,g),v),h),y),b),C=u(N,T);return[i(e,l(C,c(r,e))),i(t,l(C,c(a,t))),i(n,l(C,c(s,n)))]}(e[0],e[1],e[2],t[0],t[1],t[2],n[0],n[1],n[2],n[3])}function g(e,t,s,m){if(e=b(e),t=b(t),s=b(s),m=b(m),2===e.length){if(!v(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!v(t))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!v(s))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!v(m))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return function(e,t,s,d){var m=e,f=s,y=c(m,t),g=c(f,d),b=c(l(y[0],g[1]),l(g[0],y[1]));if(h(b))return null;if(p(r(b),n.epsilon))return null;var v=l(g[0],m[1]),N=l(g[1],m[0]),T=l(g[0],f[1]),C=l(g[1],f[0]),A=u(i(c(c(v,N),T),C),b);return a(o(y,A),m)}(e,t,s,m)}if(3===e.length){if(!N(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!N(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!N(s))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!N(m))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return function(e,t,n,r,a,s,o,p,m,f,y,g){var b=T(e,o,f,o,t,p,y,p,n,m,g,m),v=T(f,o,r,e,y,p,a,t,g,m,s,n),N=T(e,o,r,e,t,p,a,t,n,m,s,n),C=T(f,o,f,o,y,p,y,p,g,m,g,m),A=T(r,e,r,e,a,t,a,t,s,n,s,n),V=c(l(b,v),l(N,C)),x=c(l(A,C),l(v,v));if(h(x))return null;var S=u(V,x),w=u(i(b,l(S,v)),C),E=i(e,l(S,c(r,e))),D=i(t,l(S,c(a,t))),O=i(n,l(S,c(s,n))),I=i(o,l(w,c(f,o))),R=i(p,l(w,c(y,p))),_=i(m,l(w,c(g,m)));return d(E,I)&&d(D,R)&&d(O,_)?[E,D,O]:null}(e[0],e[1],e[2],t[0],t[1],t[2],s[0],s[1],s[2],m[0],m[1],m[2])}throw new TypeError("Arrays with two or thee dimensional points expected")}function b(e){return 1===e.length?e[0]:e.length>1&&Array.isArray(e[0])&&e.every((e=>Array.isArray(e)&&1===e.length))?m(e):e}function v(e){return 2===e.length&&f(e[0])&&f(e[1])}function N(e){return 3===e.length&&f(e[0])&&f(e[1])&&f(e[2])}function T(e,t,n,r,a,s,o,u,p,d,m,h){var f=l(c(e,t),c(n,r)),y=l(c(a,s),c(o,u)),g=l(c(p,d),c(m,h));return i(i(f,y),g)}})),name$P="sum",dependencies$P=["typed","config","add","numeric"],createSum=factory(name$P,dependencies$P,(e=>{var{typed:t,config:n,add:r,numeric:a}=e;return t(name$P,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){try{return reduce$2(e,t,r)}catch(e){throw improveErrorMessage(e,"sum")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function sum");return i(e)}});function i(e){var t;return deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"sum",e)}})),void 0===t&&(t=a(0,n.number)),"string"==typeof t&&(t=a(t,n.number)),t}})),name$O="cumsum",dependencies$O=["typed","add","unaryPlus"],createCumSum=factory(name$O,dependencies$O,(e=>{var{typed:t,add:n,unaryPlus:r}=e;return t(name$O,{Array:a,Matrix:function(e){return e.create(a(e.valueOf()))},"Array, number | BigNumber":s,"Matrix, number | BigNumber":function(e,t){return e.create(s(e.valueOf(),t))},"...":function(e){if(containsCollections(e))throw new TypeError("All values expected to be scalar in function cumsum");return a(e)}});function a(e){try{return i(e)}catch(e){throw improveErrorMessage(e,name$O)}}function i(e){if(0===e.length)return[];for(var t=[r(e[0])],a=1;a=n.length)throw new IndexError(t,n.length);try{return o(e,t)}catch(e){throw improveErrorMessage(e,name$O)}}function o(e,t){var n,r,a;if(t<=0){var s=e[0][0];if(Array.isArray(s)){for(a=_switch$1(e),r=[],n=0;n{var{typed:t,add:n,divide:r}=e;return t(name$N,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":function(e,t){try{var a=reduce$2(e,t,n),i=Array.isArray(e)?arraySize(e):e.size();return r(a,i[t])}catch(e){throw improveErrorMessage(e,"mean")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function mean");return a(e)}});function a(e){var t,a=0;if(deepForEach(e,(function(e){try{t=void 0===t?e:n(t,e),a++}catch(t){throw improveErrorMessage(t,"mean",e)}})),0===a)throw new Error("Cannot calculate the mean of an empty array");return r(t,a)}})),name$M="median",dependencies$M=["typed","add","divide","compare","partitionSelect"],createMedian=factory(name$M,dependencies$M,(e=>{var{typed:t,add:n,divide:r,compare:a,partitionSelect:i}=e;function s(e){try{var t=(e=flatten$4(e.valueOf())).length;if(0===t)throw new Error("Cannot calculate median of an empty array");if(t%2==0){for(var n=t/2-1,r=i(e,n+1),s=e[n],u=0;u0&&(s=e[u]);return l(s,r)}var c=i(e,(t-1)/2);return o(c)}catch(e){throw improveErrorMessage(e,"median")}}var o=t({"number | BigNumber | Complex | Unit":function(e){return e}}),l=t({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(e,t){return r(n(e,t),2)}});return t(name$M,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("median(A, dim) is not yet supported")},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function median");return s(e)}})})),name$L="mad",dependencies$L=["typed","abs","map","median","subtract"],createMad=factory(name$L,dependencies$L,(e=>{var{typed:t,abs:n,map:r,median:a,subtract:i}=e;return t(name$L,{"Array | Matrix":s,"...":function(e){return s(e)}});function s(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var t=a(e);return a(r(e,(function(e){return n(i(e,t))})))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf("median")?new TypeError(e.message.replace("median","mad")):improveErrorMessage(e,"mad")}}})),DEFAULT_NORMALIZATION="unbiased",name$K="variance",dependencies$K=["typed","add","subtract","multiply","divide","apply","isNaN"],createVariance=factory(name$K,dependencies$K,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o}=e;return t(name$K,{"Array | Matrix":function(e){return l(e,DEFAULT_NORMALIZATION)},"Array | Matrix, string":l,"Array | Matrix, number | BigNumber":function(e,t){return u(e,t,DEFAULT_NORMALIZATION)},"Array | Matrix, number | BigNumber, string":u,"...":function(e){return l(e,DEFAULT_NORMALIZATION)}});function l(e,t){var s,l=0;if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(deepForEach(e,(function(e){try{s=void 0===s?e:n(s,e),l++}catch(t){throw improveErrorMessage(t,"variance",e)}})),0===l)throw new Error("Cannot calculate variance of an empty array");var u=i(s,l);if(s=void 0,deepForEach(e,(function(e){var t=r(e,u);s=void 0===s?a(t,t):n(s,a(t,t))})),o(s))return s;switch(t){case"uncorrected":return i(s,l);case"biased":return i(s,l+1);case"unbiased":var c=isBigNumber(s)?s.mul(0):0;return 1===l?c:i(s,l-1);default:throw new Error('Unknown normalization "'+t+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function u(e,t,n){try{if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return s(e,t,(e=>l(e,n)))}catch(e){throw improveErrorMessage(e,"variance")}}})),name$J="quantileSeq",dependencies$J=["typed","add","multiply","partitionSelect","compare"],createQuantileSeq=factory(name$J,dependencies$J,(e=>{var{typed:t,add:n,multiply:r,partitionSelect:a,compare:i}=e;function s(e,t,s){var l=flatten$4(e),u=l.length;if(0===u)throw new Error("Cannot calculate quantile of an empty sequence");if(isNumber$1(t)){var c=t*(u-1),p=c%1;if(0===p){var d=s?l[c]:a(l,c);return o(d),d}var m,h,f=Math.floor(c);if(s)m=l[f],h=l[f+1];else{h=a(l,f+1),m=l[f];for(var y=0;y0&&(m=l[y])}return o(m),o(h),n(r(m,1-p),r(h,p))}var g=t.times(u-1);if(g.isInteger()){g=g.toNumber();var b=s?l[g]:a(l,g);return o(b),b}var v,N,T=g.floor(),C=g.minus(T),A=T.toNumber();if(s)v=l[A],N=l[A+1];else{N=a(l,A+1),v=l[A];for(var V=0;V0&&(v=l[V])}o(v),o(N);var x=new C.constructor(1);return n(r(v,x.minus(C)),r(N,C))}var o=t({"number | BigNumber | Unit":function(e){return e}});return function(e,t,n){var r,a,i;if(arguments.length<2||arguments.length>3)throw new SyntaxError("Function quantileSeq requires two or three parameters");if(isCollection(e)){if("boolean"==typeof(n=n||!1)){if(a=e.valueOf(),isNumber$1(t)){if(t<0)throw new Error("N/prob must be non-negative");if(t<=1)return s(a,t,n);if(t>1){if(!isInteger$1(t))throw new Error("N must be a positive integer");var o=t+1;r=new Array(t);for(var l=0;l4294967295)throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var p=new u(c+1);r=new Array(c);for(var d=0;d1)throw new Error("Probability must be between 0 and 1, inclusive")}else{if(!isBigNumber(h))throw new TypeError("Unexpected type of argument in function quantileSeq");if(i=new h.constructor(1),h.isNegative()||h.gt(i))throw new Error("Probability must be between 0 and 1, inclusive")}r[m]=s(a,h,n)}return r}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}})),name$I="std",dependencies$I=["typed","sqrt","variance"],createStd=factory(name$I,dependencies$I,(e=>{var{typed:t,sqrt:n,variance:r}=e;return t(name$I,{"Array | Matrix":a,"Array | Matrix, string":a,"Array | Matrix, number | BigNumber":a,"Array | Matrix, number | BigNumber, string":a,"...":function(e){return a(e)}});function a(e,t){if(0===e.length)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{return n(r.apply(null,arguments))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf(" variance")?new TypeError(e.message.replace(" variance"," std")):e}}})),name$H="combinations",dependencies$H=["typed"],createCombinations=factory(name$H,dependencies$H,(e=>{var{typed:t}=e;return t(name$H,{"number, number":combinationsNumber,"BigNumber, BigNumber":function(e,t){var n,r,a=e.constructor,i=e.minus(t),s=new a(1);if(!isPositiveInteger$2(e)||!isPositiveInteger$2(t))throw new TypeError("Positive integer value expected in function combinations");if(t.gt(e))throw new TypeError("k must be less than n in function combinations");if(n=s,t.lt(i))for(r=s;r.lte(i);r=r.plus(s))n=n.times(t.plus(r)).dividedBy(r);else for(r=s;r.lte(t);r=r.plus(s))n=n.times(i.plus(r)).dividedBy(r);return n}})}));function isPositiveInteger$2(e){return e.isInteger()&&e.gte(0)}var name$G="combinationsWithRep",dependencies$G=["typed"],createCombinationsWithRep=factory(name$G,dependencies$G,(e=>{var{typed:t}=e;return t(name$G,{"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(e<1)throw new TypeError("k must be less than or equal to n + k - 1");return t{var{typed:t,config:n,multiplyScalar:r,pow:a,BigNumber:i,Complex:s}=e;return t(name$F,{number:gammaNumber,Complex:function(e){if(0===e.im)return this(e.re);if(e.re<.5){var t=new s(1-e.re,-e.im),n=new s(Math.PI*e.re,Math.PI*e.im);return new s(Math.PI).div(n.sin()).div(this(t))}e=new s(e.re-1,e.im);for(var r=new s(gammaP[0],0),a=1;a2;)l+=a-=2,s=s.times(l);return new i(s.toPrecision(i.precision))}})),name$E="lgamma",dependencies$E=["Complex","typed"],createLgamma=factory(name$E,dependencies$E,(e=>{var{Complex:t,typed:n}=e,r=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return n(name$E,{number:lgammaNumber,Complex:function(e){if(e.isNaN())return new t(NaN,NaN);if(0===e.im)return new t(lgammaNumber(e.re),0);if(e.re>=7||Math.abs(e.im)>=7)return a(e);if(e.re<=.1){var n=copysign(6.283185307179586,e.im)*Math.floor(.5*e.re+.25),r=e.mul(Math.PI).sin().log(),s=this(new t(1-e.re,-e.im));return new t(1.1447298858494002,n).sub(r).sub(s)}return e.im>=0?i(e):i(e.conjugate()).conjugate()},BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function a(e){for(var n=e.sub(.5).mul(e.log()).sub(e).add(lnSqrt2PI),a=new t(1,0).div(e),i=a.div(e),s=r[0],o=r[1],l=2*i.re,u=i.re*i.re+i.im*i.im,c=2;c<8;c++){var p=o;o=-u*s+r[c],s=l*s+p}var d=a.mul(i.mul(s).add(o));return n.add(d)}function i(e){var n=0,r=0,i=e;for(e=e.add(1);e.re<=7;){var s=(i=i.mul(e)).im<0?1:0;0!==s&&0===r&&n++,r=s,e=e.add(1)}return a(e).sub(i.log()).sub(new t(0,2*n*Math.PI*1))}})),name$D="factorial",dependencies$D=["typed","gamma"],createFactorial=factory(name$D,dependencies$D,(e=>{var{typed:t,gamma:n}=e;return t(name$D,{number:function(e){if(e<0)throw new Error("Value must be non-negative");return n(e+1)},BigNumber:function(e){if(e.isNegative())throw new Error("Value must be non-negative");return n(e.plus(1))},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$C="kldivergence",dependencies$C=["typed","matrix","divide","sum","multiply","dotDivide","log","isNumeric"],createKldivergence=factory(name$C,dependencies$C,(e=>{var{typed:t,matrix:n,divide:r,sum:a,multiply:i,dotDivide:s,log:o,isNumeric:l}=e;return t(name$C,{"Array, Array":function(e,t){return u(n(e),n(t))},"Matrix, Array":function(e,t){return u(e,n(t))},"Array, Matrix":function(e,t){return u(n(e),t)},"Matrix, Matrix":function(e,t){return u(e,t)}});function u(e,t){var n=t.size().length,u=e.size().length;if(n>1)throw new Error("first object must be one dimensional");if(u>1)throw new Error("second object must be one dimensional");if(n!==u)throw new Error("Length of two vectors must be equal");if(0===a(e))throw new Error("Sum of elements in first object must be non zero");if(0===a(t))throw new Error("Sum of elements in second object must be non zero");var c=r(e,a(e)),p=r(t,a(t)),d=a(i(c,o(s(c,p))));return l(d)?d:Number.NaN}})),name$B="multinomial",dependencies$B=["typed","add","divide","multiply","factorial","isInteger","isPositive"],createMultinomial=factory(name$B,dependencies$B,(e=>{var{typed:t,add:n,divide:r,multiply:a,factorial:i,isInteger:s,isPositive:o}=e;return t(name$B,{"Array | Matrix":function(e){var t=0,l=1;return deepForEach(e,(function(e){if(!s(e)||!o(e))throw new TypeError("Positive integer value expected in function multinomial");t=n(t,e),l=a(l,i(e))})),r(i(t),l)}})})),name$A="permutations",dependencies$A=["typed","factorial"],createPermutations=factory(name$A,dependencies$A,(e=>{var{typed:t,factorial:n}=e;return t(name$A,{"number | BigNumber":n,"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function permutations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function permutations");if(t>e)throw new TypeError("second argument k must be less than or equal to first argument n");return product(e-t+1,e)},"BigNumber, BigNumber":function(e,t){var n,r;if(!isPositiveInteger(e)||!isPositiveInteger(t))throw new TypeError("Positive integer value expected in function permutations");if(t.gt(e))throw new TypeError("second argument k must be less than or equal to first argument n");for(n=e.mul(0).add(1),r=e.minus(t).plus(1);r.lte(e);r=r.plus(1))n=n.times(r);return n}})}));function isPositiveInteger(e){return e.isInteger()&&e.gte(0)}var alea$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n=function(){var e=4022871197;return function(t){t=String(t);for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)}}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function i(e,t){var n=new r(e),i=t&&t.state,s=n.next;return s.int32=function(){return 4294967296*n.next()|0},s.double=function(){return s()+11102230246251565e-32*(2097152*s()|0)},s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.alea=i}(0,e)}(alea$1);var xor128$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xor128=i}(0,e)}(xor128$1);var xorwow$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function i(e,t){var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xorwow=i}(0,e)}(xorwow$1);var xorshift7$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&(i.x&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xorshift7=i}(0,e)}(xorshift7$1);var xor4096$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,i=t.i;return t.w=r=r+1640531527|0,n=a[i+34&127],e=a[i=i+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[i]=n^e,t.i=i,n+(r^r>>>16)|0},function(e,t){var n,r,a,i,s,o=[],l=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,l=Math.max(l,t.length)),a=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,i>=0&&(s=s+1640531527|0,a=0==(n=o[127&i]^=r+s)?a+1:0);for(a>=128&&(o[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=o[a+34&127],n=o[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[a]=r^n;e.w=s,e.X=o,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&(i.X&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xor4096=i}(0,e)}(xor4096$1);var tychei$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.tychei=i}(0,e)}(tychei$1);var seedrandom$2={exports:{}},_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1);!function(e){!function(t,n,r){var a,i=256,s="random",o=r.pow(i,6),l=r.pow(2,52),u=2*l,c=255;function p(e,c,p){var g=[],b=f(h((c=1==c?{entropy:!0}:c||{}).entropy?[e,y(n)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(i):(e=new Uint8Array(i),(t.crypto||t.msCrypto).getRandomValues(e)),y(e)}catch(e){var r=t.navigator,s=r&&r.plugins;return[+new Date,t,s,t.screen,y(n)]}}():e,3),g),v=new d(g),N=function(){for(var e=v.g(6),t=o,n=0;e=u;)e/=2,t/=2,n>>>=1;return(e+n)/t};return N.int32=function(){return 0|v.g(4)},N.quick=function(){return v.g(4)/4294967296},N.double=N,f(y(v.S),n),(c.pass||p||function(e,t,n,a){return a&&(a.S&&m(a,v),e.state=function(){return m(v,{})}),n?(r[s]=e,t):e})(N,b,"global"in c?c.global:this==r,c.state)}function d(e){var t,n=e.length,r=this,a=0,s=r.i=r.j=0,o=r.S=[];for(n||(e=[n++]);a{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$z,{"Array | Matrix":function(e){return i(e,{})},"Array | Matrix, Object":function(e,t){return i(e,t)},"Array | Matrix, number":function(e,t){return i(e,{number:t})},"Array | Matrix, Array | Matrix":function(e,t){return i(e,{weights:t})},"Array | Matrix, Array | Matrix, number":function(e,t,n){return i(e,{number:n,weights:t})},"Array | Matrix, number, Array | Matrix":function(e,t,n){return i(e,{number:t,weights:n})}});function i(e,t){var{number:n,weights:r,elementWise:i=!0}=t,s=void 0===n;s&&(n=1);var o=isMatrix(e)?e.create:isMatrix(r)?r.create:null;e=e.valueOf(),r&&(r=r.valueOf()),!0===i&&(e=flatten$4(e),r=flatten$4(r));var l=0;if(void 0!==r){if(r.length!==e.length)throw new Error("Weights must have the same length as possibles");for(var u=0,c=r.length;u1)for(var r=0,a=e.shift();r{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$y,{"":()=>s(0,1),number:e=>s(0,e),"number, number":(e,t)=>s(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>s(t,n)));return isMatrix(e)?e.create(r):r}function s(e,t){return e+a()*(t-e)}})),name$x="randomInt",dependencies$x=["typed","config","?on"],createRandomInt=factory(name$x,dependencies$x,(e=>{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$x,{"":()=>s(0,1),number:e=>s(0,e),"number, number":(e,t)=>s(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>s(t,n)));return isMatrix(e)?e.create(r):r}function s(e,t){return Math.floor(e+a()*(t-e))}})),name$w="stirlingS2",dependencies$w=["typed","addScalar","subtract","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],createStirlingS2=factory(name$w,dependencies$w,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,pow:s,factorial:o,combinations:l,isNegative:u,isInteger:c,number:p,bignumber:d,larger:m}=e,h=[],f=[];return t(name$w,{"number | BigNumber, number | BigNumber":function(e,t){if(!c(e)||u(e)||!c(t)||u(t))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(m(t,e))throw new TypeError("k must be less than or equal to n in function stirlingS2");var r=!(isNumber$1(e)&&isNumber$1(t)),i=r?f:h,s=r?d:p,o=p(e),l=p(t);if(i[o]&&i[o].length>l)return i[o][l];for(var y=0;y<=o;++y)if(i[y]||(i[y]=[s(0===y?1:0)]),0!==y)for(var g=i[y],b=i[y-1],v=g.length;v<=y&&v<=l;++v)g[v]=v===y?1:n(a(s(v),b[v]),b[v-1]);return i[o][l]}})})),name$v="bellNumbers",dependencies$v=["typed","addScalar","isNegative","isInteger","stirlingS2"],createBellNumbers=factory(name$v,dependencies$v,(e=>{var{typed:t,addScalar:n,isNegative:r,isInteger:a,stirlingS2:i}=e;return t(name$v,{"number | BigNumber":function(e){if(!a(e)||r(e))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var t=0,s=0;s<=e;s++)t=n(t,i(e,s));return t}})})),name$u="catalan",dependencies$u=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],createCatalan=factory(name$u,dependencies$u,(e=>{var{typed:t,addScalar:n,divideScalar:r,multiplyScalar:a,combinations:i,isNegative:s,isInteger:o}=e;return t(name$u,{"number | BigNumber":function(e){if(!o(e)||s(e))throw new TypeError("Non-negative integer value expected in function catalan");return r(i(a(e,2),e),n(e,1))}})})),name$t="composition",dependencies$t=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],createComposition=factory(name$t,dependencies$t,(e=>{var{typed:t,addScalar:n,combinations:r,isPositive:a,isNegative:i,isInteger:s,larger:o}=e;return t(name$t,{"number | BigNumber, number | BigNumber":function(e,t){if(!(s(e)&&a(e)&&s(t)&&a(t)))throw new TypeError("Positive integer value expected in function composition");if(o(t,e))throw new TypeError("k must be less than or equal to n in function composition");return r(n(e,-1),n(t,-1))}})})),name$s="leafCount",dependencies$s=["parse","typed"],createLeafCount=factory(name$s,dependencies$s,(e=>{var{parse:t,typed:n}=e;function r(e){var t=0;return e.forEach((e=>{t+=r(e)})),t||1}return n(name$s,{string:function(e){return this(t(e))},Node:function(e){return r(e)}})}));function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread(e){for(var t=1;t{var{FunctionNode:t,OperatorNode:n,SymbolNode:r}=e,a=!0,i=!1,s="defaultF",o={add:{trivial:a,total:a,commutative:a,associative:a},unaryPlus:{trivial:a,total:a,commutative:a,associative:a},subtract:{trivial:i,total:a,commutative:i,associative:i},multiply:{trivial:a,total:a,commutative:a,associative:a},divide:{trivial:i,total:a,commutative:i,associative:i},paren:{trivial:a,total:a,commutative:a,associative:i},defaultF:{trivial:i,total:a,commutative:i,associative:i}};function l(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o,r=s;if("string"==typeof e?r=e:isOperatorNode(e)?r=e.fn.toString():isFunctionNode(e)?r=e.name:isParenthesisNode(e)&&(r="paren"),hasOwnProperty$2(n,r)){var a=n[r];if(hasOwnProperty$2(a,t))return a[t];if(hasOwnProperty$2(o,r))return o[r][t]}if(hasOwnProperty$2(n,s)){var i=n[s];return hasOwnProperty$2(i,t)?i[t]:o[s][t]}if(hasOwnProperty$2(o,r)){var l=o[r];if(hasOwnProperty$2(l,t))return l[t]}return o[s][t]}function u(e){return l(e,"associative",arguments.length>1&&void 0!==arguments[1]?arguments[1]:o)}function c(e,t){var n,r=[];return u(e,t)?(n=e.op,function e(t){for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:o)},isAssociative:u,mergeContext:function(e,t){var n=_objectSpread({},e);for(var r in t)hasOwnProperty$2(e,r)?n[r]=_objectSpread(_objectSpread({},t[r]),e[r]):n[r]=t[r];return n},flatten:function e(t,n){if(!t.args||0===t.args.length)return t;t.args=c(t,n);for(var r=0;r2&&u(t,n)){for(var s=t.args.pop();t.args.length>0;)s=r([t.args.pop(),s]);t.args=s.args}}},unflattenl:function e(t,n){if(t.args&&0!==t.args.length){for(var r=p(t),a=t.args.length,i=0;i2&&u(t,n)){for(var s=t.args.shift();t.args.length>0;)s=r([s,t.args.shift()]);t.args=s.args}}},defaultContext:o,realContext:{divide:{total:i},log:{total:i}},positiveContext:{subtract:{total:i},abs:{trivial:a},log:{total:a}}}})),name$q="simplifyConstant",dependencies$q=["typed","config","mathWithTransform","matrix","?fraction","?bignumber","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode"],createSimplifyConstant=factory(name$q,dependencies$q,(e=>{var{typed:t,config:n,mathWithTransform:r,matrix:a,fraction:i,bignumber:s,AccessorNode:o,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:p,ObjectNode:d,OperatorNode:m,SymbolNode:h}=e,{isCommutative:f,isAssociative:y,allChildren:g,createMakeNodeFunction:b}=createUtil({FunctionNode:c,OperatorNode:m,SymbolNode:h});function v(e,t){return A(E(e,t))}function N(e){return isFraction(e)?e.valueOf():e instanceof Array?e.map(N):isMatrix(e)?a(N(e.valueOf())):e}function T(e,t,n){try{return r[e].apply(null,t)}catch(a){return t=t.map(N),x(r[e].apply(null,t),n)}}var C=t({Fraction:function(e){var t,n=e.s*e.n;return t=n<0?new m("-","unaryMinus",[new u(-n)]):new u(n),1===e.d?t:new m("/","divide",[t,new u(e.d)])},number:function(e){return e<0?S(new u(-e)):new u(e)},BigNumber:function(e){return e<0?S(new u(-e)):new u(e)},Complex:function(e){throw new Error("Cannot convert Complex number to Node")},string:function(e){return new u(e)},Matrix:function(e){return new l(e.valueOf().map((e=>C(e))))}});function A(e){return isNode(e)?e:C(e)}function V(e,t){if(t&&!1!==t.exactFractions&&isFinite(e)&&i){var n=i(e),r=t&&"number"==typeof t.fractionsLimit?t.fractionsLimit:1/0;if(n.valueOf()===e&&n.nE(e,t)));if(!n.some(isNode))try{return T(e.name,n,t)}catch(e){}if("size"===e.name&&1===n.length&&isArrayNode(n[0])){for(var i=[],s=n[0];isArrayNode(s);)i.push(s.items.length),s=s.items[0];return a(i)}return new c(e.name,n.map(A))}case"OperatorNode":var m,h,N=e.fn.toString(),C=b(e);if(isOperatorNode(e)&&e.isUnary())h=isNode((m=[E(e.args[0],t)])[0])?C(m):T(N,m,t);else if(y(e,t.context))if(m=(m=g(e,t.context)).map((e=>E(e,t))),f(N,t.context)){for(var V=[],S=[],D=0;D1?(h=w(N,V,C,t),S.unshift(h),h=w(N,S,C,t)):h=w(N,m,C,t)}else h=w(N,m,C,t);else h=w(N,m=e.args.map((e=>E(e,t))),C,t);return h;case"ParenthesisNode":return E(e.content,t);case"AccessorNode":return function(e,t,n){if(!isIndexNode(t))return new o(A(e),A(t));if(isArrayNode(e)||isMatrix(e)){for(var r=Array.from(t.dimensions);r.length>0;)if(isConstantNode(r[0])&&"string"!=typeof r[0].value){var i=x(r.shift().value,n);isArrayNode(e)?e=e.items[i-1]:(e=e.valueOf()[i-1])instanceof Array&&(e=a(e))}else{if(!(r.length>1&&isConstantNode(r[1])&&"string"!=typeof r[1].value))break;var s=x(r[1].value,n),c=[],d=isArrayNode(e)?e.items:e.valueOf();for(var m of d)if(isArrayNode(m))c.push(m.items[s-1]);else{if(!isMatrix(e))break;c.push(m[s-1])}if(c.length!==d.length)break;e=isArrayNode(e)?new l(c):a(c),r.splice(1,1)}return r.length===t.dimensions.length?new o(A(e),t):r.length>0?(t=new p(r),new o(A(e),t)):e}if(isObjectNode(e)&&1===t.dimensions.length&&isConstantNode(t.dimensions[0])){var h=t.dimensions[0].value;return h in e.properties?e.properties[h]:new u}return new o(A(e),t)}(E(e.object,t),E(e.index,t),t);case"ArrayNode":var O=e.items.map((e=>E(e,t)));return O.some(isNode)?new l(O.map(A)):a(O);case"IndexNode":return new p(e.dimensions.map((e=>v(e,t))));case"ObjectNode":var I={};for(var R in e.properties)I[R]=v(e.properties[R],t);return new d(I);default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(e.type))}}return v})),name$p="simplify",dependencies$p=["config","typed","parse","add","subtract","multiply","divide","pow","isZero","equal","resolve","simplifyCore","?fraction","?bignumber","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],createSimplify=factory(name$p,dependencies$p,(e=>{var{config:t,typed:n,parse:r,add:a,subtract:i,multiply:s,divide:o,pow:l,isZero:u,equal:c,resolve:p,simplifyCore:d,fraction:m,bignumber:h,mathWithTransform:f,matrix:y,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,ParenthesisNode:V,SymbolNode:x}=e,S=createSimplifyConstant({typed:n,config:t,mathWithTransform:f,matrix:y,fraction:m,bignumber:h,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:x}),{hasProperty:w,isCommutative:E,isAssociative:D,mergeContext:O,flatten:I,unflattenr:R,unflattenl:_,createMakeNodeFunction:M,defaultContext:P,realContext:F,positiveContext:k}=createUtil({FunctionNode:N,OperatorNode:A,SymbolNode:x}),$=n("simplify",{string:function(e){return this(r(e),this.rules,createEmptyMap(),{})},"string, Map | Object":function(e,t){return this(r(e),this.rules,t,{})},"string, Map | Object, Object":function(e,t,n){return this(r(e),this.rules,t,n)},"string, Array":function(e,t){return this(r(e),t,createEmptyMap(),{})},"string, Array, Map | Object":function(e,t,n){return this(r(e),t,n,{})},"string, Array, Map | Object, Object":function(e,t,n,a){return this(r(e),t,n,a)},"Node, Map | Object":function(e,t){return this(e,this.rules,t,{})},"Node, Map | Object, Object":function(e,t,n){return this(e,this.rules,t,n)},Node:function(e){return this(e,this.rules,createEmptyMap(),{})},"Node, Array":function(e,t){return this(e,t,createEmptyMap(),{})},"Node, Array, Map | Object":function(e,t,n){return this(e,t,n,{})},"Node, Array, Object, Object":function(e,t,n,r){return this(e,t,createMap$1(n),r)},"Node, Array, Map, Object":function(e,t,n,r){var a=r.consoleDebug;t=function(e,t){for(var n=[],r=0;r ").concat(t[u].r.toString()))),a){var d=i.toString({parenthesis:"all"});d!==l&&(console.log("Applying",c,"produced",d),l=d)}_(i,r.context)}o=i.toString({parenthesis:"all"})}return i}});function B(e){return e.transform((function(e,t,n){return isParenthesisNode(e)?B(e.content):e}))}$.defaultContext=P,$.realContext=F,$.positiveContext=k;var L={true:!0,false:!0,e:!0,i:!0,Infinity:!0,LN2:!0,LN10:!0,LOG2E:!0,LOG10E:!0,NaN:!0,phi:!0,pi:!0,SQRT1_2:!0,SQRT2:!0,tau:!0};function z(e,t){var n={};if(e.s){var a=e.s.split("->");if(2!==a.length)throw SyntaxError("Could not parse rule: "+e.s);n.l=a[0],n.r=a[1]}else n.l=e.l,n.r=e.r;for(var i of(n.l=B(r(n.l)),n.r=B(r(n.r)),["imposeContext","repeat","assuming"]))i in e&&(n[i]=e[i]);if(e.evaluate&&(n.evaluate=r(e.evaluate)),D(n.l,t)){var s=M(n.l),o=new x("_p"+U++);n.expanded={},n.expanded.l=s([n.l.clone(),o]),I(n.expanded.l,t),R(n.expanded.l,t),n.expanded.r=s([n.r,o])}return n}$.rules=[d,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(c*v) -> v * (-c)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(c*v) -> (-c) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*c) -> v * (-c)",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{l:"-(n1/n2)",r:"-n1/n2"},{l:"-v",r:"v * (-1)"},{l:"(n1 + n2)*(-1)",r:"n1*(-1) + n2*(-1)",repeat:!0},{l:"n/n1^n2",r:"n*n1^-n2"},{l:"n/n1",r:"n*n1^-1"},{s:"(n1*n2)^n3 -> n1^n3 * n2^n3",assuming:{multiply:{commutative:!0}}},{s:"(n1*n2)^(-1) -> n2^(-1) * n1^(-1)",assuming:{multiply:{commutative:!1}}},{s:"(n ^ n1) ^ n2 -> n ^ (n1 * n2)",assuming:{divide:{total:!0}}},{l:" v * ( v * n1 + n2)",r:"v^2 * n1 + v * n2"},{s:" v * (v^n4 * n1 + n2) -> v^(1+n4) * n1 + v * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * ( v * n1 + n2) -> v^(n3+1) * n1 + v^n3 * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * (v^n4 * n1 + n2) -> v^(n3+n4) * n1 + v^n3 * n2",assuming:{divide:{total:!0}}},{l:"n*n",r:"n^2"},{s:"n * n^n1 -> n^(n1+1)",assuming:{divide:{total:!0}}},{s:"n^n1 * n^n2 -> n^(n1+n2)",assuming:{divide:{total:!0}}},S,{s:"n+n -> 2*n",assuming:{add:{total:!0}}},{l:"n+-n",r:"0"},{l:"v*n + v",r:"v*(n+1)"},{l:"n3*n1 + n3*n2",r:"n3*(n1+n2)"},{l:"n3^(-n4)*n1 + n3 * n2",r:"n3^(-n4)*(n1 + n3^(n4+1) *n2)"},{l:"n3^(-n4)*n1 + n3^n5 * n2",r:"n3^(-n4)*(n1 + n3^(n4+n5)*n2)"},{s:"n*v + v -> (n+1)*v",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3 -> (n1 + n2*n3^(n4 + 1))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{l:"n*c + c",r:"(n+1)*c"},{s:"c*n + c -> c*(n+1)",assuming:{multiply:{commutative:!1}}},S,{s:"(-n)*n1 -> -(n*n1)",assuming:{subtract:{total:!0}}},{s:"n1*(-n) -> -(n1*n)",assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:"c+v -> v+c",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"v*c -> c*v",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{l:"n+-n1",r:"n-n1"},{s:"n*(n1^-1) -> n/n1",assuming:{multiply:{commutative:!0}}},{s:"n*n1^-n2 -> n/n1^n2",assuming:{multiply:{commutative:!0}}},{s:"n^-1 -> 1/n",assuming:{multiply:{commutative:!0}}},{l:"n^1",r:"n"},{s:"n*(n1/n2) -> (n*n1)/n2",assuming:{multiply:{associative:!0}}},{s:"n-(n1+n2) -> n-n1-n2",assuming:{addition:{associative:!0,commutative:!0}}},{l:"1*n",r:"n",imposeContext:{multiply:{commutative:!0}}},{s:"n1/(n2/n3) -> (n1*n3)/n2",assuming:{multiply:{associative:!0}}},{l:"n1/(-n2)",r:"-n1/n2"}];var U=0;function j(e,t,n){var r=e;if(e)for(var a=0;a=2&&2===e.args.length){for(var i=function(e,t){var n,r,a=[],i=M(e);if(E(e,t))for(var s=0;s1&&(l=i(e.args.slice(0,o))),n=1===(r=e.args.slice(o)).length?r[0]:i(r),a.push(i([l,n]))}return a}(t,n),s=[],o=0;o2)throw Error("Unexpected non-binary associative function: "+e.toString());return[]}for(var u=[],p=0;p2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var m=W(e.args[0],t.args[1],n);if(0===m.length)return[];var h=W(e.args[1],t.args[0],n);if(0===h.length)return[];u=[m,h]}a=function(e){if(0===e.length)return e;for(var t=e.reduce(H),n=[],r={},a=0;a{var{equal:t,isZero:n,add:r,subtract:a,multiply:i,divide:s,pow:o,AccessorNode:l,ArrayNode:u,ConstantNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:h,ParenthesisNode:f,SymbolNode:y}=e,g=new c(0),b=new c(1),{hasProperty:v,isCommutative:N}=createUtil({FunctionNode:p,OperatorNode:h,SymbolNode:y});return function e(f,y){var T=y?y.context:void 0;if(v(f,"trivial",T)){if(isFunctionNode(f)&&1===f.args.length)return e(f.args[0],y);var C=!1,A=0;if(f.forEach((t=>{1==++A&&(C=e(t,y))})),1===A)return C}if(isOperatorNode(f)&&f.isUnary()){var V=e(f.args[0],y);if("-"===f.op){if(isOperatorNode(V)){if(V.isUnary()&&"-"===V.op)return V.args[0];if(V.isBinary()&&"subtract"===V.fn)return new h("-","subtract",[V.args[1],V.args[0]])}return new h(f.op,f.fn,[V])}}else{if(isOperatorNode(f)&&f.isBinary()){var x=e(f.args[0],y),S=e(f.args[1],y);if("+"===f.op){if(isConstantNode(x)){if(n(x.value))return S;if(isConstantNode(S))return new c(r(x.value,S.value))}return isConstantNode(S)&&n(S.value)?x:isOperatorNode(S)&&S.isUnary()&&"-"===S.op?new h("-","subtract",[x,S.args[0]]):new h(f.op,f.fn,S?[x,S]:[x])}if("-"===f.op){if(isConstantNode(x)&&S){if(isConstantNode(S))return new c(a(x.value,S.value));if(n(x.value))return new h("-","unaryMinus",[S])}if("subtract"===f.fn)return isConstantNode(S)&&n(S.value)?x:isOperatorNode(S)&&S.isUnary()&&"-"===S.op?e(new h("+","add",[x,S.args[0]]),y):new h(f.op,f.fn,[x,S])}else{if("*"===f.op){if(isConstantNode(x)){if(n(x.value))return g;if(t(x.value,1))return S;if(isConstantNode(S))return new c(i(x.value,S.value))}if(isConstantNode(S)){if(n(S.value))return g;if(t(S.value,1))return x;if(isOperatorNode(x)&&x.isBinary()&&x.op===f.op&&N(f,T)){var w=x.args[0];if(isConstantNode(w)){var E=new c(i(w.value,S.value));return new h(f.op,f.fn,[E,x.args[1]],f.implicit)}}return N(f,T)?new h(f.op,f.fn,[S,x],f.implicit):new h(f.op,f.fn,[x,S],f.implicit)}return new h(f.op,f.fn,[x,S],f.implicit)}if("/"===f.op){if(isConstantNode(x)){if(n(x.value))return g;if(isConstantNode(S)&&(t(S.value,1)||t(S.value,2)||t(S.value,4)))return new c(s(x.value,S.value))}return new h(f.op,f.fn,[x,S])}if("^"===f.op&&isConstantNode(S)){if(n(S.value))return b;if(t(S.value,1))return x;if(isConstantNode(x))return new c(o(x.value,S.value));if(isOperatorNode(x)&&x.isBinary()&&"^"===x.op){var D=x.args[1];if(isConstantNode(D))return new h(f.op,f.fn,[x.args[0],new c(i(D.value,S.value))])}}}return new h(f.op,f.fn,[x,S])}if(isFunctionNode(f))return new p(e(f.fn),f.args.map((t=>e(t,y))));if(isArrayNode(f))return new u(f.items.map((t=>e(t,y))));if(isAccessorNode(f))return new l(e(f.object,y),e(f.index,y));if(isIndexNode(f))return new d(f.dimensions.map((t=>e(t,y))));if(isObjectNode(f)){var O={};for(var I in f.properties)O[I]=e(f.properties[I],y);return new m(O)}}return f}})),name$n="resolve",dependencies$n=["parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],createResolve=factory(name$n,dependencies$n,(e=>{var{parse:t,ConstantNode:n,FunctionNode:r,OperatorNode:a,ParenthesisNode:i}=e;return function e(s,o){var l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Set;if(!o)return s;if(isMap$1(o)||(o=createMap$1(o)),isSymbolNode(s)){if(l.has(s.name)){var u=Array.from(l).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(u,"}"))}var c=o.get(s.name);if(isNode(c)){var p=new Set(l);return p.add(s.name),e(c,o,p)}return"number"==typeof c?t(String(c)):void 0!==c?new n(c):s}if(isOperatorNode(s)){var d=s.args.map((function(t){return e(t,o,l)}));return new a(s.op,s.fn,d,s.implicit)}if(isParenthesisNode(s))return new i(e(s.content,o,l));if(isFunctionNode(s)){var m=s.args.map((function(t){return e(t,o,l)}));return new r(s.name,m)}return s.map((t=>e(t,o,l)))}})),name$m="symbolicEqual",dependencies$m=["parse","simplify","typed","OperatorNode"],createSymbolicEqual=factory(name$m,dependencies$m,(e=>{var{parse:t,simplify:n,typed:r,OperatorNode:a}=e;return r(name$m,{"string, string":function(e,n){return this(t(e),t(n),{})},"string, string, Object":function(e,n,r){return this(t(e),t(n),r)},"Node, string":function(e,n){return this(e,t(n),{})},"Node, string, Object":function(e,n,r){return this(e,t(n),r)},"string, Node":function(e,n){return this(t(e),n,{})},"string, Node, Object":function(e,n,r){return this(t(e),n,r)},"Node, Node":function(e,t){return this(e,t,{})},"Node, Node, Object":function(e,t,r){var i=new a("-","subtract",[e,t]),s=n(i,{},r);return isConstantNode(s)&&!s.value}})})),name$l="derivative",dependencies$l=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],createDerivative=factory(name$l,dependencies$l,(e=>{var{typed:t,config:n,parse:r,simplify:a,equal:i,isZero:s,numeric:o,ConstantNode:l,FunctionNode:u,OperatorNode:c,ParenthesisNode:p,SymbolNode:d}=e,m=t("derivative",{"Node, SymbolNode, Object":function(e,t,n){var r={};f(r,e,t.name);var i=y(e,r);return n.simplify?a(i):i},"Node, SymbolNode":function(e,t){return this(e,t,{simplify:!0})},"string, SymbolNode":function(e,t){return this(r(e),t)},"string, SymbolNode, Object":function(e,t,n){return this(r(e),t,n)},"string, string":function(e,t){return this(r(e),r(t))},"string, string, Object":function(e,t,n){return this(r(e),r(t),n)},"Node, string":function(e,t){return this(e,r(t))},"Node, string, Object":function(e,t,n){return this(e,r(t),n)}});m._simplify=!0,m.toTex=function(e){return h.apply(null,e.args)};var h=t("_derivTex",{"Node, SymbolNode":function(e,t){return isConstantNode(e)&&"string"===typeOf$1(e.value)?h(r(e.value).toString(),t.toString(),1):h(e.toTex(),t.toString(),1)},"Node, ConstantNode":function(e,t){if("string"===typeOf$1(t.value))return h(e,r(t.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(e,t,n){return h(e.toString(),t.name,n.value)},"string, string, number":function(e,t,n){return(1===n?"{d\\over d"+t+"}":"{d^{"+n+"}\\over d"+t+"^{"+n+"}}")+"\\left[".concat(e,"\\right]")}}),f=t("constTag",{"Object, ConstantNode, string":function(e,t){return e[t]=!0,!0},"Object, SymbolNode, string":function(e,t,n){return t.name!==n&&(e[t]=!0,!0)},"Object, ParenthesisNode, string":function(e,t,n){return f(e,t.content,n)},"Object, FunctionAssignmentNode, string":function(e,t,n){return-1===t.params.indexOf(n)?(e[t]=!0,!0):f(e,t.expr,n)},"Object, FunctionNode | OperatorNode, string":function(e,t,n){if(t.args.length>0){for(var r=f(e,t.args[0],n),a=1;a0){var r=e.args.filter((function(e){return void 0===t[e]})),a=1===r.length?r[0]:new c("*","multiply",r),o=n.concat(y(a,t));return new c("*","multiply",o)}return new c("+","add",e.args.map((function(n){return new c("*","multiply",e.args.map((function(e){return e===n?y(e,t):e.clone()})))})))}if("/"===e.op&&e.isBinary()){var l=e.args[0],p=e.args[1];return void 0!==t[p]?new c("/","divide",[y(l,t),p]):void 0!==t[l]?new c("*","multiply",[new c("-","unaryMinus",[l]),new c("/","divide",[y(p,t),new c("^","pow",[p.clone(),g(2)])])]):new c("/","divide",[new c("-","subtract",[new c("*","multiply",[y(l,t),p.clone()]),new c("*","multiply",[l.clone(),y(p,t)])]),new c("^","pow",[p.clone(),g(2)])])}if("^"===e.op&&e.isBinary()){var d=e.args[0],m=e.args[1];if(void 0!==t[d])return isConstantNode(d)&&(s(d.value)||i(d.value,1))?g(0):new c("*","multiply",[e,new c("*","multiply",[new u("log",[d.clone()]),y(m.clone(),t)])]);if(void 0!==t[m]){if(isConstantNode(m)){if(s(m.value))return g(0);if(i(m.value,1))return y(d,t)}var h=new c("^","pow",[d.clone(),new c("-","subtract",[m,g(1)])]);return new c("*","multiply",[m.clone(),new c("*","multiply",[y(d,t),h])])}return new c("*","multiply",[new c("^","pow",[d.clone(),m.clone()]),new c("+","add",[new c("*","multiply",[y(d,t),new c("/","divide",[m.clone(),d.clone()])]),new c("*","multiply",[y(m,t),new u("log",[d.clone()])])])])}throw new Error('Operator "'+e.op+'" is not supported by derivative, or a wrong number of arguments is passed')}});function g(e,t){return new l(o(e,t||n.number))}return m})),name$k="rationalize",dependencies$k=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],createRationalize=factory(name$k,dependencies$k,(e=>{var{config:t,typed:n,equal:r,isZero:a,add:i,subtract:s,multiply:o,divide:l,pow:u,parse:c,simplifyCore:p,simplify:d,fraction:m,bignumber:h,mathWithTransform:f,matrix:y,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:V,ParenthesisNode:x}=e,S=createSimplifyConstant({typed:n,config:t,mathWithTransform:f,matrix:y,fraction:m,bignumber:h,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:V});return n(name$k,{string:function(e){return this(c(e),{},!1)},"string, boolean":function(e,t){return this(c(e),{},t)},"string, Object":function(e,t){return this(c(e),t,!1)},"string, Object, boolean":function(e,t,n){return this(c(e),t,n)},Node:function(e){return this(e,{},!1)},"Node, boolean":function(e,t){return this(e,{},t)},"Node, Object":function(e,t){return this(e,t,!1)},"Node, Object, boolean":function(e,t,n){var r=function(){var e=[p,{l:"n+n",r:"2*n"},{l:"n+-n",r:"0"},S,{l:"n*(n1^-1)",r:"n/n1"},{l:"n*n1^-n2",r:"n/n1^n2"},{l:"n1^-1",r:"1/n1"},{l:"n*(n1/n2)",r:"(n*n1)/n2"},{l:"1*n",r:"n"}],t=[{l:"(-n1)/(-n2)",r:"n1/n2"},{l:"(-n1)*(-n2)",r:"n1*n2"},{l:"n1--n2",r:"n1+n2"},{l:"n1-n2",r:"n1+(-n2)"},{l:"(n1+n2)*n3",r:"(n1*n3 + n2*n3)"},{l:"n1*(n2+n3)",r:"(n1*n2+n1*n3)"},{l:"c1*n + c2*n",r:"(c1+c2)*n"},{l:"c1*n + n",r:"(c1+1)*n"},{l:"c1*n - c2*n",r:"(c1-c2)*n"},{l:"c1*n - n",r:"(c1-1)*n"},{l:"v/c",r:"(1/c)*v"},{l:"v/-c",r:"-(1/c)*v"},{l:"-v*-c",r:"c*v"},{l:"-v*c",r:"-c*v"},{l:"v*-c",r:"-c*v"},{l:"v*c",r:"c*v"},{l:"-(-n1*n2)",r:"(n1*n2)"},{l:"-(n1*n2)",r:"(-n1*n2)"},{l:"-(-n1+n2)",r:"(n1-n2)"},{l:"-(n1+n2)",r:"(-n1-n2)"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"},{l:"-(-n1/n2)",r:"(n1/n2)"},{l:"-(n1/n2)",r:"(-n1/n2)"}],n=[{l:"(n1/(n2/n3))",r:"((n1*n3)/n2)"},{l:"(n1/n2/n3)",r:"(n1/(n2*n3))"}],r={};return r.firstRules=e.concat(t,n),r.distrDivRules=[{l:"(n1/n2 + n3/n4)",r:"((n1*n4 + n3*n2)/(n2*n4))"},{l:"(n1/n2 + n3)",r:"((n1 + n3*n2)/n2)"},{l:"(n1 + n2/n3)",r:"((n1*n3 + n2)/n3)"}],r.sucDivRules=n,r.firstRulesAgain=e.concat(t),r.finalRules=[p,{l:"n*-n",r:"-n^2"},{l:"n*n",r:"n^2"},S,{l:"n*-n^n1",r:"-n^(n1+1)"},{l:"n*n^n1",r:"n^(n1+1)"},{l:"n^n1*-n^n2",r:"-n^(n1+n2)"},{l:"n^n1*n^n2",r:"n^(n1+n2)"},{l:"n^n1*-n",r:"-n^(n1+1)"},{l:"n^n1*n",r:"n^(n1+1)"},{l:"n^n1/-n",r:"-n^(n1-1)"},{l:"n^n1/n",r:"n^(n1-1)"},{l:"n/-n^n1",r:"-n^(1-n1)"},{l:"n/n^n1",r:"n^(1-n1)"},{l:"n^n1/-n^n2",r:"n^(n1-n2)"},{l:"n^n1/n^n2",r:"n^(n1-n2)"},{l:"n1+(-n2*n3)",r:"n1-n2*n3"},{l:"v*(-c)",r:"-c*v"},{l:"n1+-n2",r:"n1-n2"},{l:"v*c",r:"c*v"},{l:"(n1^n2)^n3",r:"(n1^(n2*n3))"}],r}(),a=function(e,t,n,r){var a=[],i=d(e,r,t,{exactFractions:!1}),s="+-*"+((n=!!n)?"/":"");!function e(t){var n=t.type;if("FunctionNode"===n)throw new Error("There is an unsolved function call");if("OperatorNode"===n)if("^"===t.op){if("ConstantNode"!==t.args[1].type||!isInteger$1(parseFloat(t.args[1].value)))throw new Error("There is a non-integer exponent");e(t.args[0])}else{if(-1===s.indexOf(t.op))throw new Error("Operator "+t.op+" invalid in polynomial expression");for(var r=0;r=1){var l,u;e=w(e);var c,m=!0,h=!1;for(e=d(e,r.firstRules,{},s);u=m?r.distrDivRules:r.sucDivRules,m=!m,(c=(e=d(e,u,{},o)).toString())!==l;)h=!0,l=c;h&&(e=d(e,r.firstRulesAgain,{},s)),e=d(e,r.finalRules,{},s)}var f=[],y={};return"OperatorNode"===e.type&&e.isBinary()&&"/"===e.op?(1===i&&(e.args[0]=E(e.args[0],f),e.args[1]=E(e.args[1])),n&&(y.numerator=e.args[0],y.denominator=e.args[1])):(1===i&&(e=E(e,f)),n&&(y.numerator=e,y.denominator=null)),n?(y.coefficients=f,y.variables=a.variables,y.expression=e,y):e}});function w(e,t,n){var r=e.type,a=arguments.length>1;if("OperatorNode"===r&&e.isBinary()){var i,s=!1;if("^"===e.op&&("ParenthesisNode"!==e.args[0].type&&"OperatorNode"!==e.args[0].type||"ConstantNode"!==e.args[1].type||(s=(i=parseFloat(e.args[1].value))>=2&&isInteger$1(i))),s){if(i>2){var o=e.args[0],l=new A("^","pow",[e.args[0].cloneDeep(),new v(i-1)]);e=new A("*","multiply",[o,l])}else e=new A("*","multiply",[e.args[0],e.args[0].cloneDeep()]);a&&("content"===n?t.content=e:t.args[n]=e)}}if("ParenthesisNode"===r)w(e.content,e,"content");else if("ConstantNode"!==r&&"SymbolNode"!==r)for(var u=0;un&&(t[u]=0),t[u]+=s.cte*("+"===s.oper?1:-1),void(n=Math.max(u,n))}s.cte=u,""===s.fire&&(t[0]+=s.cte*("+"===s.oper?1:-1))}}(e,null,{cte:1,oper:"+",fire:""});for(var a,i=!0,s=n=t.length-1;s>=0;s--)if(0!==t[s]){var o=new v(i?t[s]:Math.abs(t[s])),l=t[s]<0?"-":"+";if(s>0){var u=new V(r);if(s>1){var c=new v(s);u=new A("^","pow",[u,c])}o=-1===t[s]&&i?new A("-","unaryMinus",[u]):1===Math.abs(t[s])?u:new A("*","multiply",[o,u])}a=i?o:"+"===l?new A("+","add",[a,o]):new A("-","subtract",[a,o]),i=!1}return i?new v(0):a}})),name$j="reviver",dependencies$j=["classes"],createReviver=factory(name$j,dependencies$j,(e=>{var{classes:t}=e;return function(e,n){var r=t[n&&n.mathjs];return r&&"function"==typeof r.fromJSON?r.fromJSON(n):n}})),name$i="replacer",dependencies$i=[],createReplacer=factory(name$i,dependencies$i,(()=>function(e,t){return"number"!=typeof t||isFinite(t)&&!isNaN(t)?t:{mathjs:"number",value:String(t)}})),version$2="10.6.4",createTrue=factory("true",[],(()=>!0)),createFalse=factory("false",[],(()=>!1)),createNull=factory("null",[],(()=>null)),createInfinity=recreateFactory("Infinity",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1/0):1/0})),createNaN=recreateFactory("NaN",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(NaN):NaN})),createPi=recreateFactory("pi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPi(n):pi$1})),createTau=recreateFactory("tau",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberTau(n):tau$1})),createE=recreateFactory("e",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberE(n):e$1})),createPhi=recreateFactory("phi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPhi(n):phi$1})),createLN2=recreateFactory("LN2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).ln():Math.LN2})),createLN10=recreateFactory("LN10",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(10).ln():Math.LN10})),createLOG2E=recreateFactory("LOG2E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(2).ln()):Math.LOG2E})),createLOG10E=recreateFactory("LOG10E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(10).ln()):Math.LOG10E})),createSQRT1_2=recreateFactory("SQRT1_2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n("0.5").sqrt():Math.SQRT1_2})),createSQRT2=recreateFactory("SQRT2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).sqrt():Math.SQRT2})),createI=recreateFactory("i",["Complex"],(e=>{var{Complex:t}=e;return t.I})),createUppercasePi=factory("PI",["pi"],(e=>{var{pi:t}=e;return t})),createUppercaseE=factory("E",["e"],(e=>{var{e:t}=e;return t})),createVersion=factory("version",[],(()=>version$2));function recreateFactory(e,t,n){return factory(e,t,n,{recreateOnConfigChange:!0})}var createSpeedOfLight=unitFactory("speedOfLight","299792458","m s^-1"),createGravitationConstant=unitFactory("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),createPlanckConstant=unitFactory("planckConstant","6.62607015e-34","J s"),createReducedPlanckConstant=unitFactory("reducedPlanckConstant","1.0545718176461565e-34","J s"),createMagneticConstant=unitFactory("magneticConstant","1.25663706212e-6","N A^-2"),createElectricConstant=unitFactory("electricConstant","8.8541878128e-12","F m^-1"),createVacuumImpedance=unitFactory("vacuumImpedance","376.730313667","ohm"),createCoulomb=unitFactory("coulomb","8.987551792261171e9","N m^2 C^-2"),createElementaryCharge=unitFactory("elementaryCharge","1.602176634e-19","C"),createBohrMagneton=unitFactory("bohrMagneton","9.2740100783e-24","J T^-1"),createConductanceQuantum=unitFactory("conductanceQuantum","7.748091729863649e-5","S"),createInverseConductanceQuantum=unitFactory("inverseConductanceQuantum","12906.403729652257","ohm"),createMagneticFluxQuantum=unitFactory("magneticFluxQuantum","2.0678338484619295e-15","Wb"),createNuclearMagneton=unitFactory("nuclearMagneton","5.0507837461e-27","J T^-1"),createKlitzing=unitFactory("klitzing","25812.807459304513","ohm"),createBohrRadius=unitFactory("bohrRadius","5.29177210903e-11","m"),createClassicalElectronRadius=unitFactory("classicalElectronRadius","2.8179403262e-15","m"),createElectronMass=unitFactory("electronMass","9.1093837015e-31","kg"),createFermiCoupling=unitFactory("fermiCoupling","1.1663787e-5","GeV^-2"),createFineStructure=numberFactory("fineStructure",.0072973525693),createHartreeEnergy=unitFactory("hartreeEnergy","4.3597447222071e-18","J"),createProtonMass=unitFactory("protonMass","1.67262192369e-27","kg"),createDeuteronMass=unitFactory("deuteronMass","3.3435830926e-27","kg"),createNeutronMass=unitFactory("neutronMass","1.6749271613e-27","kg"),createQuantumOfCirculation=unitFactory("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),createRydberg=unitFactory("rydberg","10973731.568160","m^-1"),createThomsonCrossSection=unitFactory("thomsonCrossSection","6.6524587321e-29","m^2"),createWeakMixingAngle=numberFactory("weakMixingAngle",.2229),createEfimovFactor=numberFactory("efimovFactor",22.7),createAtomicMass=unitFactory("atomicMass","1.66053906660e-27","kg"),createAvogadro=unitFactory("avogadro","6.02214076e23","mol^-1"),createBoltzmann=unitFactory("boltzmann","1.380649e-23","J K^-1"),createFaraday=unitFactory("faraday","96485.33212331001","C mol^-1"),createFirstRadiation=unitFactory("firstRadiation","3.7417718521927573e-16","W m^2"),createLoschmidt=unitFactory("loschmidt","2.686780111798444e25","m^-3"),createGasConstant=unitFactory("gasConstant","8.31446261815324","J K^-1 mol^-1"),createMolarPlanckConstant=unitFactory("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),createMolarVolume=unitFactory("molarVolume","0.022413969545014137","m^3 mol^-1"),createSackurTetrode=numberFactory("sackurTetrode",-1.16487052358),createSecondRadiation=unitFactory("secondRadiation","0.014387768775039337","m K"),createStefanBoltzmann=unitFactory("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),createWienDisplacement=unitFactory("wienDisplacement","2.897771955e-3","m K"),createMolarMass=unitFactory("molarMass","0.99999999965e-3","kg mol^-1"),createMolarMassC12=unitFactory("molarMassC12","11.9999999958e-3","kg mol^-1"),createGravity=unitFactory("gravity","9.80665","m s^-2"),createPlanckLength=unitFactory("planckLength","1.616255e-35","m"),createPlanckMass=unitFactory("planckMass","2.176435e-8","kg"),createPlanckTime=unitFactory("planckTime","5.391245e-44","s"),createPlanckCharge=unitFactory("planckCharge","1.87554603778e-18","C"),createPlanckTemperature=unitFactory("planckTemperature","1.416785e+32","K");function unitFactory(e,t,n){return factory(e,["config","Unit","BigNumber"],(e=>{var{config:r,Unit:a,BigNumber:i}=e,s=new a("BigNumber"===r.number?new i(t):parseFloat(t),n);return s.fixPrefix=!0,s}))}function numberFactory(e,t){return factory(e,["config","BigNumber"],(e=>{var{config:n,BigNumber:r}=e;return"BigNumber"===n.number?new r(t):t}))}var name$h="apply",dependencies$h=["typed","isInteger"],createApplyTransform=factory(name$h,dependencies$h,(e=>{var{typed:t,isInteger:n}=e,r=createApply({typed:t,isInteger:n});return t("apply",{"...any":function(e){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1));try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$g="column",dependencies$g=["typed","Index","matrix","range"],createColumnTransform=factory(name$g,dependencies$g,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createColumn({typed:t,Index:n,matrix:r,range:a});return t("column",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0});function compileInlineExpression(e,t,n){var r=e.filter((function(e){return isSymbolNode(e)&&!(e.name in t)&&!n.has(e.name)}))[0];if(!r)throw new Error('No undefined variable found in inline expression "'+e+'"');var a=r.name,i=createSubScope(n),s=e.compile();return function(e){return i.set(a,e),s.evaluate(i)}}var name$f="filter",dependencies$f=["typed"],createFilterTransform=factory(name$f,dependencies$f,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("filter",{"Array, function":_filter,"Matrix, function":function(e,t){return e.create(_filter(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}});return n}),{isTransformFunction:!0});function _filter(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r+1]):t(e,[r+1],a)}))}var name$e="forEach",dependencies$e=["typed"],createForEachTransform=factory(name$e,dependencies$e,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("forEach",{"Array | Matrix, function":function(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t+1))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e.valueOf(),[])}});return n}),{isTransformFunction:!0}),name$d="index",dependencies$d=["Index"],createIndexTransform=factory(name$d,dependencies$d,(e=>{var{Index:t}=e;return function(){for(var e=[],n=0,r=arguments.length;n0?0:2;else if(a&&!0===a.isSet)a=a.map((function(e){return e-1}));else if(isArray$1(a)||isMatrix(a))a=a.map((function(e){return e-1}));else if(isNumber$1(a))a--;else if(isBigNumber(a))a=a.toNumber()-1;else if("string"!=typeof a)throw new TypeError("Dimension must be an Array, Matrix, number, string, or Range");e[n]=a}var i=new t;return t.apply(i,e),i}}),{isTransformFunction:!0}),name$c="map",dependencies$c=["typed"],createMapTransform=factory(name$c,dependencies$c,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("map",{"Array, function":function(e,t){return _map(e,t,e)},"Matrix, function":function(e,t){return e.create(_map(e.valueOf(),t,e))}});return n}),{isTransformFunction:!0});function _map(e,t,n){var r=maxArgumentCount(t);return function e(a,i){return Array.isArray(a)?map$2(a,(function(t,n){return e(t,i.concat(n+1))})):1===r?t(a):2===r?t(a,i):t(a,i,n)}(e,[])}function lastDimToZeroBase(e){if(2===e.length&&isCollection(e[0])){var t=(e=e.slice())[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}return e}var name$b="max",dependencies$b=["typed","config","numeric","larger"],createMaxTransform=factory(name$b,dependencies$b,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e,i=createMax({typed:t,config:n,numeric:r,larger:a});return t("max",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$a="mean",dependencies$a=["typed","add","divide"],createMeanTransform=factory(name$a,dependencies$a,(e=>{var{typed:t,add:n,divide:r}=e,a=createMean({typed:t,add:n,divide:r});return t("mean",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$9="min",dependencies$9=["typed","config","numeric","smaller"],createMinTransform=factory(name$9,dependencies$9,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e,i=createMin({typed:t,config:n,numeric:r,smaller:a});return t("min",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$8="range",dependencies$8=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRangeTransform=factory(name$8,dependencies$8,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l}=e,u=createRange({typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l});return t("range",{"...any":function(e){return"boolean"!=typeof e[e.length-1]&&e.push(!0),u.apply(null,e)}})}),{isTransformFunction:!0}),name$7="row",dependencies$7=["typed","Index","matrix","range"],createRowTransform=factory(name$7,dependencies$7,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createRow({typed:t,Index:n,matrix:r,range:a});return t("row",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$6="subset",dependencies$6=["typed","matrix"],createSubsetTransform=factory(name$6,dependencies$6,(e=>{var{typed:t,matrix:n}=e,r=createSubset({typed:t,matrix:n});return t("subset",{"...any":function(e){try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$5="concat",dependencies$5=["typed","matrix","isInteger"],createConcatTransform=factory(name$5,dependencies$5,(e=>{var{typed:t,matrix:n,isInteger:r}=e,a=createConcat({typed:t,matrix:n,isInteger:r});return t("concat",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)?e[t]=n-1:isBigNumber(n)&&(e[t]=n.minus(1));try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$4="diff",dependencies$4=["typed","matrix","subtract","number","bignumber"],createDiffTransform=factory(name$4,dependencies$4,(e=>{var{typed:t,matrix:n,subtract:r,number:a,bignumber:i}=e,s=createDiff({typed:t,matrix:n,subtract:r,number:a,bignumber:i});return t(name$4,{"...any":function(e){e=lastDimToZeroBase(e);try{return s.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$3="std",dependencies$3=["typed","sqrt","variance"],createStdTransform=factory(name$3,dependencies$3,(e=>{var{typed:t,sqrt:n,variance:r}=e,a=createStd({typed:t,sqrt:n,variance:r});return t("std",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$2="sum",dependencies$2=["typed","config","add","numeric"],createSumTransform=factory(name$2,dependencies$2,(e=>{var{typed:t,config:n,add:r,numeric:a}=e,i=createSum({typed:t,config:n,add:r,numeric:a});return t(name$2,{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$1="cumsum",dependencies$1=["typed","add","unaryPlus"],createCumSumTransform=factory(name$1,dependencies$1,(e=>{var{typed:t,add:n,unaryPlus:r}=e,a=createCumSum({typed:t,add:n,unaryPlus:r});return t(name$1,{"...any":function(e){if(2===e.length&&isCollection(e[0])){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name="variance",dependencies=["typed","add","subtract","multiply","divide","apply","isNaN"],createVarianceTransform=factory(name,dependencies,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o}=e,l=createVariance({typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o});return t(name,{"...any":function(e){e=lastDimToZeroBase(e);try{return l.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),allFactories=Object.freeze({__proto__:null,createTyped:createTyped,createResultSet:createResultSet,createBigNumberClass:createBigNumberClass,createComplexClass:createComplexClass,createFractionClass:createFractionClass,createRangeClass:createRangeClass,createMatrixClass:createMatrixClass,createDenseMatrixClass:createDenseMatrixClass,createClone:createClone,createIsInteger:createIsInteger,createIsNegative:createIsNegative,createIsNumeric:createIsNumeric,createHasNumericValue:createHasNumericValue,createIsPositive:createIsPositive,createIsZero:createIsZero,createIsNaN:createIsNaN,createTypeOf:createTypeOf,createEqualScalar:createEqualScalar,createSparseMatrixClass:createSparseMatrixClass,createNumber:createNumber,createString:createString,createBoolean:createBoolean,createBignumber:createBignumber,createComplex:createComplex,createFraction:createFraction,createMatrix:createMatrix,createMatrixFromFunction:createMatrixFromFunction,createMatrixFromRows:createMatrixFromRows,createMatrixFromColumns:createMatrixFromColumns,createSplitUnit:createSplitUnit,createUnaryMinus:createUnaryMinus,createUnaryPlus:createUnaryPlus,createAbs:createAbs,createApply:createApply,createAddScalar:createAddScalar,createCbrt:createCbrt,createCeil:createCeil,createCube:createCube,createExp:createExp,createExpm1:createExpm1,createFix:createFix,createFloor:createFloor,createGcd:createGcd,createLcm:createLcm,createLog10:createLog10,createLog2:createLog2,createMod:createMod,createMultiplyScalar:createMultiplyScalar,createMultiply:createMultiply,createNthRoot:createNthRoot,createSign:createSign,createSqrt:createSqrt,createSquare:createSquare,createSubtract:createSubtract,createXgcd:createXgcd,createInvmod:createInvmod,createDotMultiply:createDotMultiply,createBitAnd:createBitAnd,createBitNot:createBitNot,createBitOr:createBitOr,createBitXor:createBitXor,createArg:createArg,createConj:createConj,createIm:createIm,createRe:createRe,createNot:createNot,createOr:createOr,createXor:createXor,createConcat:createConcat,createColumn:createColumn,createCount:createCount,createCross:createCross,createDiag:createDiag,createFilter:createFilter,createFlatten:createFlatten,createForEach:createForEach,createGetMatrixDataType:createGetMatrixDataType,createIdentity:createIdentity,createKron:createKron,createMap:createMap,createDiff:createDiff,createOnes:createOnes,createRange:createRange,createReshape:createReshape,createResize:createResize,createRotate:createRotate,createRotationMatrix:createRotationMatrix,createRow:createRow,createSize:createSize,createSqueeze:createSqueeze,createSubset:createSubset,createTranspose:createTranspose,createCtranspose:createCtranspose,createZeros:createZeros,createFft:createFft,createIfft:createIfft,createErf:createErf,createMode:createMode,createProd:createProd,createFormat:createFormat,createBin:createBin,createOct:createOct,createHex:createHex,createPrint:createPrint,createTo:createTo,createIsPrime:createIsPrime,createNumeric:createNumeric,createDivideScalar:createDivideScalar,createPow:createPow,createRound:createRound,createLog:createLog,createLog1p:createLog1p,createNthRoots:createNthRoots,createDotPow:createDotPow,createDotDivide:createDotDivide,createLsolve:createLsolve,createUsolve:createUsolve,createLsolveAll:createLsolveAll,createUsolveAll:createUsolveAll,createLeftShift:createLeftShift,createRightArithShift:createRightArithShift,createRightLogShift:createRightLogShift,createAnd:createAnd,createCompare:createCompare,createCompareNatural:createCompareNatural,createCompareText:createCompareText,createEqual:createEqual,createEqualText:createEqualText,createSmaller:createSmaller,createSmallerEq:createSmallerEq,createLarger:createLarger,createLargerEq:createLargerEq,createDeepEqual:createDeepEqual,createUnequal:createUnequal,createPartitionSelect:createPartitionSelect,createSort:createSort,createMax:createMax,createMin:createMin,createImmutableDenseMatrixClass:createImmutableDenseMatrixClass,createIndexClass:createIndexClass,createFibonacciHeapClass:createFibonacciHeapClass,createSpaClass:createSpaClass,createUnitClass:createUnitClass,createUnitFunction:createUnitFunction,createSparse:createSparse,createCreateUnit:createCreateUnit,createAcos:createAcos,createAcosh:createAcosh,createAcot:createAcot,createAcoth:createAcoth,createAcsc:createAcsc,createAcsch:createAcsch,createAsec:createAsec,createAsech:createAsech,createAsin:createAsin,createAsinh:createAsinh,createAtan:createAtan,createAtan2:createAtan2,createAtanh:createAtanh,createCos:createCos,createCosh:createCosh,createCot:createCot,createCoth:createCoth,createCsc:createCsc,createCsch:createCsch,createSec:createSec,createSech:createSech,createSin:createSin,createSinh:createSinh,createTan:createTan,createTanh:createTanh,createSetCartesian:createSetCartesian,createSetDifference:createSetDifference,createSetDistinct:createSetDistinct,createSetIntersect:createSetIntersect,createSetIsSubset:createSetIsSubset,createSetMultiplicity:createSetMultiplicity,createSetPowerset:createSetPowerset,createSetSize:createSetSize,createSetSymDifference:createSetSymDifference,createSetUnion:createSetUnion,createAdd:createAdd,createHypot:createHypot,createNorm:createNorm,createDot:createDot,createTrace:createTrace,createIndex:createIndex,createNode:createNode,createAccessorNode:createAccessorNode,createArrayNode:createArrayNode,createAssignmentNode:createAssignmentNode,createBlockNode:createBlockNode,createConditionalNode:createConditionalNode,createConstantNode:createConstantNode,createFunctionAssignmentNode:createFunctionAssignmentNode,createIndexNode:createIndexNode,createObjectNode:createObjectNode,createOperatorNode:createOperatorNode,createParenthesisNode:createParenthesisNode,createRangeNode:createRangeNode,createRelationalNode:createRelationalNode,createSymbolNode:createSymbolNode,createFunctionNode:createFunctionNode,createParse:createParse,createCompile:createCompile,createEvaluate:createEvaluate,createParserClass:createParserClass,createParser:createParser,createLup:createLup,createQr:createQr,createSlu:createSlu,createLusolve:createLusolve,createHelpClass:createHelpClass,createChainClass:createChainClass,createHelp:createHelp,createChain:createChain,createDet:createDet,createInv:createInv,createPinv:createPinv,createEigs:createEigs,createExpm:createExpm,createSqrtm:createSqrtm,createDivide:createDivide,createDistance:createDistance,createIntersect:createIntersect,createSum:createSum,createCumSum:createCumSum,createMean:createMean,createMedian:createMedian,createMad:createMad,createVariance:createVariance,createQuantileSeq:createQuantileSeq,createStd:createStd,createCombinations:createCombinations,createCombinationsWithRep:createCombinationsWithRep,createGamma:createGamma,createLgamma:createLgamma,createFactorial:createFactorial,createKldivergence:createKldivergence,createMultinomial:createMultinomial,createPermutations:createPermutations,createPickRandom:createPickRandom,createRandom:createRandom,createRandomInt:createRandomInt,createStirlingS2:createStirlingS2,createBellNumbers:createBellNumbers,createCatalan:createCatalan,createComposition:createComposition,createLeafCount:createLeafCount,createSimplify:createSimplify,createSimplifyCore:createSimplifyCore,createResolve:createResolve,createSymbolicEqual:createSymbolicEqual,createDerivative:createDerivative,createRationalize:createRationalize,createReviver:createReviver,createReplacer:createReplacer,createE:createE,createUppercaseE:createUppercaseE,createFalse:createFalse,createI:createI,createInfinity:createInfinity,createLN10:createLN10,createLN2:createLN2,createLOG10E:createLOG10E,createLOG2E:createLOG2E,createNaN:createNaN,createNull:createNull,createPhi:createPhi,createPi:createPi,createUppercasePi:createUppercasePi,createSQRT1_2:createSQRT1_2,createSQRT2:createSQRT2,createTau:createTau,createTrue:createTrue,createVersion:createVersion,createAtomicMass:createAtomicMass,createAvogadro:createAvogadro,createBohrMagneton:createBohrMagneton,createBohrRadius:createBohrRadius,createBoltzmann:createBoltzmann,createClassicalElectronRadius:createClassicalElectronRadius,createConductanceQuantum:createConductanceQuantum,createCoulomb:createCoulomb,createDeuteronMass:createDeuteronMass,createEfimovFactor:createEfimovFactor,createElectricConstant:createElectricConstant,createElectronMass:createElectronMass,createElementaryCharge:createElementaryCharge,createFaraday:createFaraday,createFermiCoupling:createFermiCoupling,createFineStructure:createFineStructure,createFirstRadiation:createFirstRadiation,createGasConstant:createGasConstant,createGravitationConstant:createGravitationConstant,createGravity:createGravity,createHartreeEnergy:createHartreeEnergy,createInverseConductanceQuantum:createInverseConductanceQuantum,createKlitzing:createKlitzing,createLoschmidt:createLoschmidt,createMagneticConstant:createMagneticConstant,createMagneticFluxQuantum:createMagneticFluxQuantum,createMolarMass:createMolarMass,createMolarMassC12:createMolarMassC12,createMolarPlanckConstant:createMolarPlanckConstant,createMolarVolume:createMolarVolume,createNeutronMass:createNeutronMass,createNuclearMagneton:createNuclearMagneton,createPlanckCharge:createPlanckCharge,createPlanckConstant:createPlanckConstant,createPlanckLength:createPlanckLength,createPlanckMass:createPlanckMass,createPlanckTemperature:createPlanckTemperature,createPlanckTime:createPlanckTime,createProtonMass:createProtonMass,createQuantumOfCirculation:createQuantumOfCirculation,createReducedPlanckConstant:createReducedPlanckConstant,createRydberg:createRydberg,createSackurTetrode:createSackurTetrode,createSecondRadiation:createSecondRadiation,createSpeedOfLight:createSpeedOfLight,createStefanBoltzmann:createStefanBoltzmann,createThomsonCrossSection:createThomsonCrossSection,createVacuumImpedance:createVacuumImpedance,createWeakMixingAngle:createWeakMixingAngle,createWienDisplacement:createWienDisplacement,createApplyTransform:createApplyTransform,createColumnTransform:createColumnTransform,createFilterTransform:createFilterTransform,createForEachTransform:createForEachTransform,createIndexTransform:createIndexTransform,createMapTransform:createMapTransform,createMaxTransform:createMaxTransform,createMeanTransform:createMeanTransform,createMinTransform:createMinTransform,createRangeTransform:createRangeTransform,createRowTransform:createRowTransform,createSubsetTransform:createSubsetTransform,createConcatTransform:createConcatTransform,createDiffTransform:createDiffTransform,createStdTransform:createStdTransform,createSumTransform:createSumTransform,createCumSumTransform:createCumSumTransform,createVarianceTransform:createVarianceTransform}),BigNumber=createBigNumberClass({config:config$2}),Complex=createComplexClass({}),e=createE({BigNumber:BigNumber,config:config$2}),_false=createFalse({}),fineStructure=createFineStructure({BigNumber:BigNumber,config:config$2}),Fraction=createFractionClass({}),i=createI({Complex:Complex}),_Infinity=createInfinity({BigNumber:BigNumber,config:config$2}),LN10=createLN10({BigNumber:BigNumber,config:config$2}),LOG10E=createLOG10E({BigNumber:BigNumber,config:config$2}),Matrix=createMatrixClass({}),_NaN=createNaN({BigNumber:BigNumber,config:config$2}),_null=createNull({}),phi=createPhi({BigNumber:BigNumber,config:config$2}),Range=createRangeClass({}),ResultSet=createResultSet({}),SQRT1_2=createSQRT1_2({BigNumber:BigNumber,config:config$2}),sackurTetrode=createSackurTetrode({BigNumber:BigNumber,config:config$2}),tau=createTau({BigNumber:BigNumber,config:config$2}),_true=createTrue({}),version$1=createVersion({}),DenseMatrix=createDenseMatrixClass({Matrix:Matrix}),efimovFactor=createEfimovFactor({BigNumber:BigNumber,config:config$2}),LN2=createLN2({BigNumber:BigNumber,config:config$2}),pi=createPi({BigNumber:BigNumber,config:config$2}),replacer=createReplacer({}),SQRT2=createSQRT2({BigNumber:BigNumber,config:config$2}),typed=createTyped({BigNumber:BigNumber,Complex:Complex,DenseMatrix:DenseMatrix,Fraction:Fraction}),unaryPlus=createUnaryPlus({BigNumber:BigNumber,config:config$2,typed:typed}),weakMixingAngle=createWeakMixingAngle({BigNumber:BigNumber,config:config$2}),abs$1=createAbs({typed:typed}),acos$1=createAcos({Complex:Complex,config:config$2,typed:typed}),acot$1=createAcot({BigNumber:BigNumber,typed:typed}),acsc$1=createAcsc({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),addScalar=createAddScalar({typed:typed}),arg=createArg({typed:typed}),asech$1=createAsech({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),asinh$1=createAsinh({typed:typed}),atan$1=createAtan({typed:typed}),atanh$1=createAtanh({Complex:Complex,config:config$2,typed:typed}),bignumber=createBignumber({BigNumber:BigNumber,typed:typed}),bitNot=createBitNot({typed:typed}),boolean=createBoolean({typed:typed}),clone$1=createClone({typed:typed}),combinations=createCombinations({typed:typed}),complex=createComplex({Complex:Complex,typed:typed}),conj$1=createConj({typed:typed}),cosh$1=createCosh({typed:typed}),coth$1=createCoth({BigNumber:BigNumber,typed:typed}),csc$1=createCsc({BigNumber:BigNumber,typed:typed}),cube=createCube({typed:typed}),equalScalar=createEqualScalar({config:config$2,typed:typed}),erf$1=createErf({typed:typed}),exp$1=createExp({typed:typed}),expm1=createExpm1({Complex:Complex,typed:typed}),filter$1=createFilter({typed:typed}),forEach=createForEach({typed:typed}),format=createFormat({typed:typed}),getMatrixDataType=createGetMatrixDataType({typed:typed}),hex=createHex({format:format,typed:typed}),im$1=createIm({typed:typed}),isInteger=createIsInteger({typed:typed}),isNegative=createIsNegative({typed:typed}),isPositive=createIsPositive({typed:typed}),isZero=createIsZero({typed:typed}),LOG2E=createLOG2E({BigNumber:BigNumber,config:config$2}),lgamma=createLgamma({Complex:Complex,typed:typed}),log10$1=createLog10({Complex:Complex,config:config$2,typed:typed}),log2=createLog2({Complex:Complex,config:config$2,typed:typed}),map$1=createMap({typed:typed}),multiplyScalar=createMultiplyScalar({typed:typed}),not=createNot({typed:typed}),number=createNumber({typed:typed}),oct=createOct({format:format,typed:typed}),pickRandom=createPickRandom({config:config$2,typed:typed}),print=createPrint({typed:typed}),random$1=createRandom({config:config$2,typed:typed}),re$1=createRe({typed:typed}),sec$1=createSec({BigNumber:BigNumber,typed:typed}),sign$1=createSign({BigNumber:BigNumber,Fraction:Fraction,complex:complex,typed:typed}),sin$1=createSin({typed:typed}),SparseMatrix=createSparseMatrixClass({Matrix:Matrix,equalScalar:equalScalar,typed:typed}),splitUnit=createSplitUnit({typed:typed}),square=createSquare({typed:typed}),string=createString({typed:typed}),tan$1=createTan({typed:typed}),typeOf=createTypeOf({typed:typed}),acosh$1=createAcosh({Complex:Complex,config:config$2,typed:typed}),acsch$1=createAcsch({BigNumber:BigNumber,typed:typed}),apply=createApply({isInteger:isInteger,typed:typed}),asec$1=createAsec({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),bin=createBin({format:format,typed:typed}),combinationsWithRep=createCombinationsWithRep({typed:typed}),cos$1=createCos({typed:typed}),csch$1=createCsch({BigNumber:BigNumber,typed:typed}),isNaN$2=createIsNaN({typed:typed}),isPrime=createIsPrime({typed:typed}),randomInt=createRandomInt({config:config$2,typed:typed}),sech$1=createSech({BigNumber:BigNumber,typed:typed}),sinh$1=createSinh({typed:typed}),sparse=createSparse({SparseMatrix:SparseMatrix,typed:typed}),sqrt$1=createSqrt({Complex:Complex,config:config$2,typed:typed}),tanh$1=createTanh({typed:typed}),unaryMinus=createUnaryMinus({typed:typed}),acoth$1=createAcoth({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),cot$1=createCot({BigNumber:BigNumber,typed:typed}),fraction=createFraction({Fraction:Fraction,typed:typed}),isNumeric=createIsNumeric({typed:typed}),matrix$2=createMatrix({DenseMatrix:DenseMatrix,Matrix:Matrix,SparseMatrix:SparseMatrix,typed:typed}),matrixFromFunction=createMatrixFromFunction({isZero:isZero,matrix:matrix$2,typed:typed}),mod$1=createMod({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),nthRoot=createNthRoot({BigNumber:BigNumber,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),numeric=createNumeric({bignumber:bignumber,fraction:fraction,number:number}),or=createOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),prod=createProd({config:config$2,multiplyScalar:multiplyScalar,numeric:numeric,typed:typed}),reshape=createReshape({isInteger:isInteger,matrix:matrix$2,typed:typed}),size$1=createSize({matrix:matrix$2,config:config$2,typed:typed}),smaller=createSmaller({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),squeeze=createSqueeze({matrix:matrix$2,typed:typed}),subset=createSubset({matrix:matrix$2,typed:typed}),subtract$1=createSubtract({DenseMatrix:DenseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),to=createTo({matrix:matrix$2,typed:typed}),transpose=createTranspose({matrix:matrix$2,typed:typed}),xgcd=createXgcd({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),zeros=createZeros({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),and=createAnd({equalScalar:equalScalar,matrix:matrix$2,not:not,typed:typed,zeros:zeros}),bitAnd=createBitAnd({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitXor=createBitXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),cbrt=createCbrt({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,config:config$2,isNegative:isNegative,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),compare=createCompare({BigNumber:BigNumber,DenseMatrix:DenseMatrix,Fraction:Fraction,config:config$2,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),compareText=createCompareText({matrix:matrix$2,typed:typed}),concat=createConcat({isInteger:isInteger,matrix:matrix$2,typed:typed}),count=createCount({prod:prod,size:size$1,typed:typed}),ctranspose=createCtranspose({conj:conj$1,transpose:transpose,typed:typed}),diag=createDiag({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,matrix:matrix$2,typed:typed}),divideScalar=createDivideScalar({numeric:numeric,typed:typed}),dotDivide=createDotDivide({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),equal$1=createEqual({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),fft=createFft({addScalar:addScalar,divideScalar:divideScalar,exp:exp$1,i:i,matrix:matrix$2,multiplyScalar:multiplyScalar,tau:tau,typed:typed}),flatten$3=createFlatten({matrix:matrix$2,typed:typed}),gcd=createGcd({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),hasNumericValue=createHasNumericValue({isNumeric:isNumeric,typed:typed}),hypot=createHypot({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,isPositive:isPositive,multiplyScalar:multiplyScalar,smaller:smaller,sqrt:sqrt$1,typed:typed}),ifft=createIfft({conj:conj$1,dotDivide:dotDivide,fft:fft,typed:typed}),kron=createKron({matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),largerEq=createLargerEq({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),leftShift=createLeftShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),lsolve=createLsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromColumns=createMatrixFromColumns({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),min$1=createMin({config:config$2,numeric:numeric,smaller:smaller,typed:typed}),mode=createMode({isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),nthRoots=createNthRoots({Complex:Complex,config:config$2,divideScalar:divideScalar,typed:typed}),ones=createOnes({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),partitionSelect=createPartitionSelect({compare:compare,isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),resize=createResize({config:config$2,matrix:matrix$2}),rightArithShift=createRightArithShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),round$1=createRound({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),smallerEq=createSmallerEq({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),unequal=createUnequal({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),usolve=createUsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),xor=createXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),add$1=createAdd({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),atan2$1=createAtan2({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitOr=createBitOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),catalan=createCatalan({addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,isInteger:isInteger,isNegative:isNegative,multiplyScalar:multiplyScalar,typed:typed}),compareNatural=createCompareNatural({compare:compare,typed:typed}),cumsum=createCumSum({add:add$1,typed:typed,unaryPlus:unaryPlus}),deepEqual=createDeepEqual({equal:equal$1,typed:typed}),diff=createDiff({matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),dot=createDot({addScalar:addScalar,conj:conj$1,multiplyScalar:multiplyScalar,size:size$1,typed:typed}),equalText=createEqualText({compareText:compareText,isZero:isZero,typed:typed}),floor=createFloor({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),identity$1=createIdentity({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,config:config$2,matrix:matrix$2,typed:typed}),invmod=createInvmod({BigNumber:BigNumber,add:add$1,config:config$2,equal:equal$1,isInteger:isInteger,mod:mod$1,smaller:smaller,typed:typed,xgcd:xgcd}),larger=createLarger({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),log$1=createLog({Complex:Complex,config:config$2,divideScalar:divideScalar,typed:typed}),lsolveAll=createLsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromRows=createMatrixFromRows({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),multiply$1=createMultiply({addScalar:addScalar,dot:dot,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),qr=createQr({addScalar:addScalar,complex:complex,conj:conj$1,divideScalar:divideScalar,equal:equal$1,identity:identity$1,isZero:isZero,matrix:matrix$2,multiplyScalar:multiplyScalar,sign:sign$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus,zeros:zeros}),range$1=createRange({bignumber:bignumber,matrix:matrix$2,config:config$2,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),rightLogShift=createRightLogShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),setSize=createSetSize({compareNatural:compareNatural,typed:typed}),slu=createSlu({SparseMatrix:SparseMatrix,abs:abs$1,add:add$1,divideScalar:divideScalar,larger:larger,largerEq:largerEq,multiply:multiply$1,subtract:subtract$1,transpose:transpose,typed:typed}),sum=createSum({add:add$1,config:config$2,numeric:numeric,typed:typed}),trace=createTrace({add:add$1,matrix:matrix$2,typed:typed}),usolveAll=createUsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),asin$1=createAsin({Complex:Complex,config:config$2,typed:typed}),ceil=createCeil({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),composition=createComposition({addScalar:addScalar,combinations:combinations,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,larger:larger,typed:typed}),cross=createCross({matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),det=createDet({divideScalar:divideScalar,isZero:isZero,matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),distance=createDistance({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,multiplyScalar:multiplyScalar,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),dotMultiply=createDotMultiply({equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),FibonacciHeap=createFibonacciHeapClass({larger:larger,smaller:smaller}),fix=createFix({Complex:Complex,DenseMatrix:DenseMatrix,ceil:ceil,equalScalar:equalScalar,floor:floor,matrix:matrix$2,typed:typed,zeros:zeros}),ImmutableDenseMatrix=createImmutableDenseMatrixClass({DenseMatrix:DenseMatrix,smaller:smaller}),Index=createIndexClass({ImmutableDenseMatrix:ImmutableDenseMatrix}),intersect=createIntersect({abs:abs$1,add:add$1,addScalar:addScalar,config:config$2,divideScalar:divideScalar,equalScalar:equalScalar,flatten:flatten$3,isNumeric:isNumeric,isZero:isZero,matrix:matrix$2,multiply:multiply$1,multiplyScalar:multiplyScalar,smaller:smaller,subtract:subtract$1,typed:typed}),lcm=createLcm({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),log1p=createLog1p({Complex:Complex,config:config$2,divideScalar:divideScalar,log:log$1,typed:typed}),max$1=createMax({config:config$2,larger:larger,numeric:numeric,typed:typed}),quantileSeq=createQuantileSeq({add:add$1,compare:compare,multiply:multiply$1,partitionSelect:partitionSelect,typed:typed}),row=createRow({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),setCartesian=createSetCartesian({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setDistinct=createSetDistinct({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setIsSubset=createSetIsSubset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setPowerset=createSetPowerset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),sort=createSort({compare:compare,compareNatural:compareNatural,matrix:matrix$2,typed:typed}),column=createColumn({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index=createIndex({Index:Index,typed:typed}),inv=createInv({abs:abs$1,addScalar:addScalar,det:det,divideScalar:divideScalar,identity:identity$1,matrix:matrix$2,multiply:multiply$1,typed:typed,unaryMinus:unaryMinus}),pinv=createPinv({Complex:Complex,add:add$1,ctranspose:ctranspose,deepEqual:deepEqual,divideScalar:divideScalar,dot:dot,dotDivide:dotDivide,equal:equal$1,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),pow$1=createPow({Complex:Complex,config:config$2,fraction:fraction,identity:identity$1,inv:inv,matrix:matrix$2,multiply:multiply$1,number:number,typed:typed}),setDifference=createSetDifference({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setMultiplicity=createSetMultiplicity({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),Spa=createSpaClass({FibonacciHeap:FibonacciHeap,addScalar:addScalar,equalScalar:equalScalar}),sqrtm=createSqrtm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,max:max$1,multiply:multiply$1,size:size$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed}),Unit=createUnitClass({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,abs:abs$1,addScalar:addScalar,config:config$2,divideScalar:divideScalar,equal:equal$1,fix:fix,format:format,isNumeric:isNumeric,multiplyScalar:multiplyScalar,number:number,pow:pow$1,round:round$1,subtract:subtract$1}),vacuumImpedance=createVacuumImpedance({BigNumber:BigNumber,Unit:Unit,config:config$2}),wienDisplacement=createWienDisplacement({BigNumber:BigNumber,Unit:Unit,config:config$2}),atomicMass=createAtomicMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),bohrMagneton=createBohrMagneton({BigNumber:BigNumber,Unit:Unit,config:config$2}),boltzmann=createBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$2}),conductanceQuantum=createConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),createUnit=createCreateUnit({Unit:Unit,typed:typed}),deuteronMass=createDeuteronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),dotPow=createDotPow({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,pow:pow$1,typed:typed}),electricConstant=createElectricConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),elementaryCharge=createElementaryCharge({BigNumber:BigNumber,Unit:Unit,config:config$2}),expm=createExpm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,multiply:multiply$1,typed:typed}),faraday=createFaraday({BigNumber:BigNumber,Unit:Unit,config:config$2}),firstRadiation=createFirstRadiation({BigNumber:BigNumber,Unit:Unit,config:config$2}),gamma$1=createGamma({BigNumber:BigNumber,Complex:Complex,config:config$2,multiplyScalar:multiplyScalar,pow:pow$1,typed:typed}),gravitationConstant=createGravitationConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),hartreeEnergy=createHartreeEnergy({BigNumber:BigNumber,Unit:Unit,config:config$2}),klitzing=createKlitzing({BigNumber:BigNumber,Unit:Unit,config:config$2}),loschmidt=createLoschmidt({BigNumber:BigNumber,Unit:Unit,config:config$2}),magneticConstant=createMagneticConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarMass=createMolarMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarPlanckConstant=createMolarPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),neutronMass=createNeutronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),nuclearMagneton=createNuclearMagneton({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckCharge=createPlanckCharge({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckLength=createPlanckLength({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckTemperature=createPlanckTemperature({BigNumber:BigNumber,Unit:Unit,config:config$2}),protonMass=createProtonMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),reducedPlanckConstant=createReducedPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),rydberg=createRydberg({BigNumber:BigNumber,Unit:Unit,config:config$2}),setIntersect=createSetIntersect({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),speedOfLight=createSpeedOfLight({BigNumber:BigNumber,Unit:Unit,config:config$2}),stefanBoltzmann=createStefanBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$2}),thomsonCrossSection=createThomsonCrossSection({BigNumber:BigNumber,Unit:Unit,config:config$2}),avogadro=createAvogadro({BigNumber:BigNumber,Unit:Unit,config:config$2}),bohrRadius=createBohrRadius({BigNumber:BigNumber,Unit:Unit,config:config$2}),coulomb=createCoulomb({BigNumber:BigNumber,Unit:Unit,config:config$2}),divide$1=createDivide({divideScalar:divideScalar,equalScalar:equalScalar,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),electronMass=createElectronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),factorial$1=createFactorial({gamma:gamma$1,typed:typed}),gravity=createGravity({BigNumber:BigNumber,Unit:Unit,config:config$2}),inverseConductanceQuantum=createInverseConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),lup=createLup({DenseMatrix:DenseMatrix,Spa:Spa,SparseMatrix:SparseMatrix,abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),magneticFluxQuantum=createMagneticFluxQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarMassC12=createMolarMassC12({BigNumber:BigNumber,Unit:Unit,config:config$2}),multinomial=createMultinomial({add:add$1,divide:divide$1,factorial:factorial$1,isInteger:isInteger,isPositive:isPositive,multiply:multiply$1,typed:typed}),permutations=createPermutations({factorial:factorial$1,typed:typed}),planckMass=createPlanckMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),quantumOfCirculation=createQuantumOfCirculation({BigNumber:BigNumber,Unit:Unit,config:config$2}),secondRadiation=createSecondRadiation({BigNumber:BigNumber,Unit:Unit,config:config$2}),stirlingS2=createStirlingS2({bignumber:bignumber,addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,factorial:factorial$1,isInteger:isInteger,isNegative:isNegative,larger:larger,multiplyScalar:multiplyScalar,number:number,pow:pow$1,subtract:subtract$1,typed:typed}),unit=createUnitFunction({Unit:Unit,typed:typed}),bellNumbers=createBellNumbers({addScalar:addScalar,isInteger:isInteger,isNegative:isNegative,stirlingS2:stirlingS2,typed:typed}),eigs=createEigs({abs:abs$1,add:add$1,addScalar:addScalar,atan:atan$1,bignumber:bignumber,column:column,complex:complex,config:config$2,cos:cos$1,diag:diag,divideScalar:divideScalar,dot:dot,equal:equal$1,flatten:flatten$3,im:im$1,inv:inv,larger:larger,matrix:matrix$2,matrixFromColumns:matrixFromColumns,multiply:multiply$1,multiplyScalar:multiplyScalar,number:number,qr:qr,re:re$1,sin:sin$1,smaller:smaller,sqrt:sqrt$1,subtract:subtract$1,typed:typed,usolve:usolve,usolveAll:usolveAll}),fermiCoupling=createFermiCoupling({BigNumber:BigNumber,Unit:Unit,config:config$2}),mean=createMean({add:add$1,divide:divide$1,typed:typed}),molarVolume=createMolarVolume({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckConstant=createPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),setSymDifference=createSetSymDifference({Index:Index,concat:concat,setDifference:setDifference,size:size$1,subset:subset,typed:typed}),classicalElectronRadius=createClassicalElectronRadius({BigNumber:BigNumber,Unit:Unit,config:config$2}),lusolve=createLusolve({DenseMatrix:DenseMatrix,lsolve:lsolve,lup:lup,matrix:matrix$2,slu:slu,typed:typed,usolve:usolve}),median=createMedian({add:add$1,compare:compare,divide:divide$1,partitionSelect:partitionSelect,typed:typed}),setUnion=createSetUnion({Index:Index,concat:concat,setIntersect:setIntersect,setSymDifference:setSymDifference,size:size$1,subset:subset,typed:typed}),variance=createVariance({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),kldivergence=createKldivergence({divide:divide$1,dotDivide:dotDivide,isNumeric:isNumeric,log:log$1,matrix:matrix$2,multiply:multiply$1,sum:sum,typed:typed}),norm=createNorm({abs:abs$1,add:add$1,conj:conj$1,ctranspose:ctranspose,eigs:eigs,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiply:multiply$1,pow:pow$1,smaller:smaller,sqrt:sqrt$1,typed:typed}),planckTime=createPlanckTime({BigNumber:BigNumber,Unit:Unit,config:config$2}),rotationMatrix=createRotationMatrix({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,config:config$2,cos:cos$1,matrix:matrix$2,multiplyScalar:multiplyScalar,norm:norm,sin:sin$1,typed:typed,unaryMinus:unaryMinus}),gasConstant=createGasConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),std=createStd({sqrt:sqrt$1,typed:typed,variance:variance}),mad=createMad({abs:abs$1,map:map$1,median:median,subtract:subtract$1,typed:typed}),rotate=createRotate({multiply:multiply$1,rotationMatrix:rotationMatrix,typed:typed}),math$2={},mathWithTransform={},classes={},Chain=createChainClass({math:math$2}),Node=createNode({mathWithTransform:mathWithTransform}),ObjectNode=createObjectNode({Node:Node}),OperatorNode=createOperatorNode({Node:Node}),ParenthesisNode=createParenthesisNode({Node:Node}),RelationalNode=createRelationalNode({Node:Node}),ArrayNode=createArrayNode({Node:Node}),BlockNode=createBlockNode({Node:Node,ResultSet:ResultSet}),ConditionalNode=createConditionalNode({Node:Node}),ConstantNode=createConstantNode({Node:Node}),RangeNode=createRangeNode({Node:Node}),reviver=createReviver({classes:classes}),chain$1=createChain({Chain:Chain,typed:typed}),FunctionAssignmentNode=createFunctionAssignmentNode({Node:Node,typed:typed}),AccessorNode=createAccessorNode({Node:Node,subset:subset}),AssignmentNode=createAssignmentNode({matrix:matrix$2,Node:Node,subset:subset}),IndexNode=createIndexNode({Node:Node,size:size$1}),SymbolNode=createSymbolNode({Unit:Unit,Node:Node,math:math$2}),FunctionNode=createFunctionNode({Node:Node,SymbolNode:SymbolNode,math:math$2}),parse$2=createParse({AccessorNode:AccessorNode,ArrayNode:ArrayNode,AssignmentNode:AssignmentNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,FunctionAssignmentNode:FunctionAssignmentNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,RangeNode:RangeNode,RelationalNode:RelationalNode,SymbolNode:SymbolNode,config:config$2,numeric:numeric,typed:typed}),resolve=createResolve({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,parse:parse$2}),simplifyCore=createSimplifyCore({AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,divide:divide$1,equal:equal$1,isZero:isZero,multiply:multiply$1,pow:pow$1,subtract:subtract$1}),compile=createCompile({parse:parse$2,typed:typed}),Help=createHelpClass({parse:parse$2}),leafCount=createLeafCount({parse:parse$2,typed:typed}),simplify$2=createSimplify({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$2,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,resolve:resolve,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),symbolicEqual=createSymbolicEqual({OperatorNode:OperatorNode,parse:parse$2,simplify:simplify$2,typed:typed}),evaluate$1=createEvaluate({parse:parse$2,typed:typed}),help=createHelp({Help:Help,mathWithTransform:mathWithTransform,typed:typed}),Parser=createParserClass({evaluate:evaluate$1}),rationalize=createRationalize({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$2,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,simplify:simplify$2,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),derivative$1=createDerivative({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,config:config$2,equal:equal$1,isZero:isZero,numeric:numeric,parse:parse$2,simplify:simplify$2,typed:typed}),parser=createParser({Parser:Parser,typed:typed});_extends$1(math$2,{e:e,false:_false,fineStructure:fineStructure,i:i,Infinity:_Infinity,LN10:LN10,LOG10E:LOG10E,NaN:_NaN,null:_null,phi:phi,SQRT1_2:SQRT1_2,sackurTetrode:sackurTetrode,tau:tau,true:_true,E:e,version:version$1,efimovFactor:efimovFactor,LN2:LN2,pi:pi,replacer:replacer,reviver:reviver,SQRT2:SQRT2,typed:typed,unaryPlus:unaryPlus,PI:pi,weakMixingAngle:weakMixingAngle,abs:abs$1,acos:acos$1,acot:acot$1,acsc:acsc$1,addScalar:addScalar,arg:arg,asech:asech$1,asinh:asinh$1,atan:atan$1,atanh:atanh$1,bignumber:bignumber,bitNot:bitNot,boolean:boolean,chain:chain$1,clone:clone$1,combinations:combinations,complex:complex,conj:conj$1,cosh:cosh$1,coth:coth$1,csc:csc$1,cube:cube,equalScalar:equalScalar,erf:erf$1,exp:exp$1,expm1:expm1,filter:filter$1,forEach:forEach,format:format,getMatrixDataType:getMatrixDataType,hex:hex,im:im$1,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,isZero:isZero,LOG2E:LOG2E,lgamma:lgamma,log10:log10$1,log2:log2,map:map$1,multiplyScalar:multiplyScalar,not:not,number:number,oct:oct,pickRandom:pickRandom,print:print,random:random$1,re:re$1,sec:sec$1,sign:sign$1,sin:sin$1,splitUnit:splitUnit,square:square,string:string,tan:tan$1,typeOf:typeOf,acosh:acosh$1,acsch:acsch$1,apply:apply,asec:asec$1,bin:bin,combinationsWithRep:combinationsWithRep,cos:cos$1,csch:csch$1,isNaN:isNaN$2,isPrime:isPrime,randomInt:randomInt,sech:sech$1,sinh:sinh$1,sparse:sparse,sqrt:sqrt$1,tanh:tanh$1,unaryMinus:unaryMinus,acoth:acoth$1,cot:cot$1,fraction:fraction,isNumeric:isNumeric,matrix:matrix$2,matrixFromFunction:matrixFromFunction,mod:mod$1,nthRoot:nthRoot,numeric:numeric,or:or,prod:prod,reshape:reshape,size:size$1,smaller:smaller,squeeze:squeeze,subset:subset,subtract:subtract$1,to:to,transpose:transpose,xgcd:xgcd,zeros:zeros,and:and,bitAnd:bitAnd,bitXor:bitXor,cbrt:cbrt,compare:compare,compareText:compareText,concat:concat,count:count,ctranspose:ctranspose,diag:diag,divideScalar:divideScalar,dotDivide:dotDivide,equal:equal$1,fft:fft,flatten:flatten$3,gcd:gcd,hasNumericValue:hasNumericValue,hypot:hypot,ifft:ifft,kron:kron,largerEq:largerEq,leftShift:leftShift,lsolve:lsolve,matrixFromColumns:matrixFromColumns,min:min$1,mode:mode,nthRoots:nthRoots,ones:ones,partitionSelect:partitionSelect,resize:resize,rightArithShift:rightArithShift,round:round$1,smallerEq:smallerEq,unequal:unequal,usolve:usolve,xor:xor,add:add$1,atan2:atan2$1,bitOr:bitOr,catalan:catalan,compareNatural:compareNatural,cumsum:cumsum,deepEqual:deepEqual,diff:diff,dot:dot,equalText:equalText,floor:floor,identity:identity$1,invmod:invmod,larger:larger,log:log$1,lsolveAll:lsolveAll,matrixFromRows:matrixFromRows,multiply:multiply$1,qr:qr,range:range$1,rightLogShift:rightLogShift,setSize:setSize,slu:slu,sum:sum,trace:trace,usolveAll:usolveAll,asin:asin$1,ceil:ceil,composition:composition,cross:cross,det:det,distance:distance,dotMultiply:dotMultiply,fix:fix,intersect:intersect,lcm:lcm,log1p:log1p,max:max$1,quantileSeq:quantileSeq,row:row,setCartesian:setCartesian,setDistinct:setDistinct,setIsSubset:setIsSubset,setPowerset:setPowerset,sort:sort,column:column,index:index,inv:inv,pinv:pinv,pow:pow$1,setDifference:setDifference,setMultiplicity:setMultiplicity,sqrtm:sqrtm,vacuumImpedance:vacuumImpedance,wienDisplacement:wienDisplacement,atomicMass:atomicMass,bohrMagneton:bohrMagneton,boltzmann:boltzmann,conductanceQuantum:conductanceQuantum,createUnit:createUnit,deuteronMass:deuteronMass,dotPow:dotPow,electricConstant:electricConstant,elementaryCharge:elementaryCharge,expm:expm,faraday:faraday,firstRadiation:firstRadiation,gamma:gamma$1,gravitationConstant:gravitationConstant,hartreeEnergy:hartreeEnergy,klitzing:klitzing,loschmidt:loschmidt,magneticConstant:magneticConstant,molarMass:molarMass,molarPlanckConstant:molarPlanckConstant,neutronMass:neutronMass,nuclearMagneton:nuclearMagneton,planckCharge:planckCharge,planckLength:planckLength,planckTemperature:planckTemperature,protonMass:protonMass,reducedPlanckConstant:reducedPlanckConstant,rydberg:rydberg,setIntersect:setIntersect,speedOfLight:speedOfLight,stefanBoltzmann:stefanBoltzmann,thomsonCrossSection:thomsonCrossSection,avogadro:avogadro,bohrRadius:bohrRadius,coulomb:coulomb,divide:divide$1,electronMass:electronMass,factorial:factorial$1,gravity:gravity,inverseConductanceQuantum:inverseConductanceQuantum,lup:lup,magneticFluxQuantum:magneticFluxQuantum,molarMassC12:molarMassC12,multinomial:multinomial,parse:parse$2,permutations:permutations,planckMass:planckMass,quantumOfCirculation:quantumOfCirculation,resolve:resolve,secondRadiation:secondRadiation,simplifyCore:simplifyCore,stirlingS2:stirlingS2,unit:unit,bellNumbers:bellNumbers,compile:compile,eigs:eigs,fermiCoupling:fermiCoupling,leafCount:leafCount,mean:mean,molarVolume:molarVolume,planckConstant:planckConstant,setSymDifference:setSymDifference,simplify:simplify$2,symbolicEqual:symbolicEqual,classicalElectronRadius:classicalElectronRadius,evaluate:evaluate$1,help:help,lusolve:lusolve,median:median,rationalize:rationalize,setUnion:setUnion,variance:variance,derivative:derivative$1,kldivergence:kldivergence,norm:norm,planckTime:planckTime,rotationMatrix:rotationMatrix,gasConstant:gasConstant,parser:parser,std:std,mad:mad,rotate:rotate,config:config$2}),_extends$1(mathWithTransform,math$2,{filter:createFilterTransform({typed:typed}),forEach:createForEachTransform({typed:typed}),map:createMapTransform({typed:typed}),apply:createApplyTransform({isInteger:isInteger,typed:typed}),diff:createDiffTransform({bignumber:bignumber,matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),subset:createSubsetTransform({matrix:matrix$2,typed:typed}),concat:createConcatTransform({isInteger:isInteger,matrix:matrix$2,typed:typed}),max:createMaxTransform({config:config$2,larger:larger,numeric:numeric,typed:typed}),min:createMinTransform({config:config$2,numeric:numeric,smaller:smaller,typed:typed}),range:createRangeTransform({bignumber:bignumber,matrix:matrix$2,config:config$2,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),sum:createSumTransform({add:add$1,config:config$2,numeric:numeric,typed:typed}),cumsum:createCumSumTransform({add:add$1,typed:typed,unaryPlus:unaryPlus}),row:createRowTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),column:createColumnTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index:createIndexTransform({Index:Index}),mean:createMeanTransform({add:add$1,divide:divide$1,typed:typed}),variance:createVarianceTransform({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),std:createStdTransform({sqrt:sqrt$1,typed:typed,variance:variance})}),_extends$1(classes,{BigNumber:BigNumber,Chain:Chain,Complex:Complex,Fraction:Fraction,Matrix:Matrix,Node:Node,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,Range:Range,RelationalNode:RelationalNode,ResultSet:ResultSet,ArrayNode:ArrayNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,DenseMatrix:DenseMatrix,RangeNode:RangeNode,FunctionAssignmentNode:FunctionAssignmentNode,SparseMatrix:SparseMatrix,AccessorNode:AccessorNode,AssignmentNode:AssignmentNode,IndexNode:IndexNode,FibonacciHeap:FibonacciHeap,ImmutableDenseMatrix:ImmutableDenseMatrix,Index:Index,Spa:Spa,Unit:Unit,SymbolNode:SymbolNode,FunctionNode:FunctionNode,Help:Help,Parser:Parser}),Chain.createProxy(math$2);var all=allFactories;Number.isFinite=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Number.isNaN=Number.isNaN||function(e){return e!=e};var tinyEmitter={exports:{}};function E(){}function mixin$1(e){var t=new tinyEmitter.exports;return e.on=t.on.bind(t),e.off=t.off.bind(t),e.once=t.once.bind(t),e.emit=t.emit.bind(t),e}function importFactory(e,t,n,r){function a(t,a,s){var o;if(s.wrap&&"function"==typeof a&&(a=function(e){var t=function(){for(var t=[],r=0,a=arguments.length;r2&&void 0!==arguments[2]?arguments[2]:t.fn;if(contains$1(i,"."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(i));var o=d(t)?n.expression.transform:n,l=i in n.expression.transform,c=hasOwnProperty$2(o,i)?o[i]:void 0,m=function(){var r={};t.dependencies.map(stripOptionalNotation).forEach((e=>{if(contains$1(e,"."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(e));"math"===e?r.math=n:"mathWithTransform"===e?r.mathWithTransform=n.expression.mathWithTransform:"classes"===e?r.classes=n:r[e]=n[e]}));var s=t(r);if(s&&"function"==typeof s.transform)throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with exports.path="expression.transform"');if(void 0===c||a.override)return s;if(u(c)&&u(s))return e(c,s);if(a.silent)return c;throw new Error('Cannot import "'+i+'": already exists')};t.meta&&!1===t.meta.lazy?(o[i]=m(),c&&l?s(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>o[i]))):(lazy(o,i,m),c&&l?s(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>o[i]))),r[i]=t,n.emit("import",i,m)}function l(e){return"function"==typeof e||"number"==typeof e||"string"==typeof e||"boolean"==typeof e||null===e||isUnit(e)||isComplex(e)||isBigNumber(e)||isFraction(e)||isMatrix(e)||Array.isArray(e)}function u(e){return"function"==typeof e&&"object"==typeof e.signatures}function c(e){return!hasOwnProperty$2(m,e)}function p(e){return!(-1!==e.fn.indexOf(".")||hasOwnProperty$2(m,e.fn)||e.meta&&e.meta.isClass)}function d(e){return void 0!==e&&void 0!==e.meta&&!0===e.meta.isTransformFunction||!1}var m={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return function(e,t){var n=arguments.length;if(1!==n&&2!==n)throw new ArgumentsError("import",n,1,2);t||(t={});var r={};for(var i in function e(n,r,a){if(Array.isArray(r))r.forEach((t=>e(n,t)));else if("object"==typeof r)for(var i in r)hasOwnProperty$2(r,i)&&e(n,r[i],i);else if(isFactory(r)||void 0!==a){var s=isFactory(r)?d(r)?r.fn+".transform":r.fn:a;if(hasOwnProperty$2(n,s)&&n[s]!==r&&!t.silent)throw new Error('Cannot import "'+s+'" twice');n[s]=r}else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}(r,e),r)if(hasOwnProperty$2(r,i)){var s=r[i];if(isFactory(s))o(s,t);else if(l(s))a(i,s,t);else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}}}function create$1(e,t){var n=_extends$1({},DEFAULT_CONFIG,t);if("function"!=typeof Object.create)throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r=mixin$1({isNumber:isNumber$1,isComplex:isComplex,isBigNumber:isBigNumber,isFraction:isFraction,isUnit:isUnit,isString:isString$1,isArray:isArray$1,isMatrix:isMatrix,isCollection:isCollection,isDenseMatrix:isDenseMatrix,isSparseMatrix:isSparseMatrix,isRange:isRange,isIndex:isIndex,isBoolean:isBoolean$1,isResultSet:isResultSet,isHelp:isHelp,isFunction:isFunction$2,isDate:isDate$1,isRegExp:isRegExp$1,isObject:isObject$1,isNull:isNull$1,isUndefined:isUndefined$1,isAccessorNode:isAccessorNode,isArrayNode:isArrayNode,isAssignmentNode:isAssignmentNode,isBlockNode:isBlockNode,isConditionalNode:isConditionalNode,isConstantNode:isConstantNode,isFunctionAssignmentNode:isFunctionAssignmentNode,isFunctionNode:isFunctionNode,isIndexNode:isIndexNode,isNode:isNode,isObjectNode:isObjectNode,isOperatorNode:isOperatorNode,isParenthesisNode:isParenthesisNode,isRangeNode:isRangeNode,isSymbolNode:isSymbolNode,isChain:isChain});r.config=configFactory(n,r.emit),r.expression={transform:{},mathWithTransform:{config:r.config}};var a=[],i=[],s={},o=importFactory((function(){for(var e=arguments.length,t=new Array(e),n=0;n{values$1(s).forEach((e=>{e&&e.meta&&e.meta.recreateOnConfigChange&&o(e,{override:!0})}))})),r.create=create$1.bind(null,e),r.factory=factory,r.import(values$1(deepFlatten(e))),r.ArgumentsError=ArgumentsError,r.DimensionError=DimensionError,r.IndexError=IndexError,r}E.prototype={on:function(e,t,n){var r=this.e||(this.e={});return(r[e]||(r[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var r=this;function a(){r.off(e,a),t.apply(n,arguments)}return a._=t,this.on(e,a,n)},emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||(this.e={}))[e]||[]).slice(),r=0,a=n.length;r3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;if(new Date-n>t)break}for(a=r;a>3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;return 1e3*(3*r-1)/(new Date-n)},numeric._myIndexOf=function(e){var t,n=this.length;for(t=0;tnumeric.largeArray)return n.push("...Large Array..."),!0;for(u=!1,n.push("["),a=0;a0&&(n.push(","),u&&n.push("\n ")),u=e(r[a]);return n.push("]"),!0}for(a in n.push("{"),u=!1,r)r.hasOwnProperty(a)&&(u&&n.push(",\n"),u=!0,n.push(a),n.push(": \n"),e(r[a]));return n.push("}"),!0}(e),n.join("")},numeric.parseDate=function(e){return function e(t){if("string"==typeof t)return Date.parse(t.replace(/-/g,"/"));if(!(t instanceof Array))throw new Error("parseDate: parameter must be arrays of strings");var n,r=[];for(n=0;n0){for(i[l]=[],t=0;t>>8^a[255&(i^e[r])];return-1^i}var n,r,a,i,s,o,l,u,c,p,d=e[0].length,m=e[0][0].length,h=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,m>>24&255,m>>16&255,m>>8&255,255&m,d>>24&255,d>>16&255,d>>8&255,255&d,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];for(p=t(h,12,29),h[29]=p>>24&255,h[30]=p>>16&255,h[31]=p>>8&255,h[32]=255&p,n=1,r=0,l=0;l>8&255,h.push(s),h.push(o),h.push(255&~s),h.push(255&~o),0===l&&h.push(0),u=0;u255?255:s<0?0:Math.round(s)))%65521))%65521,h.push(s);h.push(0)}return c=(r<<16)+n,h.push(c>>24&255),h.push(c>>16&255),h.push(c>>8&255),h.push(255&c),i=h.length-41,h[33]=i>>24&255,h[34]=i>>16&255,h[35]=i>>8&255,h[36]=255&i,p=t(h,37),h.push(p>>24&255),h.push(p>>16&255),h.push(p>>8&255),h.push(255&p),h.push(0),h.push(0),h.push(0),h.push(0),h.push(73),h.push(69),h.push(78),h.push(68),h.push(174),h.push(66),h.push(96),h.push(130),"data:image/png;base64,"+function(e){var t,n,r,a,i,s,o,l=e.length,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="";for(t=0;t>4),s=((15&r)<<2)+((a=e[t+2])>>6),o=63&a,t+1>=l?s=o=64:t+2>=l&&(o=64),c+=u.charAt(n>>2)+u.charAt(i)+u.charAt(s)+u.charAt(o);return c}(h)},numeric._dim=function(e){for(var t=[];"object"==typeof e;)t.push(e.length),e=e[0];return t},numeric.dim=function(e){var t;return"object"==typeof e?"object"==typeof(t=e[0])?"object"==typeof t[0]?numeric._dim(e):[e.length,t.length]:[e.length]:[]},numeric.mapreduce=function(e,t){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+t+';\nif(typeof x === "number") { var xi = x; '+e+'; return accum; }\nif(typeof _s === "undefined") _s = numeric.dim(x);\nif(typeof _k === "undefined") _k = 0;\nvar _n = _s[_k];\nvar i,xi;\nif(_k < _s.length-1) {\n for(i=_n-1;i>=0;i--) {\n accum = arguments.callee(x[i],accum,_s,_k+1);\n } return accum;\n}\nfor(i=_n-1;i>=1;i-=2) { \n xi = x[i];\n '+e+";\n xi = x[i-1];\n "+e+";\n}\nif(i === 0) {\n xi = x[i];\n "+e+"\n}\nreturn accum;")},numeric.mapreduce2=function(e,t){return Function("x","var n = x.length;\nvar i,xi;\n"+t+";\nfor(i=n-1;i!==-1;--i) { \n xi = x[i];\n "+e+";\n}\nreturn accum;")},numeric.same=function e(t,n){var r,a;if(!(t instanceof Array&&n instanceof Array))return!1;if((a=t.length)!==n.length)return!1;for(r=0;r=0;r-=2)i[r+1]=t,i[r]=t;return-1===r&&(i[0]=t),i}for(r=a-1;r>=0;r--)i[r]=numeric.rep(e,t,n+1);return i},numeric.dotMMsmall=function(e,t){var n,r,a,i,s,o,l,u,c,p,d;for(i=e.length,s=t.length,o=t[0].length,l=Array(i),n=i-1;n>=0;n--){for(u=Array(o),c=e[n],a=o-1;a>=0;a--){for(p=c[s-1]*t[s-1][a],r=s-2;r>=1;r-=2)d=r-1,p+=c[r]*t[r][a]+c[d]*t[d][a];0===r&&(p+=c[0]*t[0][a]),u[a]=p}l[n]=u}return l},numeric._getCol=function(e,t,n){var r;for(r=e.length-1;r>0;--r)n[r]=e[r][t],n[--r]=e[r][t];0===r&&(n[0]=e[0][t])},numeric.dotMMbig=function(e,t){var n,r,a,i=numeric._getCol,s=t.length,o=Array(s),l=e.length,u=t[0].length,c=new Array(l),p=numeric.dotVV;for(--s,r=--l;-1!==r;--r)c[r]=Array(u);for(r=--u;-1!==r;--r)for(i(t,r,o),a=l;-1!==a;--a)n=e[a],c[a][r]=p(n,o);return c},numeric.dotMV=function(e,t){var n,r=e.length;t.length;var a=Array(r),i=numeric.dotVV;for(n=r-1;n>=0;n--)a[n]=i(e[n],t);return a},numeric.dotVM=function(e,t){var n,r,a,i,s,o,l;for(a=e.length,i=t[0].length,s=Array(i),r=i-1;r>=0;r--){for(o=e[a-1]*t[a-1][r],n=a-2;n>=1;n-=2)l=n-1,o+=e[n]*t[n][r]+e[l]*t[l][r];0===n&&(o+=e[0]*t[0][r]),s[r]=o}return s},numeric.dotVV=function(e,t){var n,r,a=e.length,i=e[a-1]*t[a-1];for(n=a-2;n>=1;n-=2)r=n-1,i+=e[n]*t[n]+e[r]*t[r];return 0===n&&(i+=e[0]*t[0]),i},numeric.dot=function(e,t){var n=numeric.dim;switch(1e3*n(e).length+n(t).length){case 2002:return t.length<10?numeric.dotMMsmall(e,t):numeric.dotMMbig(e,t);case 2001:return numeric.dotMV(e,t);case 1002:return numeric.dotVM(e,t);case 1001:return numeric.dotVV(e,t);case 1e3:return numeric.mulVS(e,t);case 1:return numeric.mulSV(e,t);case 0:return e*t;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(e){var t,n,r,a,i=e.length,s=Array(i);for(t=i-1;t>=0;t--){for(a=Array(i),n=t+2,r=i-1;r>=n;r-=2)a[r]=0,a[r-1]=0;for(r>t&&(a[r]=0),a[t]=e[t],r=t-1;r>=1;r-=2)a[r]=0,a[r-1]=0;0===r&&(a[0]=0),s[t]=a}return s},numeric.getDiag=function(e){var t,n=Math.min(e.length,e[0].length),r=Array(n);for(t=n-1;t>=1;--t)r[t]=e[t][t],r[--t]=e[t][t];return 0===t&&(r[0]=e[0][0]),r},numeric.identity=function(e){return numeric.diag(numeric.rep([e],1))},numeric.pointwise=function(e,t,n){void 0===n&&(n="");var r,a,i=[],s=/\[i\]$/,o="",l=!1;for(r=0;r=0;i--) ret[i] = arguments.callee("+e.join(",")+",_s,_k+1);\n return ret;\n}\n"+n+"\nfor(i=_n-1;i!==-1;--i) {\n "+t+"\n}\nreturn ret;",Function.apply(null,i)},numeric.pointwise2=function(e,t,n){void 0===n&&(n="");var r,a,i=[],s=/\[i\]$/,o="",l=!1;for(r=0;r=0;s--)e("object"==typeof t?t[s]:t,"object"==typeof n?n[s]:n,r,a+1,i);else i(t,n)},numeric._biforeach2=function e(t,n,r,a,i){if(a===r.length-1)return i(t,n);var s,o=r[a],l=Array(o);for(s=o-1;s>=0;--s)l[s]=e("object"==typeof t?t[s]:t,"object"==typeof n?n[s]:n,r,a+1,i);return l},numeric._foreach=function e(t,n,r,a){var i;if(r!==n.length-1)for(i=n[r]-1;i>=0;i--)e(t[i],n,r+1,a);else a(t)},numeric._foreach2=function e(t,n,r,a){if(r===n.length-1)return a(t);var i,s=n[r],o=Array(s);for(i=s-1;i>=0;i--)o[i]=e(t[i],n,r+1,a);return o},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var e,t;for(e=0;ef&&(h=i,f=o);for(n=d[h],d[h]=d[s],d[s]=n,a=m[h],m[h]=m[s],m[s]=a,e=n[s],o=s;o!==p;++o)n[o]/=e;for(o=p-1;-1!==o;--o)a[o]/=e;for(i=c-1;-1!==i;--i)if(i!==s){for(t=d[i],r=m[i],e=t[s],o=s+1;o!==p;++o)t[o]-=n[o]*e;for(o=p-1;o>0;--o)r[o]-=a[o]*e,r[--o]-=a[o]*e;0===o&&(r[0]-=a[0]*e)}}return m},numeric.det=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: det() only works on square matrices");var n,r,a,i,s,o,l,u,c=t[0],p=1,d=numeric.clone(e);for(r=0;rMath.abs(d[a][r])&&(a=n);for(a!==r&&(l=d[a],d[a]=d[r],d[r]=l,p*=-1),i=d[r],n=r+1;n=1;t-=2){for(a=e[t],r=e[t-1],n=o-1;n>=1;--n)(i=l[n])[t]=a[n],i[t-1]=r[n],(i=l[--n])[t]=a[n],i[t-1]=r[n];0===n&&((i=l[0])[t]=a[0],i[t-1]=r[0])}if(0===t){for(r=e[0],n=o-1;n>=1;--n)l[n][0]=r[n],l[--n][0]=r[n];0===n&&(l[0][0]=r[0])}return l},numeric.negtranspose=function(e){var t,n,r,a,i,s=e.length,o=e[0].length,l=Array(o);for(n=0;n=1;t-=2){for(a=e[t],r=e[t-1],n=o-1;n>=1;--n)(i=l[n])[t]=-a[n],i[t-1]=-r[n],(i=l[--n])[t]=-a[n],i[t-1]=-r[n];0===n&&((i=l[0])[t]=-a[0],i[t-1]=-r[0])}if(0===t){for(r=e[0],n=o-1;n>=1;--n)l[n][0]=-r[n],l[--n][0]=-r[n];0===n&&(l[0][0]=-r[0])}return l},numeric._random=function e(t,n){var r,a,i=t[n],s=Array(i);if(n===t.length-1){for(a=Math.random,r=i-1;r>=1;r-=2)s[r]=a(),s[r-1]=a();return 0===r&&(s[0]=a()),s}for(r=i-1;r>=0;r--)s[r]=e(t,n+1);return s},numeric.random=function(e){return numeric._random(e,0)},numeric.norm2=function(e){return Math.sqrt(numeric.norm2Squared(e))},numeric.linspace=function(e,t,n){if(void 0===n&&(n=Math.max(Math.round(t-e)+1,1)),n<2)return 1===n?[e]:[];var r,a=Array(n);for(r=--n;r>=0;r--)a[r]=(r*t+(n-r)*e)/n;return a},numeric.getBlock=function(e,t,n){var r=numeric.dim(e);return function e(a,i){var s,o=t[i],l=n[i]-o,u=Array(l);if(i===r.length-1){for(s=l;s>=0;s--)u[s]=a[s+o];return u}for(s=l;s>=0;s--)u[s]=e(a[s+o],i+1);return u}(e,0)},numeric.setBlock=function(e,t,n,r){var a=numeric.dim(e);return function e(r,i,s){var o,l=t[s],u=n[s]-l;if(s===a.length-1)for(o=u;o>=0;o--)r[o+l]=i[o];for(o=u;o>=0;o--)e(r[o+l],i[o],s+1)}(e,r,0),e},numeric.getRange=function(e,t,n){var r,a,i,s,o=t.length,l=n.length,u=Array(o);for(r=o-1;-1!==r;--r)for(u[r]=Array(l),i=u[r],s=e[t[r]],a=l-1;-1!==a;--a)i[a]=s[n[a]];return u},numeric.blockMatrix=function(e){var t=numeric.dim(e);if(t.length<4)return numeric.blockMatrix([e]);var n,r,a,i,s,o=t[0],l=t[1];for(n=0,r=0,a=0;a=0;i--){for(a=Array(u),o=e[i],s=u-1;s>=3;--s)a[s]=o*t[s],a[--s]=o*t[s],a[--s]=o*t[s],a[--s]=o*t[s];for(;s>=0;)a[s]=o*t[s],--s;c[i]=a}return c},numeric.T=function(e,t){this.x=e,this.y=t},numeric.t=function(e,t){return new numeric.T(e,t)},numeric.Tbinop=function(e,t,n,r,a){var i;if(numeric.indexOf,"string"!=typeof a)for(i in a="",numeric)numeric.hasOwnProperty(i)&&(e.indexOf(i)>=0||t.indexOf(i)>=0||n.indexOf(i)>=0||r.indexOf(i)>=0)&&i.length>1&&(a+="var "+i+" = numeric."+i+";\n");return Function(["y"],"var x = this;\nif(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n"+a+"\nif(x.y) { if(y.y) { return new numeric.T("+r+");\n }\n return new numeric.T("+n+");\n}\nif(y.y) {\n return new numeric.T("+t+");\n}\nreturn new numeric.T("+e+");\n")},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var e=numeric.mul,t=numeric.div;if(this.y){var n=numeric.add(e(this.x,this.x),e(this.y,this.y));return new numeric.T(t(this.x,n),t(numeric.neg(this.y),n))}return new T(t(1,this.x))},numeric.T.prototype.div=function(e){if(e instanceof numeric.T||(e=new numeric.T(e)),e.y)return this.mul(e.reciprocal());var t=numeric.div;return this.y?new numeric.T(t(this.x,e.x),t(this.y,e.x)):new numeric.T(t(this.x,e.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),e(n)):new numeric.T(e(t))},numeric.T.prototype.transjugate=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),numeric.negtranspose(n)):new numeric.T(e(t))},numeric.Tunop=function(e,t,n){return"string"!=typeof n&&(n=""),Function("var x = this;\n"+n+"\nif(x.y) { "+t+";\n}\n"+e+";\n")},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));","var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\nreturn new numeric.T(numeric.log(r.x),theta.x);"),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);","var f = numeric.norm2Squared;\nreturn Math.sqrt(f(x.x)+f(x.y));"),numeric.T.prototype.inv=function(){var e=this;if(void 0===e.y)return new numeric.T(numeric.inv(e.x));var t,n,r,a,i,s,o,l,u,c,p,d,m,h,f,y,g,b,v=e.x.length,N=numeric.identity(v),T=numeric.rep([v,v],0),C=numeric.clone(e.x),A=numeric.clone(e.y);for(u=0;ud&&(p=c,d=m);for(p!==u&&(b=C[u],C[u]=C[p],C[p]=b,b=A[u],A[u]=A[p],A[p]=b,b=N[u],N[u]=N[p],N[p]=b,b=T[u],T[u]=T[p],T[p]=b),t=C[u],n=A[u],i=N[u],s=T[u],h=t[u],f=n[u],c=u+1;c0;u--)for(i=N[u],s=T[u],c=u-1;c>=0;c--)for(o=N[c],l=T[c],h=C[c][u],f=A[c][u],p=v-1;p>=0;p--)y=i[p],g=s[p],o[p]-=h*y-f*g,l[p]-=h*g+f*y;return new numeric.T(N,T)},numeric.T.prototype.get=function(e){var t,n=this.x,r=this.y,a=0,i=e.length;if(r){for(;a=0?1:-1)*numeric.norm2(e);t[0]+=n;var r=numeric.norm2(t);if(0===r)throw new Error("eig: internal error");return numeric.div(t,r)},numeric.toUpperHessenberg=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var n,r,a,i,s,o,l,u,c,p,d=t[0],m=numeric.clone(e),h=numeric.identity(d);for(r=0;r0){for(s=numeric.house(i),o=numeric.getBlock(m,[r+1,r],[d-1,d-1]),l=numeric.tensor(s,numeric.dot(s,o)),n=r+1;n=4*l?(x=.5*(u+Math.sqrt(u*u-4*l)),S=.5*(u-Math.sqrt(u*u-4*l)),c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,x+S)),numeric.diag(numeric.rep([3],x*S)))):c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,u)),numeric.diag(numeric.rep([3],l))),n=[c[0][0],c[1][0],c[2][0]],r=numeric.house(n),m=[e[0],e[1],e[2]],h=numeric.tensor(r,numeric.dot(r,m)),y=0;y<3;y++)for(d=e[y],f=h[y],b=0;b=0?((y=(s-(d=c<0?-.5*(c-S(p)):-.5*(c+S(p))))*(s-d)+o*o)>(g=l*l+(u-d)*(u-d))?(h=(s-d)/(y=S(y)),f=o/y):(h=l/(g=S(g)),f=(u-d)/g),a=new N([[f,-h],[h,f]]),V.setRows(n,i,a.dot(V.getRows(n,i)))):(d=-.5*c,m=.5*S(-p),(y=(s-d)*(s-d)+o*o)>(g=l*l+(u-d)*(u-d))?(h=(s-d)/(y=S(y+m*m)),f=o/y,d=0,m/=y):(h=l/(g=S(g+m*m)),f=(u-d)/g,d=m/g,m=0),a=new N([[f,-h],[h,f]],[[d,m],[m,-d]]),V.setRows(n,i,a.dot(V.getRows(n,i))))}var w=V.dot(e).dot(V.transjugate()),E=(T=e.length,numeric.T.identity(T));for(i=0;i0)for(r=i-1;r>=0;r--){var D=w.get([r,r]),O=w.get([i,i]);numeric.neq(D.x,O.x)||numeric.neq(D.y,O.y)?(d=w.getRow(r).getBlock([r],[i-1]),m=E.getRow(i).getBlock([r],[i-1]),E.set([i,r],w.get([r,i]).neg().sub(d.dot(m)).div(D.sub(O)))):E.setRow(i,E.getRow(r))}for(i=0;i=i.length;)i[i.length]=0;0!==t[r]&&i[r]++}var s=i.length,o=Array(s+1);for(o[0]=0,n=0;n=l){if(a[c]=m[u],0===u)return;++c,o=p[--u],l=d[u]}else 0===r[s=i[n[o]]]?(r[s]=1,p[u]=o,m[++u]=s,o=t[s],d[u]=l=t[s+1]):++o},numeric.ccsLPSolve=function(e,t,n,r,a,i,s){var o=e[0],l=e[1],u=e[2];o.length;var c,p,d,m,h,f,y,g,b,v=t[0],N=t[1],T=t[2];for(p=v[a],d=v[a+1],r.length=0,c=p;ci&&(s=a,i=o);for(T(b[n])=u){if(a[p]=i[h[c]],0===c)return;++p,l=d[--c],u=m[c]}else 0===r[o=n[l]]?(r[o]=1,d[c]=l,h[++c]=o,l=t[o=i[o]],m[c]=u=t[o+1]):++l}},numeric.ccsLPSolve0=function(e,t,n,r,a,i,s,o){var l=e[0],u=e[1],c=e[2];l.length;var p,d,m,h,f,y,g,b,v,N=t[0],T=t[1],C=t[2];for(d=N[a],m=N[a+1],r.length=0,p=d;pi&&(s=a,i=o);for(T(b[C[n]])n[r]&&(n[r]=t.length),t)t.hasOwnProperty(a)&&e(t[a],n,r+1);return n},numeric.sclone=function e(t,n,r){void 0===n&&(n=0),void 0===r&&(r=numeric.sdim(t).length);var a,i=Array(t.length);if(n===r-1){for(a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);return i}for(a in t)t.hasOwnProperty(a)&&(i[a]=e(t[a],n+1,r));return i},numeric.sdiag=function(e){var t,n,r=e.length,a=Array(r);for(t=r-1;t>=1;t-=2)n=t-1,a[t]=[],a[t][t]=e[t],a[n]=[],a[n][n]=e[n];return 0===t&&(a[0]=[],a[0][0]=e[t]),a},numeric.sidentity=function(e){return numeric.sdiag(numeric.rep([e],1))},numeric.stranspose=function(e){var t,n,r,a=[];for(t in e.length,e)if(e.hasOwnProperty(t))for(n in r=e[t])r.hasOwnProperty(n)&&("object"!=typeof a[n]&&(a[n]=[]),a[n][t]=r[n]);return a},numeric.sLUP=function(e,t){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(e,t){var n=e.length;t.length;var r,a,i,s,o,l,u,c=numeric.stranspose(t),p=c.length,d=Array(n);for(i=n-1;i>=0;i--){for(u=[],r=e[i],o=p-1;o>=0;o--){for(s in l=0,a=c[o],r)r.hasOwnProperty(s)&&s in a&&(l+=r[s]*a[s]);l&&(u[o]=l)}d[i]=u}return d},numeric.sdotMV=function(e,t){var n,r,a,i,s=e.length,o=Array(s);for(r=s-1;r>=0;r--){for(a in i=0,n=e[r])n.hasOwnProperty(a)&&t[a]&&(i+=n[a]*t[a]);i&&(o[r]=i)}return o},numeric.sdotVM=function(e,t){var n,r,a,i,s=[];for(n in e)if(e.hasOwnProperty(n))for(r in a=t[n],i=e[n],a)a.hasOwnProperty(r)&&(s[r]||(s[r]=0),s[r]+=i*a[r]);return s},numeric.sdotVV=function(e,t){var n,r=0;for(n in e)e[n]&&t[n]&&(r+=e[n]*t[n]);return r},numeric.sdot=function(e,t){var n=numeric.sdim(e).length,r=numeric.sdim(t).length;switch(1e3*n+r){case 0:return e*t;case 1001:return numeric.sdotVV(e,t);case 2001:return numeric.sdotMV(e,t);case 1002:return numeric.sdotVM(e,t);case 2002:return numeric.sdotMM(e,t);default:throw new Error("numeric.sdot not implemented for tensors of order "+n+" and "+r)}},numeric.sscatter=function(e){var t,n,r,a,i=e[0].length,s=e.length,o=[];for(n=i-1;n>=0;--n)if(e[s-1][n]){for(a=o,r=0;r=0;--i)n[i]=[];for(i=a;i>=0;--i)n[i].push(r[i]);n[a+1].push(s)}}else e(s,n,r);return r.length>a&&r.pop(),n},numeric.cLU=function(e){var t,n,r,a,i,s,o=e[0],l=e[1],u=e[2],c=o.length,p=0;for(t=0;tp&&(p=o[t]);p++;var d,m=Array(p),h=Array(p),f=numeric.rep([p],1/0),y=numeric.rep([p],-1/0);for(r=0;ry[t]&&(y[t]=n);for(t=0;ty[t+1]&&(y[t+1]=y[t]);for(t=p-1;t>=1;t--)f[t]=0;d--){for(;u[m]>d;)a[d]-=c[m]*a[u[m]],m--;a[d]/=c[m],m--}return a},numeric.cgrid=function(e,t){"number"==typeof e&&(e=[e,e]);var n,r,a,i=numeric.rep(e,-1);for("function"!=typeof t&&(t="L"===t?function(t,n){return t>=e[0]/2||na&&(a=i[r]);for(a++,n=numeric.rep([a],0),r=0;r1;)a[r=s((t+n)/2)]<=e?t=r:n=r;return this._at(e,t)}i=e.length;var o,l=Array(i);for(o=i-1;-1!==o;--o)l[o]=this.at(e[o]);return l},numeric.Spline.prototype.diff=function(){var e,t,n,r=this.x,a=this.yl,i=this.yr,s=this.kl,o=this.kr,l=a.length,u=s,c=o,p=Array(l),d=Array(l),m=numeric.add,h=numeric.mul,f=numeric.div,y=numeric.sub;for(e=l-1;-1!==e;--e)t=r[e+1]-r[e],n=y(i[e+1],a[e]),p[e]=f(m(h(n,6),h(s[e],-4*t),h(o[e+1],-2*t)),t*t),d[e+1]=f(m(h(n,-6),h(s[e],2*t),h(o[e+1],4*t)),t*t);return new numeric.Spline(r,u,c,p,d)},numeric.Spline.prototype.roots=function(){function e(e){return e*e}var t=[],n=this.x,r=this.yl,a=this.yr,i=this.kl,s=this.kr;"number"==typeof r[0]&&(r=[r],a=[a],i=[i],s=[s]);var o,l,u,c,p,d,m,h,f,y,g,b,v,N,T,C,A,V,x,S,w,E,D,O=r.length,I=n.length-1,R=(t=Array(O),Math.sqrt);for(o=0;o!==O;++o){for(c=r[o],p=a[o],d=i[o],m=s[o],h=[],l=0;l!==I;l++){for(l>0&&p[l]*c[l]<0&&h.push(n[l]),C=n[l+1]-n[l],n[l],g=c[l],b=p[l+1],f=d[l]/C,v=(y=m[l+1]/C)+3*g+2*f-3*b,N=3*(y+f+2*(g-b)),(T=e(f-y+3*(g-b))+12*y*g)<=0?A=(V=v/N)>n[l]&&Vn[l]&&Vn[l]&&x0)w=E,V=x;else{for(var _=0;!((D=(V*E-x*w)/(V-x))<=w||D>=E);)if((S=this._at(D,l))*x>0)E=D,x=S,-1===_&&(V*=.5),_=-1;else{if(!(S*V>0))break;w=D,V=S,1===_&&(x*=.5),_=1}h.push(D),w=A[u+1],V=this._at(w,l)}else h.push(w),w=E,V=x;0===x&&h.push(E)}t[o]=h}return"number"==typeof this.yl[0]?t[0]:t},numeric.spline=function(e,t,n,r){var a,i=e.length,s=[],o=[],l=[],u=numeric.sub,c=numeric.mul,p=numeric.add;for(a=i-2;a>=0;a--)o[a]=e[a+1]-e[a],l[a]=u(t[a+1],t[a]);"string"!=typeof n&&"string"!=typeof r||(n=r="periodic");var d=[[],[],[]];switch(typeof n){case"undefined":s[0]=c(3/(o[0]*o[0]),l[0]),d[0].push(0,0),d[1].push(0,1),d[2].push(2/o[0],1/o[0]);break;case"string":s[0]=p(c(3/(o[i-2]*o[i-2]),l[i-2]),c(3/(o[0]*o[0]),l[0])),d[0].push(0,0,0),d[1].push(i-2,0,1),d[2].push(1/o[i-2],2/o[i-2]+2/o[0],1/o[0]);break;default:s[0]=n,d[0].push(0),d[1].push(0),d[2].push(1)}for(a=1;a20)throw new Error("Numerical gradient fails");if(l[a]=t[a]+v,i=e(l),l[a]=t[a]-v,s=e(l),l[a]=t[a],isNaN(i)||isNaN(s))v/=16;else{if(u[a]=(i-s)/(2*v),c=t[a]-v,p=t[a],d=t[a]+v,m=(i-r)/v,h=(r-s)/v,f=o(y(u[a]),y(r),y(i),y(s),y(c),y(p),y(d),1e-8),!(g(o(y(m-u[a]),y(h-u[a]),y(m-h))/f,v/f)>.001))break;v/=16}}return u},numeric.uncmin=function(e,t,n,r,a,i,s){var o=numeric.gradient;void 0===s&&(s={}),void 0===n&&(n=1e-8),void 0===r&&(r=function(t){return o(e,t)}),void 0===a&&(a=1e3);var l,u,c=(t=numeric.clone(t)).length,p=e(t);if(isNaN(p))throw new Error("uncmin: f(x0) is a NaN!");var d=Math.max,m=numeric.norm2;n=d(n,numeric.epsilon);var h,f,y,g=s.Hinv||numeric.identity(c),b=numeric.dot;numeric.inv;var v,N,T,C,A,V,x,S=numeric.sub,w=numeric.add,E=numeric.tensor,D=numeric.div,O=numeric.mul,I=numeric.all,R=numeric.isFinite,_=numeric.neg,M=0,P="";for(f=r(t);M=.1*V*u||isNaN(l));)V*=.5,++M;if(V*x1;)o[r=a(.5*(t+n))]<=e?t=r:n=r;return this._at(e,t)},numeric.dopri=function(e,t,n,r,a,i,s){void 0===a&&(a=1e-6),void 0===i&&(i=1e3);var o,l,u,c,p,d,m,h,f,y,g,b,v,N=[e],T=[n],C=[r(e,n)],A=[],V=[3/40,9/40],x=[44/45,-56/15,32/9],S=[19372/6561,-25360/2187,64448/6561,-212/729],w=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],E=[35/384,0,500/1113,125/192,-2187/6784,11/84],D=[.10013431883002395,0,.3918321794184259,-.02982460176594817,.05893268337240795,-.04497888809104361,5618549.5/235043384],O=[.2,.3,.8,8/9,1,1],I=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40],R=0,_=(t-e)/10,M=0,P=numeric.add,F=numeric.mul,k=Math.min,$=Math.abs,B=numeric.norminf,L=Math.pow,z=numeric.any,U=numeric.lt,j=numeric.and;numeric.sub;var q=new numeric.Dopri(N,T,C,A,-1,"");for("function"==typeof s&&(g=s(e,n));et&&(_=t-e),o=r(e+O[0]*_,P(n,F(.2*_,C[R]))),l=r(e+O[1]*_,P(P(n,F(V[0]*_,C[R])),F(V[1]*_,o))),u=r(e+O[2]*_,P(P(P(n,F(x[0]*_,C[R])),F(x[1]*_,o)),F(x[2]*_,l))),c=r(e+O[3]*_,P(P(P(P(n,F(S[0]*_,C[R])),F(S[1]*_,o)),F(S[2]*_,l)),F(S[3]*_,u))),p=r(e+O[4]*_,P(P(P(P(P(n,F(w[0]*_,C[R])),F(w[1]*_,o)),F(w[2]*_,l)),F(w[3]*_,u)),F(w[4]*_,c))),d=r(e+_,f=P(P(P(P(P(n,F(C[R],_*E[0])),F(l,_*E[2])),F(u,_*E[3])),F(c,_*E[4])),F(p,_*E[5]))),(y="number"==typeof(m=P(P(P(P(P(F(C[R],_*I[0]),F(l,_*I[2])),F(u,_*I[3])),F(c,_*I[4])),F(p,_*I[5])),F(d,_*I[6])))?$(m):B(m))>a){if(e+(_=.2*_*L(a/y,.25))===e){q.msg="Step size became too small";break}}else{if(A[R]=P(P(P(P(P(P(n,F(C[R],_*D[0])),F(l,_*D[2])),F(u,_*D[3])),F(c,_*D[4])),F(p,_*D[5])),F(d,_*D[6])),N[++R]=e+_,T[R]=f,C[R]=d,"function"==typeof s){var G,H,W=e,K=e+.5*_;if(b=s(K,A[R-1]),z(v=j(U(g,0),U(0,b)))||(W=K,g=b,b=s(K=e+_,f),v=j(U(g,0),U(0,b))),z(v)){for(var Z,X,Y=0,Q=1,J=1;;){if("number"==typeof g)H=(J*b*W-Q*g*K)/(J*b-Q*g);else for(H=K,h=g.length-1;-1!==h;--h)g[h]<0&&b[h]>0&&(H=k(H,(J*b[h]*W-Q*g[h]*K)/(J*b[h]-Q*g[h])));if(H<=W||H>=K)break;X=s(H,G=q._at(H,R-1)),z(Z=j(U(g,0),U(0,X)))?(K=H,b=X,v=Z,J=1,-1===Y?Q*=.5:Q=1,Y=-1):(W=H,g=X,Q=1,1===Y?J*=.5:J=1,Y=1)}return f=q._at(.5*(e+H),R-1),q.f[R]=r(H,G),q.x[R]=H,q.y[R]=G,q.ymid[R-1]=f,q.events=v,q.iterations=M,q}}e+=_,n=f,g=b,_=k(.8*_*L(a/y,.25),4*_)}return q.iterations=M,q},numeric.LU=function(e,t){t=t||!1;var n,r,a,i,s,o,l,u,c,p=Math.abs,d=e.length,m=d-1,h=new Array(d);for(t||(e=numeric.clone(e)),a=0;a=0;--n){for(i=o[n],r=n+1;rP)&&(g=P),E=m(e,u(g,x)),T=p(M,S),R=h-1;-1!==R;--R)T[R][R]+=1;_=D(T,d(E,g),!0);var F=d(O,p(t,_)),k=1;for(R=f-1;-1!==R;--R)F[R]<0&&(k=C(k,-.999*F[R]));if(l=c(i,u(_,k)),!A(V(O=c(n,p(t,l)),0)))return{solution:i,message:"",iterations:w};if(i=l,g=0);if(y)return{solution:l,message:"Unbounded",iterations:w}}return{solution:i,message:"maximum iteration count exceeded",iterations:w}},numeric._solveLP=function(e,t,n,r,a){var i=e.length,s=n.length;numeric.sum,numeric.log,numeric.mul;var o=numeric.sub,l=numeric.dot;numeric.div,numeric.add;var u=numeric.rep([i],0).concat([1]),c=numeric.rep([s,1],-1),p=numeric.blockMatrix([[t,c]]),d=n,m=numeric.rep([i],0).concat(Math.max(0,numeric.sup(numeric.neg(n)))+1),h=numeric.__solveLP(u,p,d,r,a,m,!1),f=numeric.clone(h.solution);if(f.length=i,numeric.inf(o(n,l(t,f)))<0)return{solution:NaN,message:"Infeasible",iterations:h.iterations};var y=numeric.__solveLP(e,t,n,r,a-h.iterations,f,!0);return y.iterations+=h.iterations,y},numeric.solveLP=function(e,t,n,r,a,i,s){if(void 0===s&&(s=1e3),void 0===i&&(i=numeric.epsilon),void 0===r)return numeric._solveLP(e,t,n,i,s);var o,l=r.length,u=r[0].length,c=t.length,p=numeric.echelonize(r),d=numeric.rep([u],0),m=p.P,h=[];for(o=m.length-1;-1!==o;--o)d[m[o]]=1;for(o=u-1;-1!==o;--o)0===d[o]&&h.push(o);var f=numeric.getRange,y=numeric.linspace(0,l-1),g=numeric.linspace(0,c-1),b=f(r,y,h),v=f(t,g,m),N=f(t,g,h),T=numeric.dot,C=numeric.sub,A=T(v,p.I),V=C(N,T(A,b)),x=C(n,T(A,a)),S=Array(m.length),w=Array(h.length);for(o=m.length-1;-1!==o;--o)S[o]=e[m[o]];for(o=h.length-1;-1!==o;--o)w[o]=e[h[o]];var E=C(w,T(S,T(p.I,b))),D=numeric._solveLP(E,V,x,i,s),O=D.solution;if(O!=O)return D;var I=T(p.I,C(a,T(b,O))),R=Array(e.length);for(o=m.length-1;-1!==o;--o)R[m[o]]=I[o];for(o=h.length-1;-1!==o;--o)R[h[o]]=O[o];return{solution:R,message:D.message,iterations:D.iterations}},numeric.MPStoLP=function(e){e instanceof String&&e.split("\n");var t,n,r,a,i=0,s=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],o=e.length,l=0,u={},c=[],p=0,d={},m=0,h=[],f=[],y=[];function g(n){throw new Error("MPStoLP: "+n+"\nLine "+t+": "+e[t]+"\nCurrent state: "+s[i]+"\n")}for(t=0;t=i;)e/=2,t/=2,r>>>=1;return(e+r)/t},r},s=t.pow(n,6),a=t.pow(2,a),i=2*a,u(t.random(),e)}([],numeric.seedrandom,256,0,52),function(e){function t(e){if("object"!=typeof e)return e;var n,r=[],a=e.length;for(n=0;nc)h[b]=I;else if(h[b]=-Math.abs(I),I>0){for(g=1;g<=r;g+=1)s[g][y]=-s[g][y];o[y]=-o[y]}}for(y=1;y<=d;y+=1)h[x+p[y]]=0;for(w=0,O=0,y=1;y<=u;y+=1)h[x+y]=1;y-=1){for(I=h[y],v=(b=V+y*(y+3)/2)-y,g=y+1;g<=d;g+=1)I-=h[b]*h[A+g],b+=g;if(I/=h[v],h[A+y]=I,p[y]c)h[x+w]=I;else if(h[x+w]=-Math.abs(I),I>0){for(g=1;g<=r;g+=1)s[g][w]=-s[g][w];o[w]=-o[w]}return 700}for(p[d+=1]=w,b=V+(d-1)*d/2+1,y=1;y<=d-1;y+=1)h[b]=h[y],b+=1;if(d===r)h[b]=h[r];else{for(y=r;y>=d+1&&0!==h[y]&&(M=Math.max(Math.abs(h[y-1]),Math.abs(h[y])),P=Math.min(Math.abs(h[y-1]),Math.abs(h[y])),O=h[y-1]>=0?Math.abs(M*Math.sqrt(1+P*P/(M*M))):-Math.abs(M*Math.sqrt(1+P*P/(M*M))),M=h[y-1]/O,P=h[y]/O,1!==M);y-=1)if(0===M)for(h[y-1]=P*O,g=1;g<=r;g+=1)O=e[g][y-1],e[g][y-1]=e[g][y],e[g][y]=O;else for(h[y-1]=O,F=P/(1+M),g=1;g<=r;g+=1)O=M*e[g][y-1]+P*e[g][y],e[g][y]=F*(e[g][y-1]+O)-e[g][y],e[g][y-1]=O;h[b]=h[d]}return 0}function G(){if(0===h[v=(b=V+T*(T+1)/2+1)+T])return 798;if(M=Math.max(Math.abs(h[v-1]),Math.abs(h[v])),P=Math.min(Math.abs(h[v-1]),Math.abs(h[v])),O=h[v-1]>=0?Math.abs(M*Math.sqrt(1+P*P/(M*M))):-Math.abs(M*Math.sqrt(1+P*P/(M*M))),M=h[v-1]/O,P=h[v]/O,1===M)return 798;if(0===M){for(y=T+1;y<=d;y+=1)O=h[v-1],h[v-1]=h[v],h[v]=O,v+=y;for(y=1;y<=r;y+=1)O=e[y][T],e[y][T]=e[y][T+1],e[y][T+1]=O}else{for(F=P/(1+M),y=T+1;y<=d;y+=1)O=M*h[v-1]+P*h[v],h[v]=F*(h[v-1]+O)-h[v],h[v-1]=O,v+=y;for(y=1;y<=r;y+=1)O=M*e[y][T]+P*e[y][T+1],e[y][T+1]=F*(e[y][T]+O)-e[y][T+1],e[y][T]=O}return 0}function H(){for(v=b-T,y=1;y<=T;y+=1)h[v]=h[b],b+=1,v+=1;return h[S+T]=h[S+T+1],p[T]=p[T+1],(T+=1)(t=Math.abs(t))?e*Math.sqrt(1+t*t/e/e):0==t?e:t*Math.sqrt(1+e*e/t/t)}var y=0,g=0,b=0,v=0,N=0,T=0,C=0;for(i=0;i=0&&(g=-g),b=y*g-C,u[i][i]=y-g,s=l;s=0&&(g=-g),b=y*g-C,u[i][i+1]=y-g,s=l;sv&&(v=N)}for(i=p-1;-1!=i;i+=-1){if(0!=g){for(b=g*u[i][i+1],s=l;s=49)throw"Error: no convergence.";for(v=m[l],g=f(y=(((N=m[o-1])-T)*(N+T)+((g=d[o-1])-(b=d[o]))*(g+b))/(2*b*N),1),y=y<0?((v-T)*(v+T)+b*(N/(y-g)-b))/v:((v-T)*(v+T)+b*(N/(y+g)-b))/v,a=1,C=1,i=l+1;i=0;s--)if(m[s]=0&&n<=MAX_ARRAY_INDEX}}function shallowProperty(e){return function(t){return null==t?void 0:t[e]}}var getByteLength=shallowProperty("byteLength"),isBufferLike=createSizePropertyCheck(getByteLength),typedArrayPattern=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;function isTypedArray(e){return nativeIsView?nativeIsView(e)&&!isDataView$1(e):isBufferLike(e)&&typedArrayPattern.test(toString$1.call(e))}var isTypedArray$1=supportsArrayBuffer?isTypedArray:constant(!1),getLength=shallowProperty("length");function emulatedSet(e){for(var t={},n=e.length,r=0;r":">",'"':""","'":"'","`":"`"},escape=createEscaper(escapeMap),unescapeMap=invert(escapeMap),unescape=createEscaper(unescapeMap),templateSettings=_$1.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},noMatch=/(.)^/,escapes={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},escapeRegExp=/\\|'|\r|\n|\u2028|\u2029/g;function escapeChar(e){return"\\"+escapes[e]}var bareIdentifier=/^\s*(\w|\$)+\s*$/;function template(e,t,n){!t&&n&&(t=n),t=defaults({},t,_$1.templateSettings);var r=RegExp([(t.escape||noMatch).source,(t.interpolate||noMatch).source,(t.evaluate||noMatch).source].join("|")+"|$","g"),a=0,i="__p+='";e.replace(r,(function(t,n,r,s,o){return i+=e.slice(a,o).replace(escapeRegExp,escapeChar),a=o+t.length,n?i+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?i+="'+\n((__t=("+r+"))==null?'':__t)+\n'":s&&(i+="';\n"+s+"\n__p+='"),t})),i+="';\n";var s,o=t.variable;if(o){if(!bareIdentifier.test(o))throw new Error("variable is not a bare identifier: "+o)}else i="with(obj||{}){\n"+i+"}\n",o="obj";i="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{s=new Function(o,"_",i)}catch(e){throw e.source=i,e}var l=function(e){return s.call(this,e,_$1)};return l.source="function("+o+"){\n"+i+"}",l}function result(e,t,n){var r=(t=toPath(t)).length;if(!r)return isFunction$1(n)?n.call(e):n;for(var a=0;a1)flatten$2(o,t-1,n,r),a=r.length;else for(var l=0,u=o.length;lt?(r&&(clearTimeout(r),r=null),o=u,s=e.apply(a,i),r||(a=i=null)):r||!1===n.trailing||(r=setTimeout(l,c)),s};return u.cancel=function(){clearTimeout(r),o=0,r=a=i=null},u}function debounce(e,t,n){var r,a,i,s,o,l=function(){var u=now()-a;t>u?r=setTimeout(l,t-u):(r=null,n||(s=e.apply(o,i)),r||(i=o=null))},u=restArguments((function(u){return o=this,i=u,a=now(),r||(r=setTimeout(l,t),n&&(s=e.apply(o,i))),s}));return u.cancel=function(){clearTimeout(r),r=i=o=null},u}function wrap(e,t){return partial(t,e)}function negate(e){return function(){return!e.apply(this,arguments)}}function compose(){var e=arguments,t=e.length-1;return function(){for(var n=t,r=e[t].apply(this,arguments);n--;)r=e[n].call(this,r);return r}}function after(e,t){return function(){if(--e<1)return t.apply(this,arguments)}}function before(e,t){var n;return function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=null),n}}var once$1=partial(before,2);function findKey(e,t,n){t=cb(t,n);for(var r,a=keys(e),i=0,s=a.length;i0?0:a-1;i>=0&&i0?s=i>=0?i:Math.max(i+o,s):o=i>=0?Math.min(i+1,o):i+o+1;else if(n&&i&&o)return r[i=n(r,a)]===a?i:-1;if(a!=a)return(i=t(slice.call(r,s,o),isNaN$1))>=0?i+s:-1;for(i=e>0?s:o-1;i>=0&&i0?0:s-1;for(a||(r=t[i?i[o]:o],o+=e);o>=0&&o=3;return t(e,optimizeCb(n,a,4),r,i)}}var reduce$1=createReduce(1),reduceRight=createReduce(-1);function filter(e,t,n){var r=[];return t=cb(t,n),each(e,(function(e,n,a){t(e,n,a)&&r.push(e)})),r}function reject(e,t,n){return filter(e,negate(cb(t)),n)}function every(e,t,n){t=cb(t,n);for(var r=!isArrayLike(e)&&keys(e),a=(r||e).length,i=0;i=0}var invoke=restArguments((function(e,t,n){var r,a;return isFunction$1(t)?a=t:(t=toPath(t),r=t.slice(0,-1),t=t[t.length-1]),map(e,(function(e){var i=a;if(!i){if(r&&r.length&&(e=deepGet(e,r)),null==e)return;i=e[t]}return null==i?i:i.apply(e,n)}))}));function pluck(e,t){return map(e,property(t))}function where(e,t){return filter(e,matcher(t))}function max(e,t,n){var r,a,i=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var o=0,l=(e=isArrayLike(e)?e:values(e)).length;oi&&(i=r);else t=cb(t,n),each(e,(function(e,n,r){((a=t(e,n,r))>s||a===-1/0&&i===-1/0)&&(i=e,s=a)}));return i}function min(e,t,n){var r,a,i=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var o=0,l=(e=isArrayLike(e)?e:values(e)).length;or||void 0===n)return 1;if(n1&&(r=optimizeCb(r,t[1])),t=allKeys(e)):(r=keyInObj,t=flatten$2(t,!1,!1),e=Object(e));for(var a=0,i=t.length;a1&&(n=t[1])):(t=map(flatten$2(t,!1,!1),String),r=function(e,n){return!contains(t,n)}),pick(e,r,n)}));function initial(e,t,n){return slice.call(e,0,Math.max(0,e.length-(null==t||n?1:t)))}function first(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[0]:initial(e,e.length-t)}function rest(e,t,n){return slice.call(e,null==t||n?1:t)}function last(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[e.length-1]:rest(e,Math.max(0,e.length-t))}function compact(e){return filter(e,Boolean)}function flatten$1(e,t){return flatten$2(e,t,!1)}var difference=restArguments((function(e,t){return t=flatten$2(t,!0,!0),filter(e,(function(e){return!contains(t,e)}))})),without=restArguments((function(e,t){return difference(e,t)}));function uniq(e,t,n,r){isBoolean(t)||(r=n,n=t,t=!1),null!=n&&(n=cb(n,r));for(var a=[],i=[],s=0,o=getLength(e);sr&&(r=n)):(n>r&&(r=n),r*=i),Math.abs(e-t)<=r}return e===t}var i=e[0],s=e.slice(1),o=t[0],l=t.slice(1);return i===o&&(s.length===l.length&&(n>0&&!r&&"^"===i?!!equal(s[0],l[0],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})&&equal(s[1],l[1]):_.every(_.zip(s,l),(function(e){return equal(e[0],e[1],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})}))))},match$2=function(e,t,n){var r=!1;void 0===n?n={}:n.allow_extended_match&&(r=!0,delete(n=Object.assign({},n)).allow_extended_match);var a=n.variables;if(void 0===a){a={};let e=variables(t);for(let t=0;tObject())),s=n.length,o=!1;function l(u,c,p){let d,m=1,h=1;if((is_associative$1[e]||["tuple","vector","altvector"].includes(e))&&(m=u.length-(s-c-1),h=u.length),void 0!==r.max_group&&(m=r.max_group1?[e].concat(s):s[0],o=match$2(s,n[c],r),i[c][a]=o}if(!o)continue;if(!_.every(_.intersection(Object.keys(p),Object.keys(o)),(function(e){return equal(p[e],o[e])})))continue;let d=Object.assign({},o);Object.assign(d,p);let m=u.filter((e=>!a.includes(e)));if(c===s-1)return{matches:d,skipped:m.reduce((function(e,n){return e.concat([t[n]])}),[])};let h=l(m,c+1,d);if(h)return h}return!1}r.allow_permutations&&("*"===e?o=![...t,...n].some((e=>["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e[0]))):"+"!==e&&"="!==e&&"and"!==e&&"or"!==e&&"ne"!==e&&"union"!==e&&"intersect"!==e||(o=!0));var u={},c=[...Array(t.length).keys()];if(o){let e=l(c,0,{});return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),u)}{let e,n=a?t.length-s:0,r=[];for(let a=0;a<=n&&(e=l(c,0,{}),!e);a++)c=c.slice(1),r.push(t[a]);return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),r.length>0&&(u._skipped_before=r),u)}}function matchImplicitIdentity(e,t,n){var r=t[0],a=t.slice(1);if("+"!==r&&"*"!==r&&"^"!==r)return!1;var i=[];for(let e=0;e0;n--){r=a;for(let e=0;e0||a.length>0)&&(Array.isArray(e)&&(e=e[0]===n[0]?e.slice(1):[e]),e=[n[0]].concat(s,e,a)),i.evaluate_numbers&&(e=evaluate_numbers(e,{max_digits:i.max_digits})),e}return e}))}if(equal(r,a))return a}return a};var math=math$1;const operators$2={"+":function(e){return 1===e.length?e[0]:new math.OperatorNode("+","add",e)},"*":function(e){return new math.OperatorNode("*","multiply",e)},"/":function(e){return new math.OperatorNode("/","divide",e)},"-":function(e){return new math.OperatorNode("-","unaryMinus",[e[0]])},"^":function(e){return new math.OperatorNode("^","pow",e)},vector:function(e){return new math.ArrayNode(e)},altvector:function(e){return new math.ArrayNode(e)},and:function(e){return new math.OperatorNode("and","and",e)},or:function(e){return new math.OperatorNode("or","or",e)},not:function(e){return new math.OperatorNode("not","not",[e[0]])},"<":function(e){return new math.OperatorNode("<","smaller",e)},">":function(e){return new math.OperatorNode(">","larger",e)},le:function(e){return new math.OperatorNode("<=","smallerEq",e)},ge:function(e){return new math.OperatorNode(">=","largerEq",e)},ne:function(e){return new math.OperatorNode("!=","unequal",e)},binom:function(e){const t=new math.SymbolNode("combinations");return new math.FunctionNode(t,e)}},functionConverstions={nCr:"combinations",nPr:"permutations",binom:"combinations"};class astToMathjs$1{constructor({mathjs:e=null}={}){e&&(math=e)}convert(e){if("number"==typeof e)return Number.isFinite(e)?new math.ConstantNode(e):Number.isNaN(e)?new math.SymbolNode("NaN"):e<0?operators$2["-"]([new math.SymbolNode("Infinity")]):new math.SymbolNode("Infinity");if("string"==typeof e)return new math.SymbolNode(e);if("boolean"==typeof e)throw Error("no support for boolean");if(!Array.isArray(e))throw Error("Invalid ast");const t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to mathjs");if("factorial"===n[0])return new math.OperatorNode("!","factorial",[this.convert(n[1])]);let e=functionConverstions[n[0]];e||(e=n[0]);const t=new math.SymbolNode(e),r=n[1];let a;return a="tuple"===r[0]?r.slice(1).map(function(e,t){return this.convert(e)}.bind(this)):[this.convert(r)],new math.FunctionNode(t,a)}if("lts"===t||"gts"===t){const e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");const a=e.slice(1).map(function(e,t){return this.convert(e)}.bind(this));let i=[];for(let n=1;n","larger",a.slice(n-1,n+1))):"lts"===t?i.push(new math.OperatorNode("<=","smallerEq",a.slice(n-1,n+1))):i.push(new math.OperatorNode(">=","largerEq",a.slice(n-1,n+1)));let s=new math.OperatorNode("and","and",i.slice(0,2));for(let e=2;e=","largerEq",[e,s])):l.push(new math.OperatorNode(">","larger",[e,s])),i[2]?l.push(new math.OperatorNode("<=","smallerEq",[e,o])):l.push(new math.OperatorNode("<","smaller",[e,o]));let u=new math.OperatorNode("and","and",l);return"notin"!==t&&"notni"!==t||(u=new math.OperatorNode("not","not",[u])),u}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let e,r;if("subset"===t||"notsubset"===t?(r=n[0],e=n[1]):(r=n[1],e=n[0]),"interval"!==r[0]||"interval"!==e[0])throw Error("Set containment of non-intervals not implemented for conversion to mathjs");let a=r[1],i=r[2],s=e[1],o=e[2];if("tuple"!==a[0]||"tuple"!==i[0]||"tuple"!==s[0]||"tuple"!==o[0])throw Error("Badly formed ast");let l=this.convert(a[1]),u=this.convert(a[2]),c=this.convert(s[1]),p=this.convert(s[2]),d=[];i[1]&&!o[1]?d.push(new math.OperatorNode(">","larger",[l,c])):d.push(new math.OperatorNode(">=","largerEq",[l,c])),i[2]&&!o[2]?d.push(new math.OperatorNode("<","smaller",[u,p])):d.push(new math.OperatorNode("<=","smallerEq",[u,p]));let m=new math.OperatorNode("and","and",d);return"notsubset"!==t&&"notsuperset"!==t||(m=new math.OperatorNode("not","not",[m])),m}if("matrix"===t){let e=n[0],t=e[1],r=e[2],a=n[1];if(!Number.isInteger(t)||!Number.isInteger(r))throw Error("Matrix must have integer dimensions");let i=[];for(let e=1;e<=t;e++){let t=[];for(let n=1;n<=r;n++)t.push(this.convert(a[e][n]));i.push(new math.ArrayNode(t))}return new math.ArrayNode(i)}if(t in operators$2)return operators$2[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var function_normalizations={ln:"log",arccos:"acos",arccosh:"acosh",arcsin:"asin",arcsinh:"asinh",arctan:"atan",arctanh:"atanh",arcsec:"asec",arcsech:"asech",arccsc:"acsc",arccsch:"acsch",arccot:"acot",arccoth:"acoth",cosec:"csc"},create_trig_inverses_for=["cos","cosh","sin","sinh","tan","tanh","sec","sech","csc","csch","cot","coth"],move_exponents_outside_for=["cos","cosh","sin","sinh","tan","tanh","sec","sech","csc","csch","cot","coth"];function normalize_function_names(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){if("sqrt"===r[0])return["^",normalize_function_names(r[1]),.5];var a=normalize_function_names_sub(r[0]);a=["apply",a];var i=r.slice(1).map((function(e){return normalize_function_names(e)}));return i=i.length>1?["tuple"].concat(i):i[0],a.push(i),a}return"^"===n&&"e"===r[0]&&math$1.define_e?["apply","exp",normalize_function_names(r[1])]:"binom"===n?["apply","nCr",["tuple",normalize_function_names(r[0]),normalize_function_names(r[1])]]:[n].concat(r.map((function(e){return normalize_function_names(e)})))}function normalize_function_names_sub(e){if("string"==typeof e)return e in function_normalizations?function_normalizations[e]:e;if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if("^"===t&&2===n.length&&-1===n[1]){let e=normalize_function_names_sub(n[0]);if(create_trig_inverses_for.includes(e))return"a"+e}return[t].concat(n.map((function(e){return normalize_function_names_sub(e)})))}function normalize_applied_functions(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){let e=r[0];if("^"===e[0]){let t=e[1],n=e[2];return-1!==n&&move_exponents_outside_for.includes(t)?["^",["apply",t,normalize_applied_functions(r[1])],n]:["apply",e,normalize_applied_functions(r[1])]}let t=0;for(;"prime"===e[0];)t+=1,e=e[1];let n=["apply",e,normalize_applied_functions(r[1])];for(let e=0;e2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_integer_ast(e,s[0],n),is_integer_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_integer_ast(i[0],r,n);if("*"===a)return!!i.every((function(e){return is_integer_ast(e,r,n)}))||void 0;if("^"===a){let e=is_nonzero_ast(i[0],r,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!is_positive_ast(i[1],r,!0,n))return;if(!1===e)return!0}let t=is_integer_ast(i[0],r,n),a=is_integer_ast(i[1],r,n);if(!t)return t;if(!a)return;return!!is_positive_ast(i[1],r,!1,n)||void 0}if("+"===a){let e=0;for(let t=0;t0)return;e+=1}if(void 0===a)return}return 0===e}if("apply"===a)return!!(functions.C.Z&&functions.C.Z.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.Z&&functions.R.Z.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.Z&&functions.nonzeroC.Z.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.Z&&functions.nonneg.Z.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.Z&&functions.pos.Z.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("/"===a||"prime"===a)return;return!1}return!1}function is_real_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e,!1);if(null!==r)return"number"==typeof r&&Number.isFinite(r);if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}if("in"===i&&s[0]===e&&"R"===s[1])return negate_adjust(!0,o);if("notin"===i&&s[0]===e&&"R"===s[1])return negate_adjust(!1,o);if(!1===o){if("in"===i&&s[0]===e&&"Z"===s[1])return!0}else if("notin"===i&&s[0]===e&&"Z"===s[1])return!0;if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!o||"ne"===i&&o){let t=narrow_assumptions(a,n);if(s[0]===e)return is_real_ast(s[1],t);if(s[1]===e)return is_real_ast(s[0],t)}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_real_ast(e,s[0],n),is_real_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_real_ast(i[0],r,n);if("*"===a||"+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),"*"===a&&(!1===is_nonzero_ast(i[0],r,n)||!1===is_nonzero_ast(i[1],r,n)))return!0;let t=is_real_ast(i[0],r,n),s=is_real_ast(i[1],r,n);return!(!t||!s)||!(t&&!1===s||s&&!1===t)&&void 0}if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_real_ast(i[0],r,n),s=is_real_ast(i[1],r,n);if(!a||!s)return;return is_positive_ast(i[0],r,!1,n)?!!is_positive_ast(i[0],r,!0,n)||!!t||void 0:!!is_integer_ast(i[1],r,n)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_real_ast(i[0],r,n)||!is_real_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.R&&functions.C.R.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.R&&functions.R.R.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.R&&functions.nonzeroC.R.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.R&&functions.nonneg.R.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.R&&functions.pos.R.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_complex_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e,!1);if(null!==r)return"number"==typeof r?Number.isFinite(r):!(void 0===r.re||!Number.isFinite(r.re)||void 0===r.im||!Number.isFinite(r.im));if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}if("in"===i&&s[0]===e&&"C"===s[1])return negate_adjust(!0,o);if("notin"===i&&s[0]===e&&"C"===s[1])return negate_adjust(!1,o);if(!1===o){if("in"===i){if(s[0]===e&&"Z"===s[1])return!0;if(s[0]===e&&"R"===s[1])return!0}}else if("notin"===i){if(s[0]===e&&"Z"===s[1])return!0;if(s[0]===e&&"R"===s[1])return!0}if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!o||"ne"===i&&o){let t=narrow_assumptions(a,n);if(s[0]===e)return is_complex_ast(s[1],t);if(s[1]===e)return is_complex_ast(s[0],t)}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_complex_ast(e,s[0],n),is_complex_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_complex_ast(i[0],r,n);if("*"===a||"+"===a)return"*"===a&&!i.every((e=>!1!==is_nonzero_ast(e,r,n)))||(!!i.every((e=>is_complex_ast(e,r,n)))||void 0);if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_complex_ast(i[0],r,n),s=is_complex_ast(i[1],r,n);return!(!a||!s)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_complex_ast(i[0],r,n)||!is_complex_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.C&&functions.C.C.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.C&&functions.R.C.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.C&&functions.nonzeroC.C.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.C&&functions.nonneg.C.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.C&&functions.pos.C.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_nonzero_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e){if(Number.isFinite(e))return 0!==e;if(Number.isNaN(e))return;return!0}var r=evaluate_to_constant(e,!1);if(null!==r){if("number"==typeof r){if(Number.isFinite(r))return 0!==r;if(Number.isNaN(r))return;return!0}return void 0!==r.re&&void 0!==r.im&&(0!==r.re||0!==r.im)||void 0}if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}let l=narrow_assumptions(a,n);if("="===i&&!o||"ne"===i&&o){if(s[0]===e)return is_nonzero_ast(s[1],l);if(s[1]===e)return is_nonzero_ast(s[0],l)}if("ne"===i&&!o||"="===i&&o){if(s[0]===e&&!1===is_nonzero_ast(s[1],l))return!0;if(s[1]===e&&!1===is_nonzero_ast(s[0],l))return!0}if("<"===i)if(o){if(s[0]===e&&is_positive_ast(s[1],l,!0))return!0;if(s[1]===e&&is_negative_ast(s[0],l,!0))return!0}else{if(s[0]===e&&is_negative_ast(s[1],l,!1))return!0;if(s[1]===e&&is_positive_ast(s[0],l,!1))return!0}if("le"===i)if(o){if(s[0]===e&&is_positive_ast(s[1],l,!1))return!0;if(s[1]===e&&is_negative_ast(s[0],l,!1))return!0}else{if(s[0]===e&&is_negative_ast(s[1],l,!0))return!0;if(s[1]===e&&is_positive_ast(s[0],l,!0))return!0}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_nonzero_ast(e,s[0],n),is_nonzero_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_nonzero_ast(i[0],r,n);if("+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),equal(i[0],simplify(["-",i[1]],n)))return!1;let t=is_nonzero_ast(i[0],r,n),a=is_nonzero_ast(i[1],r,n);if(!1===t)return a;if(!1===a)return t;let s=is_real_ast(i[0],r,n),o=is_real_ast(i[1],r,n);if(!s||!o)return!0===s?!1===o||void 0:!0===o&&!1===s||void 0;let l=is_positive_ast(i[0],r,!1,n),u=is_positive_ast(i[1],r,!1,n),c=is_positive_ast(i[0],r,!0,n),p=is_positive_ast(i[1],r,!0,n);return!!(l&&p||c&&u)||!1===l&&!1===p||!1===c&&!1===u||void 0}if("*"===a){let e=!0;for(let t=0;t0:e>=0);var a=is_real_ast(e,t,r);if(!a)return a;var i=evaluate_to_constant(e,!1);if(null!==i)return"number"==typeof i&&!!Number.isFinite(i)&&(n?i>0:i>=0);if("string"==typeof e){let a;if(a=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(a))return;let i=a,s=a[0],o=a.slice(1),l=!1;for(;"not"===s;){if(l=!l,a=o[0],!Array.isArray(a))return;s=a[0],o=a.slice(1)}let u=narrow_assumptions(i,r);if("="===s&&!l||"ne"===s&&l){if(o[0]===e)return is_positive_ast(o[1],u,n);if(o[1]===e)return is_positive_ast(o[0],u,n)}if("<"===s)if(l){if(o[0]===e&&is_positive_ast(o[1],u,n))return!0;if(o[1]===e&&is_negative_ast(o[0],u,!n))return!1}else{if(o[0]===e&&is_negative_ast(o[1],u,!1))return!1;if(o[1]===e&&is_positive_ast(o[0],u,!1))return!0}if("le"===s)if(l){if(o[0]===e&&is_positive_ast(o[1],u,!1))return!0;if(o[1]===e&&is_negative_ast(o[0],u,!1))return!1}else{if(o[0]===e&&is_negative_ast(o[1],u,!n))return!1;if(o[1]===e&&is_positive_ast(o[0],u,n))return!0}if("and"!==s&&"or"!==s)return;if(l)return;return o.length>2&&(a=unflattenRight(a),o=a.slice(1)),simple_assumption_combination(s,is_positive_ast(e,o[0],n,r),is_positive_ast(e,o[1],n,r))}if(Array.isArray(e)){let a;a=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let i=e[0],s=e.slice(1);if("-"===i)return is_negative_ast(s[0],a,n,r);if("+"===i){s.length>2&&(s=(e=unflattenRight(e)).slice(1));let t=is_positive_ast(s[0],a,!1,r),i=is_positive_ast(s[1],a,!1,r),o=is_positive_ast(s[0],a,!0,r),l=is_positive_ast(s[1],a,!0,r);if(n){if(t&&l||o&&i)return!0}else if(t&&i)return!0;if(n){if(!1===o&&!1===l)return!1}else if(!1===t&&!1===l||!1===o&&!1===i)return!1;return}if("*"===i){if(!s.every((e=>!1!==is_nonzero_ast(e,a,r))))return!n;s.length>2&&(s=(e=unflattenRight(e)).slice(1));let t=is_real_ast(s[0],a,r),i=is_real_ast(s[1],a,r);if(void 0===t||void 0===i)return;if(!1===t)return!1===i&&void 0;if(!1===i)return!1;let o=is_positive_ast(s[0],a,!1,r),l=is_positive_ast(s[1],a,!1,r),u=is_positive_ast(s[0],a,!0,r),c=is_positive_ast(s[1],a,!0,r);if(n){if(u&&c||!1===o&&!1===l)return!0;if(!1===u&&l||o&&!1===c)return!1}else{if(o&&l||!1===u&&!1===c)return!0;if(u&&!1===l||!1===o&&c)return!1}return}if("/"===i){if(!is_nonzero_ast(s[1],a,r))return;if(!1===is_nonzero_ast(s[0],a,r))return!n;let e=is_positive_ast(s[1],a,!0,r);if(void 0===e)return;let t=e?n:!n,i=is_positive_ast(s[0],a,t,r);if(void 0===i)return;return!0===i?!0===e:!0!==e}if("^"===i){let e=is_nonzero_ast(s[0],a,r);if(e){if(!1===is_nonzero_ast(s[1],a,r)){if(s[0]===1/0||s[0]===-1/0)return;return!0}}else{if(!is_positive_ast(s[1],a,!0,r))return;if(!1===e)return!n;if(n)return}if(!0!==is_real_ast(s[0],a,r))return;return is_positive_ast(s[0],a,n,r)?!!is_real_ast(s[1],a,r)||void 0:!!is_integer_ast(simplify(["/",s[1],2],r),a,r)||void 0}if("apply"===i&&!n)return!!(functions.C.nonneg&&functions.C.nonneg.includes(s[0])&&is_complex_ast(s[1],a,r))||!!(functions.R.nonneg&&functions.R.nonneg.includes(s[0])&&is_real_ast(s[1],a,r))||!!(functions.nonzeroC.nonneg&&functions.nonzeroC.nonneg.includes(s[0])&&is_nonzero_ast(s[1],a,r)&&is_complex_ast(s[1],a,r))||!!(functions.nonneg.nonneg&&functions.nonneg.nonneg.includes(s[0])&&is_positive_ast(s[1],a,!1,r))||!!(functions.pos.nonneg&&functions.pos.nonneg.includes(s[0])&&is_positive_ast(s[1],a,!0,r))||void 0;if("apply"===i&&n)return!!(functions.C.pos&&functions.C.pos.includes(s[0])&&is_complex_ast(s[1],a,r))||!!(functions.R.pos&&functions.R.pos.includes(s[0])&&is_real_ast(s[1],a,r))||!!(functions.nonzeroC.pos&&functions.nonzeroC.pos.includes(s[0])&&is_nonzero_ast(s[1],a,r)&&is_complex_ast(s[1],a,r))||!!(functions.nonneg.pos&&functions.nonneg.pos.includes(s[0])&&is_positive_ast(s[1],a,!1,r))||!!(functions.pos.pos&&functions.pos.pos.includes(s[0])&&is_positive_ast(s[1],a,!0,r))||void 0;if("prime"===i)return;return!1}return!1}function is_negative_ast(e,t,n,r){void 0===n&&(n=!0);var a=is_real_ast(e,t,r);if(!0===a){let a=is_positive_ast(e,t,!n,r);return!1===a||!0!==a&&void 0}return a}function tuples_to_vectors(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n)return["vector"].concat(r.map((function(e,t){return tuples_to_vectors(e)})));if("apply"===n){if("tuple"===r[1][0]){let e=tuples_to_vectors(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return tuples_to_vectors(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return tuples_to_vectors(e)}))),t]}return[n].concat(r.map((function(e,t){return tuples_to_vectors(e)})))}function to_intervals(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!1,!1]],e}if("array"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!0,!0]],e}if("apply"===n){if("tuple"===r[1][0]){let e=to_intervals(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return to_intervals(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return to_intervals(e)}))),t]}return[n].concat(r.map((function(e,t){return to_intervals(e)})))}function altvectors_to_vectors(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);return"altvector"===n?["vector"].concat(r.map((function(e,t){return altvectors_to_vectors(e)}))):[n].concat(r.map((function(e,t){return altvectors_to_vectors(e)})))}function ParseError(e,t){this.name="ParseError",this.message=e||"Error parsing input",this.stack=(new Error).stack,this.location=t}functions.C.nonneg=["abs"],functions.C.nonzero=["exp"],functions.C.R=["abs","arg"],functions.C.C=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf","sqrt","log","ln","log10"],functions.R.pos=["exp"],functions.R.nonneg=["abs","exp","arg"],functions.R.R=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf"],functions.R.Z=["sign"],functions.nonzeroC.pos=["abs"],functions.nonneg.nonneg=["abs","exp","arg","sqrt","erf"],functions.nonzeroC.nonzero=["abs"],functions.nonneg.R=[...new Set(functions.R.R.concat(functions.nonneg.nonneg))],functions.pos.pos=["abs","exp","sqrt","erf"],functions.pos.nonneg=functions.pos.pos,functions.pos.nonzero=["abs","exp","sqrt","erf"],functions.pos.R=functions.nonneg.R.concat(["log","ln","log10"]),ParseError.prototype=Object.create(Error.prototype),ParseError.prototype.constructor=ParseError;class lexer{constructor(e,t="\\s"){this.input="",this.location=0,this.token_rules=[],this.initial_whitespace=new RegExp("^("+t+")+");for(let t of e)this.token_rules.push([new RegExp("^"+t[0])].concat(t.slice(1)))}set_input(e){if("string"!=typeof e)throw new Error("Input must be a string");this.input=e,this.location=0}return_state(){return{input:this.input,location:this.location}}set_state({input:e=null,location:t=0}={}){null!==e&&(this.input=e,this.location=t)}advance({remove_initial_space:e=!0}={}){let t=this.initial_whitespace.exec(this.input);if(t){let n=t[0].length;if(this.input=this.input.slice(n),this.location+=n,!e)return{token_type:"SPACE",token_text:t[0],original_text:t[0]}}if(0===this.input.length)return{token_type:"EOF",token_text:"",original_text:""};for(var n of(t=null,this.token_rules))if(t=n[0].exec(this.input),t){let e=t[0].length;this.input=this.input.slice(e),this.location+=e;break}return null===t?{token_type:"INVALID",token_text:this.input[0],original_text:this.input[0]}:n.length>2?{token_type:n[1],token_text:n[2],original_text:t[0]}:{token_type:n[1],token_text:t[0],original_text:t[0]}}unput(e){if("string"!=typeof e)throw new Error("Input must be a string");this.location-=e.length,this.input=e+this.input}}var is_associative={"+":!0,"*":!0,and:!0,or:!0,union:!0,intersect:!0};function flatten(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if(n=n.map((function(e,t){return flatten(e)})),is_associative[t]){for(var r=[],a=0;a2?r=r.concat(n[a].slice(1)):r.push(n[a]);n=r}return[t].concat(n)}const sci_notat_exp_regex$1="(E[+\\-]?[0-9]+\\s*($|(?=\\,|\\||\\)|\\}|\\])))?",number_rules_sci$1=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex$1,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex$1,"NUMBER"]],number_rules_non_sci$1=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_text_rules=[["\\*\\*","^"],["\\*","*"],["\\xB7","*"],["·","*"],["•","*"],["⋅","*"],["×","*"],["/","/"],["-","-"],["֊","-"],["־","-"],["᠆","-"],["‐","-"],["‑","-"],["‒","-"],["–","-"],["—","-"],["―","-"],["⁻","-"],["₋","-"],["−","-"],["⸺","-"],["⸻","-"],["﹘","-"],["﹣","-"],["-","-"],["\\+","+"],["\\^","^"],["‸","^"],["ʌ","^"],["\\|","|"],["\\(","("],["\\)",")"],["\\[","["],["\\]","]"],["\\{","{"],["\\}","}"],["⟨","LANGLE"],["⟩","RANGLE"],["〈","LANGLE"],["〉","RANGLE"],[",",","],[":",":"],["α","VARMULTICHAR","alpha"],["β","VARMULTICHAR","beta"],["ϐ","VARMULTICHAR","beta"],["Γ","VARMULTICHAR","Gamma"],["γ","VARMULTICHAR","gamma"],["Δ","VARMULTICHAR","Delta"],["δ","VARMULTICHAR","delta"],["ε","VARMULTICHAR","epsilon"],["ϵ","VARMULTICHAR","epsilon"],["ζ","VARMULTICHAR","zeta"],["η","VARMULTICHAR","eta"],["Θ","VARMULTICHAR","Theta"],["ϴ","VARMULTICHAR","Theta"],["θ","VARMULTICHAR","theta"],["ᶿ","VARMULTICHAR","theta"],["ϑ","VARMULTICHAR","theta"],["ι","VARMULTICHAR","iota"],["κ","VARMULTICHAR","kappa"],["Λ","VARMULTICHAR","Lambda"],["λ","VARMULTICHAR","lambda"],["μ","VARMULTICHAR","mu"],["µ","VARMULTICHAR","mu"],["ν","VARMULTICHAR","nu"],["Ξ","VARMULTICHAR","Xi"],["ξ","VARMULTICHAR","xi"],["Π","VARMULTICHAR","Pi"],["π","VARMULTICHAR","pi"],["ϖ","VARMULTICHAR","pi"],["ρ","VARMULTICHAR","rho"],["ϱ","VARMULTICHAR","rho"],["Σ","VARMULTICHAR","Sigma"],["σ","VARMULTICHAR","sigma"],["ς","VARMULTICHAR","sigma"],["τ","VARMULTICHAR","tau"],["Υ","VARMULTICHAR","Upsilon"],["υ","VARMULTICHAR","upsilon"],["Φ","VARMULTICHAR","Phi"],["φ","VARMULTICHAR","phi"],["ϕ","VARMULTICHAR","phi"],["Ψ","VARMULTICHAR","Psi"],["ψ","VARMULTICHAR","psi"],["Ω","VARMULTICHAR","Omega"],["ω","VARMULTICHAR","omega"],["oo(?![a-zA-Z0-9])","INFINITY"],["OO(?![a-zA-Z0-9])","INFINITY"],["infty(?![a-zA-Z0-9])","INFINITY"],["infinity(?![a-zA-Z0-9])","INFINITY"],["Infinity(?![a-zA-Z0-9])","INFINITY"],["∞","INFINITY"],["ℯ","VAR","e"],["♠","VARMULTICHAR","spade"],["♡","VARMULTICHAR","heart"],["♢","VARMULTICHAR","diamond"],["♣","VARMULTICHAR","club"],["★","VARMULTICHAR","bigstar"],["◯","VARMULTICHAR","bigcirc"],["◊","VARMULTICHAR","lozenge"],["△","VARMULTICHAR","bigtriangleup"],["▽","VARMULTICHAR","bigtriangledown"],["⧫","VARMULTICHAR","blacklozenge"],["■","VARMULTICHAR","blacksquare"],["▲","VARMULTICHAR","blacktriangle"],["▼","VARMULTICHAR","blacktriangledown"],["◀","VARMULTICHAR","blacktriangleleft"],["▶","VARMULTICHAR","blacktriangleright"],["□","VARMULTICHAR","Box"],["∘","VARMULTICHAR","circ"],["⋆","VARMULTICHAR","star"],["and(?![a-zA-Z0-9])","AND"],["\\&\\&?","AND"],["∧","AND"],["or(?![a-zA-Z0-9])","OR"],["∨","OR"],["not(?![a-zA-Z0-9])","NOT"],["¬","NOT"],["=","="],["᐀","="],["゠","="],["!=","NE"],["≠","NE"],["<=","LE"],["≤","LE"],[">=","GE"],["≥","GE"],["<","<"],[">",">"],["forall(?![a-zA-Z0-9])","FORALL"],["∀","FORALL"],["exists(?![a-zA-Z0-9])","EXISTS"],["∃","EXISTS"],["elementof(?![a-zA-Z0-9])","IN"],["∈","IN"],["notelementof(?![a-zA-Z0-9])","NOTIN"],["∉","NOTIN"],["containselement(?![a-zA-Z0-9])","NI"],["∋","NI"],["notcontainselement(?![a-zA-Z0-9])","NOTNI"],["∌","NOTNI"],["subset(?![a-zA-Z0-9])","SUBSET"],["⊂","SUBSET"],["subseteq(?![a-zA-Z0-9])","SUBSETEQ"],["⊆","SUBSETEQ"],["notsubset(?![a-zA-Z0-9])","NOTSUBSET"],["⊄","NOTSUBSET"],["notsubseteq(?![a-zA-Z0-9])","NOTSUBSETEQ"],["⊈","NOTSUBSETEQ"],["superset(?![a-zA-Z0-9])","SUPERSET"],["⊃","SUPERSET"],["superseteq(?![a-zA-Z0-9])","SUPERSETEQ"],["⊇","SUPERSETEQ"],["notsuperset(?![a-zA-Z0-9])","NOTSUPERSET"],["⊅","NOTSUPERSET"],["notsuperseteq(?![a-zA-Z0-9])","NOTSUPERSETEQ"],["⊉","NOTSUPERSETEQ"],["union(?![a-zA-Z0-9])","UNION"],["∪","UNION"],["intersect(?![a-zA-Z0-9])","INTERSECT"],["∩","INTERSECT"],["perp(?![a-zA-Z0-9])","PERP"],["⟂","PERP"],["parallel(?![a-zA-Z0-9])","PARALLEL"],["∥","PARALLEL"],["angle(?![a-zA-Z0-9])","ANGLE"],["∠","ANGLE"],["int(?![a-zA-Z0-9])","INT"],["∫","INT"],["!","!"],["'","'"],["_","_"],["\\.\\.\\.","LDOTS"],["[a-zA-Z∂][a-zA-Z∂0-9]*","VAR"],["[_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault$1=!0,splitSymbolsDefault=!0,unsplitSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","angle","deg"],appliedFunctionSymbolsDefault$1=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","re","im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault$1=["f","g"],operatorSymbolsDefault$1=["binom","vec","linesegment"],unitsDefault$1=get_all_units(),parseLeibnizNotationDefault$1=!0;class textToAst$4{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault$1,splitSymbols:t=splitSymbolsDefault,unsplitSymbols:n=unsplitSymbolsDefault,appliedFunctionSymbols:r=appliedFunctionSymbolsDefault$1,functionSymbols:a=functionSymbolsDefault$1,operatorSymbols:i=operatorSymbolsDefault$1,units:s=unitsDefault$1,parseLeibnizNotation:o=parseLeibnizNotationDefault$1,parseScientificNotation:l=!0}={}){this.allowSimplifiedFunctionApplication=e,this.splitSymbols=t,this.unsplitSymbols=n,this.appliedFunctionSymbols=r,this.functionSymbols=a,this.operatorSymbols=i,this.units=s,this.parseLeibnizNotation=o;let u=base_text_rules;u=l?[...number_rules_sci$1,...u]:[...number_rules_non_sci$1,...u],this.lexer=new lexer(u)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});return":"!==this.token.token_type?n:(this.advance(),[":",n,this.statement_a()])}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type)throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];if("FORALL"===this.token.token_type||"EXISTS"===this.token.token_type){let t=this.token.token_type.toLowerCase();return this.advance(),[t,this.relation(e)]}for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let t=n.length;for(let[e,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&e0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===e?["unit",n[0],s]:["unit",["*",...n.slice(0,e)],s],e===t-1?i:this.convert_units_in_term(["*",i,...n.slice(e+1)])}}}return e}return"/"===t?["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])]:e}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_subsuperscript({parse_absolute_value:e}){if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("NUMBER"===this.token.token_type)a=parseFloat(this.token.token_text),this.advance();else if("INFINITY"===this.token.token_type)a=1/0,this.advance();else if("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type){if(a=this.token.token_text,this.appliedFunctionSymbols.includes(a)||this.functionSymbols.includes(a)){let e=!1;if(this.appliedFunctionSymbols.includes(a)&&(e=!0),this.advance(),"_"===this.token.token_type){this.advance();let e=this.get_subsuperscript({parse_absolute_value:t});a="log"===a&&10===e?"log10":["_",a,e]}if(r)e&&(a=["apply",a,"_"]);else{for(;"'"===this.token.token_type;)a=["prime",a],this.advance();for(;"^"===this.token.token_type;)this.advance(),a=["^",a,this.get_subsuperscript({parse_absolute_value:t})];if("("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),"list"===e[0]&&(e[0]="tuple"),a=["apply",a,e]}else if(e){if(!this.allowSimplifiedFunctionApplication)throw new ParseError("Expecting ( after function",this.lexer.location);let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),a=["apply",a,e]}}return a}if(this.operatorSymbols.includes(a))if(this.advance(),"("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),a="list"===e[0]?[a,...e.slice(1)]:[a,e]}else{let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),a=[a,e]}else{if(this.parseLeibnizNotation){let e=this.return_state(),t=this.leibniz_notation();if(t)return t;this.set_state(e)}let r=this.splitSymbols;if(r&&("VARMULTICHAR"===this.token.token_type||this.unsplitSymbols.includes(a)||1===a.length||a.match(/[\d]/g))&&(r=!1),r){for(let e=a.length-1;e>=0;e--)this.lexer.unput(" "),this.lexer.unput(a[e]);return this.advance(),this.baseFactor({inside_absolute_value:e,parse_absolute_value:t,allow_absolute_value_closing:n})}this.advance()}}else if("("===this.token.token_type||"["===this.token.token_type||"{"===this.token.token_type||"LANGLE"===this.token.token_type){let e,t,n=this.token.token_type;"("===this.token.token_type?(e=")",t="]"):"["===this.token.token_type?(e="]",t=")"):"{"===this.token.token_type?(e="}",t=null):(e="RANGLE",t=null),this.advance();let r=1;if("list"===(a=this.statement_list())[0]&&(r=a.length-1),this.token.token_type!==e){if(2!==r||null===t)throw new ParseError("Expecting "+e,this.lexer.location);if(this.token.token_type!==t)throw new ParseError("Expecting ) or ]",this.lexer.location);let i;a[0]="tuple",i="("===n?["tuple",!1,!0]:["tuple",!0,!1],(a=["interval",a]).push(i)}else r>=2?a[0]="("===n?"tuple":"["===n?"array":"{"===n?"set":"altvector":"{"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type||!t||0!==e&&n){if("ANGLE"===this.token.token_type)if(this.advance(),"("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),"list"===e[0]?a=["angle",...e.slice(1)]:"*"===e[0]&&(a=["angle",e])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;t2&&(this.lexer.unput(this.token.token_text.slice(2)),this.token.token_text=this.token.token_text.slice(0,2));let o=this.token.token_text;if(2===o.length){if(!/[a-zA-Z]/.exec(o[1]))return!1;a.push(o[1])}else{if(this.advance(),("VAR"!==this.token.token_type||this.token.token_text.includes("∂"))&&"VARMULTICHAR"!==this.token.token_type)return!1;a.push(this.token.token_text)}let l=1,u=!1;if(this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance()),"^"===this.token.token_type){if(this.advance(),"NUMBER"!==this.token.token_type)return!1;if(l=parseFloat(this.token.token_text),!Number.isInteger(l))return!1;u=!1,this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance())}if(i.push(l),s+=l,s>n)return!1;if(s===n){if(!u&&("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type))return!1;"SPACE"===this.token.token_type&&this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;et[e+1]));if(t.length!==r||a.length!==r)return subtree;let i=["+",...t.map(((e,t)=>["*",e,a[t]]))];n.push(i)}o.push(n)}return{success:!0,newMatrix:["matrix",["tuple",n,a],o]}}function i(e,t){let n=e[1][1],r=e[1][2],a=e[2],i=["tuple"];for(let e=0;e=0;t--){let r=n[t][0];if("matrix"===r){let r=a(n[t],e);if(!r.success)break;e=r.newMatrix,n.pop()}else{if(["tuple","list","vector","altvector","interval","set","array"].includes(r))break;1!==n[t]&&(e=i(e,n[t])),n.pop()}}for(;r.length>0;){let t=r[0][0];if("matrix"===t){let t=a(e,r[0]);if(!t.success)break;e=t.newMatrix,r.splice(0,1)}else{if(["tuple","list","vector","altvector","interval","set","array"].includes(t))break;1!==r[0]&&(e=i(e,r[0])),r.splice(0,1)}}return n.length>0||r.length>0?["*",...n,e,...r]:e}return e})),(t||n)&&(s=["*",["matrix",["tuple","m","n"],"matrixData"],"b"],o={variables:{n:Number.isInteger,m:Number.isInteger,matrixData:!0,b:!0}},r=transform(r,(function(e){let r=match$2(e,s,o);if(r){let a,i=r.m,s=r.n,o=r.b,l=r.matrixData,u=[];t&&(u.push("vector"),u.push("altvector")),n&&u.push("tuple");let c=[];if(u.includes(o[0]))a=o;else{if(!Array.isArray(o)||"*"!==o[0]||!u.includes(o[1][0]))return e;a=o[1],c=o.slice(2)}let p=a.slice(1);if(p.length!==s)return e;let d=[a[0]];for(let e=0;e["*",e,p[t]]))];d.push(t)}return c.length>0?["*",d,...c]:d}return e}))),r}function perform_vector_scalar_multiplications(e,t=!0){var n=get_tree(e);let r=function(e,t){let n=["*","a",[t,"vectorData"],"b"],r={allow_implicit_identities:["a","b"]};return e=transform(e,(function(e){let a=match$2(e,n,r);if(a){if(1===a.a&&1===a.b)return e;let n=a.vectorData;n=Array.isArray(n)&&n[0]===t?n.slice(1):[n];let r=[],i=[];Array.isArray(a.a)&&"*"===a.a[0]?r.push(...a.a.slice(1)):r.push(a.a),Array.isArray(a.b)&&"*"===a.b[0]?i.push(...a.b.slice(1)):i.push(a.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>["*",t,r[e]]))),r.pop()}for(;i.length>0;){let e=i[0][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e))break;1!==i[0]&&(n=n.map((e=>["*",e,i[0]]))),i.splice(0,1)}let s=[t,...n];return r.length>0||i.length>0?["*",...r,s,...i]:s}return e})),e};return n=r(n,"vector"),n=r(n,"altvector"),t&&(n=r(n,"tuple")),n}function perform_matrix_scalar_multiplications(e){var t=get_tree(e);let n=["*","a",["matrix","size","matrixData"],"b"],r={allow_implicit_identities:["a","b"]};return t=transform(t,(function(e){let t=match$2(e,n,r);if(t){if(1===t.a&&1===t.b)return e;let n=t.matrixData,r=[],a=[];Array.isArray(t.a)&&"*"===t.a[0]?r.push(...t.a.slice(1)):r.push(t.a),Array.isArray(t.b)&&"*"===t.b[0]?a.push(...t.b.slice(1)):a.push(t.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>"tuple"===t?t:t.map((t=>"tuple"===t?t:["*",t,r[e]]))))),r.pop()}for(;a.length>0;){let e=a[0][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e))break;1!==a[0]&&(n=n.map((e=>"tuple"===e?e:e.map((e=>"tuple"===e?e:["*",e,a[0]]))))),a.splice(0,1)}let i=["matrix",t.size,n];return r.length>0||a.length>0?["*",...r,i,...a]:i}return e})),t}function expand_relations(e){var t=get_tree(e);return transform(t,expand_relations_transform)}function expand_relations_transform(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if("="===t){if(n.length<=2)return e;let t=["and"];for(let e=0;e":"lts"===t?"le":"ge",a.push([i,e[n],e[n+1]])}let i=["and",a[0],a[1]];for(let e=2;e",r,u]),o[2]?i?p.push([">",r,c]):p.push(["le",r,c]):i?p.push(["ge",r,c]):p.push(["<",r,c]),l=i?["or"].concat(p):["and"].concat(p),l}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let r,a,i=!1;if("notsubset"!==t&&"notsuperset"!==t||(i=!0),"subset"===t||"notsubset"===t?(r=n[0],a=n[1]):(r=n[1],a=n[0]),r=to_intervals(r),a=to_intervals(a),"interval"!==r[0]||"interval"!==a[0])return e;let s=r[1],o=r[2],l=a[1],u=a[2];if("tuple"!==s[0]||"tuple"!==o[0]||"tuple"!==l[0]||"tuple"!==u[0])throw new Error("Badly formed ast");let c,p=s[1],d=s[2],m=l[1],h=l[2],f=[];return o[1]&&!u[1]?i?f.push(["le",p,m]):f.push([">",p,m]):i?f.push(["<",p,m]):f.push(["ge",p,m]),o[2]&&!u[2]?i?f.push(["ge",d,h]):f.push(["<",d,h]):i?f.push([">",d,h]):f.push(["le",d,h]),c=i?["or"].concat(f):["and"].concat(f),c}return e}function substitute(e,t){var n=get_tree(e),r={};for(let e in t)r[e]=get_tree(t[e]);return substitute$1(n,r)}function substitute_component(e,t,n){let r=get_tree(e);if(get_tree(n),"number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid substitute_component: "+t);let a=["list","tuple","vector","altvector","array"];return function e(t,r,i){if(0===r.length)return n;if(!Array.isArray(t))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let s=t[0],o=t.slice(1);if(!a.includes(s))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let l=r[0];if(l<0||l>o.length-1)throw Error("Invalid substitute_component: component out of range");let u=r.slice(1),c=e(o[l],u);return[s,...o.slice(0,l),c,...o.slice(l+1)]}(r,t)}function get_component(e,t){let n=get_tree(e);if("number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid get_component: "+t);let r=["list","tuple","vector","altvector","array"];return function e(t,n){if(0===n.length)return t;if(!Array.isArray(t))throw Error("Invalid get_component: expected list, tuple, vector, or array");let a=t[0],i=t.slice(1);if(!r.includes(a))throw Error("Invalid get_component: expected list, tuple, vector, or array");let s=n[0];if(s<0||s>i.length-1)throw Error("Invalid get_component: component out of range");let o=n.slice(1);return e(i[s],o)}(n,t)}var transformation=Object.freeze({__proto__:null,expand:expand,expand_relations:expand_relations,substitute:substitute,substitute_component:substitute_component,get_component:get_component,perform_vector_scalar_multiplications:perform_vector_scalar_multiplications,perform_matrix_scalar_multiplications:perform_matrix_scalar_multiplications,perform_matrix_multiplications:perform_matrix_multiplications});function clean(e){return flatten$5(get_tree(e))}function evalf(e,t){return parseFloat(math$1.format(e,{notation:"exponential",precision:t}))}function collapse_unary_minus(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if(r=r.map((e=>collapse_unary_minus(e))),"-"===n){if("number"==typeof r[0])return-r[0];if(Array.isArray(r[0])&&"*"===r[0][0]&&"number"==typeof r[0][1])return["*",-r[0][1]].concat(r[0].slice(2));if(Array.isArray(r[0])&&"/"===r[0][0]){if("number"==typeof r[0][1])return["/",-r[0][1],r[0][2]];if(Array.isArray(r[0][1])&&"*"===r[0][1][0]&&"number"==typeof r[0][1][1])return["/",["*",-r[0][1][1]].concat(r[0][1].slice(2)),r[0][2]]}}return[n].concat(r)}function simplify(e,t,n){var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r=evaluate_numbers(r,{assumptions:t,max_digits:n,evaluate_functions:!0}),Array.isArray(r)?r=collect_like_terms_factors(r=perform_vector_matrix_additions_scalar_multiplications(r=simplify_logical(r,t)),t,n):r)}function simplify_logical(e,t){var n=get_tree(e);if(contains_blank(n))return n;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),n=evaluate_numbers(n,{assumptions:t}),n=unflattenRight(n);var r=[];return r.push([["not",["not","a"]],"a"]),r.push([["not",["and","a","b"]],["or",["not","a"],["not","b"]]]),r.push([["not",["or","a","b"]],["and",["not","a"],["not","b"]]]),r.push([["not",["=","a","b"]],["ne","a","b"]]),r.push([["not",["ne","a","b"]],["=","a","b"]]),r.push([["not",["<","a","b"]],["le","b","a"]]),r.push([["not",["le","a","b"]],["not",["le","a","b"]]]),r.push([["not",["in","a","b"]],["notin","a","b"]]),r.push([["not",["subset","a","b"]],["notsubset","a","b"]]),flatten$5(n=applyAllTransformations(n,r,20))}function perform_vector_matrix_additions_scalar_multiplications(e,t=!0){var n=get_tree(e);n=perform_vector_scalar_multiplications(n=perform_matrix_scalar_multiplications(n),t);let r=["+","a","b"];return n=transform(n,(function(e){let n=match$2(e,r,{allow_permutations:!0});if(n){let r=["vector","altvector"];t&&r.push("tuple");let a={},i={},s=[];if(r.includes(n.a[0])){let e=n.a.length-1;a[e]||(a[e]=[]),a[e].push(n.a)}else if("matrix"===n.a[0]){let e=n.a[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.a)}else s.push(n.a);if(r.includes(n.b[0])){let e=n.b.length-1;a[e]||(a[e]=[]),a[e].push(n.b)}else if("matrix"===n.b[0]){let e=n.b[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.b)}else if("+"===n.b[0])for(let e of n.b.slice(1))if(r.includes(e[0])){let t=e.length-1;a[t]||(a[t]=[]),a[t].push(e)}else if("matrix"===e[0]){let t=e[1].slice(1).toString();i[t]||(i[t]=[]),i[t].push(e)}else s.push(e);else s.push(n.b);if(Object.values(a).every((e=>e.length<2))&&Object.values(i).every((e=>e.length<2)))return e;let o=s;for(let e in a)if(a[e].length<2)o.push(...a[e]);else{let t,n=a[e].some((e=>"vector"===e[0])),r=a[e].some((e=>"tuple"===e[0])),i=a[e].some((e=>"altvector"===e[0]));t=n||r&&i?["vector"]:i?["altvector"]:["tuple"];for(let n=0;ne[n+1]))]);o.push(t)}for(let e in i)if(i[e].length<2)o.push(...i[e]);else{let[t,n]=e.split(",").map(Number),r=["tuple"];for(let a=0;ae[2][a+1][r+1]))]);r.push(t)}let a=["matrix",["tuple",t,n],r];o.push(a)}return 1===o.length?o[0]:["+",...o]}return e})),n}function contains_decimal_number(e){return"string"!=typeof e&&("number"==typeof e?!(!Number.isFinite(e)||Number.isInteger(e)):!!Array.isArray(e)&&e.slice(1).some((e=>contains_decimal_number(e))))}function contains_only_numbers(e,{include_number_symbols:t=!1,evaluate_functions:n=!1}={}){if("string"==typeof e){if(t){if("e"===e&&math$1.define_e)return!0;if("pi"===e&&math$1.define_pi)return!0}return!("i"!==e||!math$1.define_i)}return"number"==typeof e||!!Array.isArray(e)&&(n&&"apply"===e[0]?e.slice(2).every((e=>contains_only_numbers(e,{include_number_symbols:t}))):e.slice(1).every((e=>contains_only_numbers(e,{include_number_symbols:t}))))}function try_evaluate_sum_of_numbers(e,t,n){if("number"==typeof e){if(0===e)return t;if("number"==typeof t)return e+t;if(Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[1])return["+",e+t[1],t[2]];if(!n&&Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[2])return["+",e+t[2],t[1]]}return"number"==typeof t&&0===t?e:null}function try_evaluate_negate_number(e){if("number"==typeof e)return-e;if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1])return["*",-e[1]].concat(e.slice(2));if(Array.isArray(e)&&"/"===e[0]){if("number"==typeof e[1])return["/",-e[1],e[2]];if(Array.isArray(e[1])&&"*"===e[1][0]&&"number"==typeof e[1][1])return["/",["*",-e[1][1]].concat(e[1].slice(2)),e[2]]}return null}function try_evaluate_product_of_numbers(e,t){if("number"==typeof e){if(isNaN(e))return NaN;if("number"==typeof t)return e*t;if(!isFinite(e))return e===1/0&&is_negative_ast(t)||e===-1/0&&is_positive_ast(t)?-1/0:!1===is_nonzero_ast(t)?NaN:1/0;if(0===e)return 0;if(1===e)return t;if(-1===e)return["-",t];if(Array.isArray(t)&&"*"===t[0]&&"number"==typeof t[1])return e*=t[1],t=t[2],1===e?t:-1===e?["-",t]:["*",e,t]}if("number"==typeof t){if(isNaN(t))return NaN;if(!isFinite(t))return t===1/0&&is_negative_ast(e)||t===-1/0&&is_positive_ast(e)?-1/0:!1===is_nonzero_ast(e)?NaN:1/0;if(0===t)return 0;if(1===t)return e;if(-1===t)return["-",e];if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1])return t*=e[1],e=e[2],1===t?e:-1===t?["-",e]:["*",e,t]}if(math$1.define_i&&"i"===e){if("i"===t)return-1;if(Array.isArray(t)&&"*"===t[0]&&"i"===t[1])return["-",t[2]]}else if(math$1.define_i&&"i"===t&&Array.isArray(e)&&"*"===e[0]&&"i"===e[1])return["-",e[2]];return null}function try_evaluate_quotient_of_numbers(e,t,n,r){if("number"==typeof e){if(0===e){let e=is_nonzero_ast(t,n);if(e)return 0;if(!1===e)return NaN}if("number"==typeof t){let n=e/t;if(r===1/0||math$1.round(n,r)===n)return n;if(t<0)return["/",-e,-t]}if(Array.isArray(t)&&"*"===t[0]&&"number"==typeof t[1]){let n=e/t[1];if(r===1/0||math$1.round(n,r)===n)return["/",n,t[2]]}}else if("number"==typeof t){if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1]){let n=e[1]/t;if(r===1/0||math$1.round(n,r)===n)return 1===n?e[2]:["*",n,e[2]];if(t<0)return["/",["*",-e[1],e[2]],-t]}let n=1/t;if(r===1/0||math$1.round(n,r)===n)return["*",n,e];if(t<0)return Array.isArray(e)&&"-"===e[0]?["/",e[1],-t]:["-",["/",e,-t]]}return null}function evaluate_numbers_sub(e,t,n,r,a,i){if(void 0===e)return e;if("number"==typeof e)return i>0&&math$1.abs(e)0&&math$1.abs(t)evaluate_numbers_sub(e,t,n,r,a,i)));if("+"===o){let e=l[0],t=l[1];if(void 0===t)return e;let n=try_evaluate_sum_of_numbers(e,t,r);if(null!==n)return n;if("unit"===e[0]&&"unit"===t[0]){let n=get_unit_of_tree(e),a=get_unit_of_tree(t);if(n&&n===a){let a=try_evaluate_sum_of_numbers(remove_units(e,!1),remove_units(t,!1),r);if(null!==a)return add_unit(a,n)}}return[o].concat(l)}if("-"===o){let e=try_evaluate_negate_number(l[0]);if(null!==e)return e;if("unit"===l[0][0]){let e=get_unit_of_tree(l[0]);if(e){let t=try_evaluate_negate_number(remove_units(l[0],!1));if(null!==t)return add_unit(t,e)}}return[o].concat(l)}if("*"===o){let e=l[0],t=l[1];if(void 0===t)return e;let n=try_evaluate_product_of_numbers(e,t);if(null!==n)return n;if("unit"===e[0]&&"unit"!==t[0]){let n=get_unit_of_tree(e);if(n){let r=try_evaluate_product_of_numbers(remove_units(e,!1),t);if(null!==r)return add_unit(r,n)}}if("unit"!==e[0]&&"unit"===t[0]){let n=get_unit_of_tree(t);if(n){let r=try_evaluate_product_of_numbers(e,remove_units(t,!1));if(null!==r)return add_unit(r,n)}}return[o].concat(l)}if("/"===o){let e=l[0],r=l[1],a=try_evaluate_quotient_of_numbers(e,r,t,n);if(null!==a)return a;if("unit"===e[0]&&"unit"!==r[0]){let a=get_unit_of_tree(e);if(a){let i=try_evaluate_quotient_of_numbers(remove_units(e,!1),r,t,n);if(null!==i)return add_unit(i,a)}}return[o].concat(l)}if("^"===o){let e=l[0],r=l[1];if("number"==typeof r)if(0===r){if(!math$1.pow_strict)return 1;let n=is_nonzero_ast(e,t);if(n&&e!==1/0&&e!==-1/0)return 1;if(!1===n)return NaN}else{if(1===r)return e;if("number"==typeof e){let t=math$1.pow(e,r);if(n===1/0||math$1.round(t,n)===t)return t}}else if(1===e)return 1;return[o].concat(l)}return[o].concat(l)}function evaluate_numbers(e,{assumptions:t,max_digits:n,skip_ordering:r=!1,evaluate_functions:a=!1,set_small_zero:i=0}={}){(void 0===n||!Number.isInteger(n)&&n!==1/0)&&(n=0),!0===i&&(i=1e-14);var s,o=get_tree(e);return contains_blank(o)?o:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r?s=evaluate_numbers_sub(o=unflattenRight(flatten$5(o)),t,n,r,a,i):(o=move_units_outside_products(o),o=unflattenRight(default_order(flatten$5(o))),s=default_order(evaluate_numbers_sub(o,t,n,r,a,i)),s=default_order(evaluate_numbers_sub(unflattenRight(s),t,n,r,a,i))),flatten$5(s=set_negative_zeros_to_zero(s)))}function set_negative_zeros_to_zero(e){return 0===e?0:Array.isArray(e)?[e[0],...e.slice(1).map(set_negative_zeros_to_zero)]:e}function collect_like_terms_factors(e,t,n){function r(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function a(e){return"number"==typeof e&&e<0||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function i(e){if("number"==typeof e)return!0;if(Array.isArray(e)&&"-"===e[0]&&"number"==typeof e[1])return!0;let t=evaluate_to_constant(e,!1);return!("number"!=typeof t||!Number.isFinite(t))}var s=get_tree(e);if(contains_blank(s))return s;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),s=evaluate_numbers(s,{assumptions:t,max_digits:n,evaluate_functions:!0});var o=[];o.push([["/","x",["^","y","a"]],["*","x",["^","y",["-","a"]]],{evaluate_numbers:!0,max_digits:n}]),o.push([["/","x",["apply","exp","a"]],["*","x",["apply","exp",["-","a"]]],{evaluate_numbers:!0,max_digits:n,variables:{x:!0,a:!0}}]),o.push([["/","x","y"],["*","x",["^","y",["-",1]]],{evaluate_numbers:!0,max_digits:n}]),s=applyAllTransformations(s,o,40),o=[];for(let e in all_units)all_units[e].prefix?(o.push([["+",["unit",e,"x"],["unit",e,"y"]],["unit",e,["+","x","y"]],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["unit",e,"x"],["-",["unit",e,"y"]]],["unit",e,["+","x",["-","y"]]],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}])):(o.push([["+",["unit","x",e],["unit","y",e]],["unit",["+","x","y"],e],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["unit","x",e],["-",["unit","y",e]]],["unit",["+","x",["-","y"]],e],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]));return o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:e=>is_nonzero_ast(e,t),n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_positive_ast(e,t),m:e=>r(e)&&is_positive_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_negative_ast(e,t),m:e=>r(e)&&is_negative_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["apply","exp","n"],["apply","exp","m"]],["apply","exp",["+","n","m"]],{variables:{n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n","x"],["*","m","x"]],["*",["+","n","m"],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n1","x"],["*",["/","n2","m2"],"x"]],["*",["+","n1",["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n1","x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+","n1",["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*",["/","n1","m1"],"x"],["*",["/","n2","m2"],"x"]],["*",["+",["/","n1","m1"],["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*",["/","n1","m1"],"x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+",["/","n1","m1"],["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n","x"],["-",["*","m","x"]]],["*",["+","n",["-","m"]],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["^",["*","x","y"],"a"],["*",["^","x","a"],["^","y","a"]],{allow_permutations:!0}]),o.push([["^",["^","x","n"],"m"],["^","x",["*","n","m"]],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_permutations:!0}]),o.push([["-",["+","a","b"]],["+",["-","a"],["-","b"]]]),o.push([["*","x","y"],["*","x","y"],{variables:{x:i,y:i},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s=applyAllTransformations(s,o,40),(o=[]).push([["*","x",["^","y",["-","a"]]],["/","x",["^","y","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1}]),o.push([["*","x",["apply","exp",["-","a"]]],["/","x",["apply","exp","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1,variables:{x:!0,a:!0}}]),o.push([["*","x",["^","y","n"]],["/","x",["^","y",["-","n"]]],{variables:{x:!0,y:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*","x",["apply","exp","n"]],["/","x",["apply","exp",["-","n"]]],{variables:{x:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s=applyAllTransformations(s,o,40),(o=[]).push([["^","y","n"],["/",1,["^","y",["-","n"]]],{variables:{y:!0,n:a},evaluate_numbers:!0,max_digits:n}]),o.push([["apply","exp","n"],["/",1,["apply","exp",["-","n"]]],{variables:{n:a},evaluate_numbers:!0,max_digits:n}]),s=applyAllTransformations(s,o,40),(o=[]).push([["*","x",["/","y","z"]],["/",["*","x","y"],"z"],{allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["/",["/","x","y"],"z"],["/","x",["*","y","z"]],{allow_extended_match:!0,allow_permutations:!0}]),o.push([["/","x",["/","y","z"]],["/",["*","x","z"],"y"],{allow_extended_match:!0,allow_permutations:!0}]),evaluate_numbers(s=applyAllTransformations(s,o,40),{assumptions:t,max_digits:n})}function simplify_ratios(e,t){function n(e){var t=1;return e=e.map((function(e){if("number"==typeof e)return e<0?(t*=-1,-e):e;if(!Array.isArray(e))return e;if("-"===e[0])return t*=-1,e[1];if("+"!==e[0])return e;var n=!1;if(("number"==typeof e[1]&&e[1]<0||Array.isArray(e[1])&&"-"===e[1][0]||Array.isArray(e[1])&&"*"===e[1][0]&&Number(e[1][1])<0)&&(n=!0),n){t*=-1;var r=e.slice(1).map((e=>["-",e]));return evaluate_numbers(["+"].concat(r))}return e})),{factors:e,sign_change:t}}var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),function e(t,r){if(!Array.isArray(t))return r?["-",t]:t;var a=t[0];if("-"===a)return e(t[1],r=!0);var i=t.slice(1).map((t=>e(t)));if("/"!==a)return r?["-",[a,...i]]:[a,...i];var s,o=i[0],l=i[1];o=default_order(o,{ignore_negatives:!0});var u,c=n(s=Array.isArray(o)&&"*"===o[0]?o.slice(1):[o]);s=c.factors,r&&(c.sign_change*=-1),l=default_order(l,{ignore_negatives:!0});var p=n(Array.isArray(l)&&"*"===l[0]?l.slice(1):[l]);return u=p.factors,c.sign_change*p.sign_change<0&&(s[0]=["-",s[0]]),["/",o=1===s.length?s[0]:["*"].concat(s),l=1===u.length?u[0]:["*"].concat(u)]}(r))}function contains_blank(e){return"_"===e||!!Array.isArray(e)&&e.some(contains_blank)}let all_units=get_all_units();function remove_units(e,t=!0){var n=get_tree(e);if(!Array.isArray(n))return n;let r=n[0],a=n.slice(1);if("unit"===r){let e=all_units[get_unit_of_tree(n)];if(!e)return n;let r=remove_units(e.prefix?a[1]:a[0],t);return t?e.scale(r):r}return[r,...a.map((e=>remove_units(e,t)))]}function remove_scaling_units(e){var t=get_tree(e);if(!Array.isArray(t))return t;let n=t[0],r=t.slice(1);if("unit"===n){let e=all_units[get_unit_of_tree(t)];if(!e||!e.only_scales)return t;let n=remove_scaling_units(e.prefix?r[1]:r[0]);return e.scale(n)}return[n,...r.map((e=>remove_scaling_units(e)))]}function add_unit(e,t){var n=get_tree(e);let r=all_units[t];return r?r.prefix?["unit",t,n]:["unit",n,t]:n}function move_units_outside_products(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=[],t=[];for(let r of n){let n=get_unit_value_of_tree(r);n?(e.push(n[0]),t.push(n[1])):t.push(r)}let r=["*",...t];for(let t of e)r=add_unit(r,t);return r}return[t,...n.map(move_units_outside_products)]}var simplify$1=Object.freeze({__proto__:null,clean:clean,simplify:simplify,simplify_logical:simplify_logical,evaluate_numbers:evaluate_numbers,collect_like_terms_factors:collect_like_terms_factors,collapse_unary_minus:collapse_unary_minus,simplify_ratios:simplify_ratios,default_order:default_order,perform_vector_matrix_additions_scalar_multiplications:perform_vector_matrix_additions_scalar_multiplications,remove_units:remove_units,add_unit:add_unit,remove_scaling_units:remove_scaling_units});function solve_linear(e,t,n){if("string"==typeof t){void 0===n&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(n=e.context.get_assumptions([e.variables()]));var r=simplify(get_tree(e),n);if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("="===a||"ne"===a||"<"===a||"le"===a||">"===a||"ge"===a){var s=simplify(["+",i[0],["-",i[1]]],n),o=e=>!variables(e).includes(t);if(variables(s=simplify(applyAllTransformations(s,[[["+",["*","_a",t],["*","_b",t]],["*",["+","_a","_b"],t],{variables:{_a:o,_b:o},allow_permutations:!0,allow_extended_match:!0,allow_implicit_identities:["_a","_b"],evaluate_numbers:!0}]],20))).includes(t)){var l=match$2(s,["+",["*","_a",t],"_b"],{variables:{_a:o,_b:o},allow_permutations:!0,allow_implicit_identities:["_a","_b"]});if(l){var u=simplify(l._a),c=simplify(l._b);if(is_nonzero_ast(u,n)){if("="===a||"ne"===a||is_positive_ast(u,n)){let e=simplify(["/",["-",c],u]);return[a,t,e]}if(is_negative_ast(u,n)){var p=simplify(["/",["-",c],u]);return[a="<"===a?">":"le"===a?"ge":">"===a?"<":"le",t,p]}}}}}}}}var solve=Object.freeze({__proto__:null,solve_linear:solve_linear});function clean_assumptions(e,t){if(!Array.isArray(e)||0===e.length)return e;var n=(e=flatten$5(default_order(simplify_logical(expand_relations(e)))))[0],r=e.slice(1);if("and"===n||"or"===n){if(r=r.reduce((function(e,t){return e.every((function(e){return!equal(e,t)}))&&e.push(t),e}),[]),"and"===n&&t&&Array.isArray(t)){let e;e="and"===t[0]?t.slice(1):[t],r=r.filter((t=>e.every((e=>!equal(e,t)))))}e=1===r.length?r[0]:[n].concat(r)}if("and"!==n&&t&&Array.isArray(t)){let n;if(n="and"===t[0]?t.slice(1):[t],!n.every((t=>!equal(t,e))))return}return e}function calculate_derived_assumptions(e,t){if(void 0===t){t=[];for(let n in e.byvar){let r=e.byvar[n];r.length>0&&t.push(r)}if(0===t.length)return{};t=clean_assumptions(t=1===t.length?t[0]:["and"].concat(t))}if(!Array.isArray(t)||0===t.length)return{};var n=t[0],r=t.slice(1);if("and"===n||"or"===n){let t=r.map((function(t){return calculate_derived_assumptions(e,t)})),a=[...new Set(t.reduce(((e,t)=>[...e,...Object.keys(t)]),[]))],i={};for(let r of a){let a=t.reduce((function(e,t){return void 0!==t[r]&&e.push(t[r]),e}),[]);if("and"===n||a.length===t.length){let t=i[r];t=void 0===t?a.length>1?[n].concat(a):a[0]:a.length>1?["and",t,[n].concat(a)]:["and",t,a[0]],i[r]=clean_assumptions(t,get_assumptions(e,r,{omit_derived:!0}))}}return i}let a={};if("="===n||"ne"===n||"<"===n||"le"===n||"in"===n||"subset"===n||"notin"===n||"notsubset"===n){var i=!1;for(let t=0;t<2;t++){let o=r[t],l=r[1-t],u=variables(l);if("string"!=typeof o||0===u.length||u.includes(o))continue;i=!0;var s=n;1===t&&("<"===n?s=">":"le"===n?s="ge":"in"===n?s="ni":"subset"===n?s="superset":"notin"===n?s="notni":"notsubset"===n&&(s="notsuperset"));let c=get_assumptions_for_expr(e,l,[o]);if(c=combine_assumptions(o,s,l,c),void 0!==c){let t=a[o];t=void 0===t?c:["and",t,c],a[o]=clean_assumptions(t,get_assumptions(e,o,{omit_derived:!0}))}}if(i)return a}let o=[];for(let t of r){let n=get_assumptions_for_expr(e,t,[]);void 0!==n&&o.push(n)}if(0===o.length)return{};o=1===o.length?o[0]:["and"].concat(o);for(let n of variables(t))a[n]=clean_assumptions(o,get_assumptions(e,n,{omit_derived:!0}));return a}function get_assumptions_for_expr(e,t,n){let r=variables(t);if(r=r.filter((e=>!n.includes(e))),0===r.length)return;function a(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}var i=["_b"],s=["_b"],o={_b:a},l={};for(let e=0;evoid 0!==e));if(0===e.length)return;return"or"===s?e.length===o.length?["or"].concat(e):void 0:1===e.length?e[0]:["and"].concat(e)}if(!(["=","ne","<","le"].includes(s)||["in","notin","subset","notsubset"].includes(s)&&c)){let r=n.concat(variables(t)),a=[];for(let t of variables(i)){if(r.includes(t))continue;let n=get_assumptions_for_expr(e,t,r);void 0!==n&&a.push(n)}return 0===a.length?i:1===a.length?["and",i,a[0]]:["and",i].concat(a)}let u=[];for(let a=0;a<=1;a++){let i=o[a],c=o[1-a];if("string"==typeof i&&r.includes(i)){var p={};p[i]=c;var d=simplify(substitute$1(t,p)),m=!1,h=s;(1===a&&l[i]>0||0===a&&l[i]<0)&&("<"===s?(m=!0,h=">"):"le"===s?(m=!0,h="ge"):"in"===s?(m=!0,h="ni"):"subset"===s?(m=!0,h="superset"):"notin"===s?(m=!0,h="notni"):"notsubset"===s&&(m=!0,h="notsuperset")),m?u.push([s,d,t]):u.push([s,t,d]);let r=n.concat([i]),o=get_assumptions_for_expr(e,d,r);o=combine_assumptions(t,h,d,o),void 0!==o&&u.push(o)}}if(1===u.length)return u[0];if(u.length>1)return["and"].concat(u);let f=n.concat(variables(t));u=[];for(let t of variables(i)){if(f.includes(t))continue;let n=get_assumptions_for_expr(e,t,f);void 0!==n&&u.push(n)}return 0===u.length?i:1===u.length?["and",i,u[0]]:["and",i].concat(u)}(p)):void 0}function combine_assumptions(e,t,n,r){if(!["=","ne","<","le",">","ge","in","notin","ni","notni","subset","notsubset","superset","notsuperset"].includes(t))return r;if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("and"===a||"or"===a){let r=i.map((r=>combine_assumptions(e,t,n,r))).filter((e=>void 0!==e));if(0===r.length)return;return"or"===a?r.length===i.length?[["or"].concat(r)]:void 0:1===r.length?r[0]:["and"].concat(r)}if(!["=","ne","<","le","in","notin","subset","notsubset"].includes(a))return r;var s,o,l=a;if(equal(i[0],n))s=i[1];else{if(!equal(i[1],n))return r;s=i[0],"<"===a?l=">":"le"===a?l="ge":"in"===a?l="ni":"notin"===a?l="notni":"subset"===a?l="superset":"notsubset"===a&&(l="notsuperset")}if("="===t)o=l;else if("="===l)o=t;else if("<"===t){if("<"!==l&&"le"!==l)return"in"===l||"notin"===l?r:void 0;o="<"}else if("le"===t)if("<"===l)o="<";else{if("le"!==l)return"in"===l||"notin"===l?r:void 0;o="le"}else if(">"===t){if(">"!==l&&"ge"!==l)return"in"===l||"notin"===l?r:void 0;o=">"}else if("ge"===t)if(">"===l)o=">";else{if("ge"!==l)return"in"===l||"notin"===l?r:void 0;o="ge"}else if("in"===t){if("subset"!==l)return;o="in"}else if("notin"===t){if("superset"!==l)return;o="notin"}else if("ni"===t){if("notin"!==l)return;o="notsubset"}else if("notni"===t){if("in"!==l)return;o="notsuperset"}else if("subset"===t)if("subset"===l)o="subset";else if("notni"===l)o="notni";else{if("notsuperset"!==l)return;o="notsuperset"}else if("notsubset"===t){if("superset"!==l)return;o="notsubset"}else if("superset"===t)if("superset"===l)o="superset";else if("ni"===l)o="ni";else{if("notsubset"!==l)return;o="notsubset"}else{if("notsuperset"!==t)return;if("subset"!==l)return;o="notsuperset"}return">"===o?["<",s,e]:"ge"===o?["le",s,e]:"ni"===o?["in",s,e]:"notni"===o?["notin",s,e]:"superset"===o?["subset",s,e]:"notsuperset"===o?["notsubset",s,e]:[o,e,s]}}function filter_assumptions_from_tree(e,t){if(Array.isArray(e)&&0!==e.length){Array.isArray(t)||(t=[t]);var n=e[0],r=e.slice(1);if("and"===n){var a=r.map((function(e){return filter_assumptions_from_tree(e,t)}));return 0===(a=a.filter((e=>void 0!==e))).length?void 0:1===a.length?a[0]:["and"].concat(a)}var i=variables(e);return t.filter((e=>i.includes(e))).length>0?void 0:e}}function get_assumptions_sub(e,t,n,r){Array.isArray(t)||(t=[t]);var a=[];return t.forEach((function(t){if(e.byvar[t]||e.derived[t]){if(e.byvar[t]&&e.byvar[t].length>0){var i=filter_assumptions_from_tree(e.byvar[t],n);void 0!==i&&a.push(i)}if(e.derived[t]&&e.derived[t].length>0&&!r){var s=filter_assumptions_from_tree(e.derived[t],n);void 0!==s&&a.push(s)}}else e.generic.length>0&&("x"!==t&&variables(e.generic).includes(t)||a.push(substitute$1(e.generic,{x:t})))})),1===a.length?a=a[0]:a.length>1&&(a=["and"].concat(a)),a.length>0?clean_assumptions(a):void 0}function get_assumptions(e,t,n){void 0===n&&(n={});var r,a=n.exclude_variables;void 0===a?a=[]:Array.isArray(a)||(a=[a]);var i=get_tree(t);if("string"==typeof i)r=[i];else{if(!Array.isArray(i))return;Array.isArray(i[0])&&(r=i[0])}return r?get_assumptions_sub(e,r,a,n.omit_derived):get_assumptions_for_expr(e,i,a)}function add_assumption(e,t,n){var r=get_tree(t);if(!Array.isArray(r))return 0;var a=add_assumption_sub(e,r=clean_assumptions(simplify(r,e)),n);return a&&(e.derived=calculate_derived_assumptions(e)),a}function add_assumption_sub(e,t,n){if("and"===t[0])return t.slice(1).map((t=>add_assumption_sub(e,t,n))).reduce((function(e,t){return e+t}));var r=variables(t);if(0===r.length)return 0;let a=0;!n&&e.generic.length>0&&r.forEach((function(t){void 0===e.byvar[t]&&("x"!==t&&variables(e.generic).includes(t)||(add_assumption_sub(e,substitute$1(e.generic,{x:t}),!0),a+=1))}));for(let n of r){let r=solve_linear(t,n,e),i=t;r&&(i=r);let s=e.byvar[n];void 0!==s&&0!==s.length&&(i=["and",s,i]),i=clean_assumptions(i),equal(i,s)||(e.byvar[n]=i,a+=1)}return a}function add_generic_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=add_generic_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function add_generic_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>add_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;let n=solve_linear(t,"x",e),r=t;n&&(r=n);let a=e.generic;return 0!==a.length&&(r=["and",a,r]),r=clean_assumptions(r),equal(r,a)?0:(e.generic=r,1)}function remove_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=remove_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function remove_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>remove_assumption_sub(e,t))).reduce((function(e,t){return e+t}));var n=variables(t);if(0===n.length)return 0;var r=0;for(let a of n){let n=solve_linear(t,a,e),i=e.byvar[a];if(!i||0===i.length)continue;let s,o=i[0],l=i.slice(1),u=l.length;if("and"===o)if(l=l.filter((e=>!(equal(e,t)||equal(e,n)))),0===l.length)s=[];else if(1===l.length)s=l[0];else{if(!(l.lengthremove_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;var n=e.generic;if(0===n.length)return 0;let r=solve_linear(t,"x",e);var a,i=n[0],s=n.slice(1),o=s.length;if("and"===i)if(0===(s=s.filter((e=>!(equal(e,t)||equal(e,r))))).length)a=[];else if(1===s.length)a=s[0];else{if(!(s.length0)if(e.includes(".")){if("0"!==e[0]?n++:n+=e.match(/^0\.0*/)[0].length,e.length0)if(e.includes(".")){let t=e.match(/\.\d*$/)[0].length-1;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" \\le ")},ge:function(e){return e.join(" \\ge ")},ne:function(e){return e.join(" \\ne ")},forall:function(e){return"\\forall "+e[0]},exists:function(e){return"\\exists "+e[0]},in:function(e){return e[0]+" \\in "+e[1]},notin:function(e){return e[0]+" \\notin "+e[1]},ni:function(e){return e[0]+" \\ni "+e[1]},notni:function(e){return e[0]+" \\not\\ni "+e[1]},subset:function(e){return e[0]+" \\subset "+e[1]},subseteq:function(e){return e[0]+" \\subseteq "+e[1]},notsubset:function(e){return e[0]+" \\not\\subset "+e[1]},notsubseteq:function(e){return e[0]+" \\not\\subseteq "+e[1]},superset:function(e){return e[0]+" \\supset "+e[1]},superseteq:function(e){return e[0]+" \\supseteq "+e[1]},notsuperset:function(e){return e[0]+" \\not\\supset "+e[1]},notsuperseteq:function(e){return e[0]+" \\not\\supseteq "+e[1]},union:function(e){return e.join(" \\cup ")},intersect:function(e){return e.join(" \\cap ")},perp:function(e){return e.join(" \\perp ")},parallel:function(e){return e.join(" \\parallel ")},derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},partial_derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},"|":function(e){return e[0]+" \\mid "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"\\binom{"+e[0]+"}{"+e[1]+"}"},vec:function(e){return"\\vec{"+e[0]+"}"},linesegment:function(e){return"\\overline{"+e.join(" ")+"}"},angle:function(e,t){return t?"\\angle "+e.join(""):"\\angle\\left( "+e.join(", ")+" \\right)"},unit:function(e){return"\\circ"===e[1]?e[0]+"^{\\circ}":e[0]+" "+e[1]}},allowedLatexSymbolsDefault$1=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","arg","Re","Im","det","angle","perp","circ","%","$","int"],convertLatexSymbolsDefault={acos:"arccos",acosh:"arccosh",acot:"arccot",acoth:"arccoth",acsc:"arccsc",acsch:"arccsch",asec:"arcsec",asech:"arcsech",asin:"arcsin",asinh:"arcsinh",atan:"arctan",atanh:"arctanh",deg:"circ"},matrixEnvironmentDefault="bmatrix";class astToLatex$1{constructor({allowedLatexSymbols:e=allowedLatexSymbolsDefault$1,convertLatexSymbols:t=convertLatexSymbolsDefault,matrixEnvironment:n=matrixEnvironmentDefault,padToDigits:r=null,padToDecimals:a=null,showBlanks:i=!0}={}){this.allowedLatexSymbols=e,this.convertLatexSymbols=t,this.matrixEnvironment=n,this.padToDigits=r,this.padToDecimals=a,this.showBlanks=i}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);var t=e[0],n=e.slice(1);if("ldots"===t)return"\\ldots";if(!(t in operators$1)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);var t=e[0],n=e.slice(1);if("not"===t)return operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this)));if("exists"===t||"forall"===t)return operators$1[t]([this.single_statement(n[0])]);if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"subseteq"===t||"notsubseteq"===t||"superset"===t||"notsuperset"===t||"superseteq"===t||"notsuperseteq"===t)return operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":a+="lts"===t?" \\le ":" \\ge ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t?1===n.length?"+"+this.term(n[0]):operators$1[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):["union","intersect","perp","parallel"].includes(t)?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"-"===t?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):"*"===t?operators$1[t](n.map(function(e,t){let r;return t>0?(r=this.factorWithParenthesesIfNegatedOrExplicitPlus(e),r.match(/^[0-9]/)?"\\cdot "+r:"angle"===e[0]&&n.length>1?"\\left( "+r+" \\right)":r):(r=this.factor(e),"angle"===e[0]&&n.length>1?"\\left( "+r+" \\right)":r)}.bind(this))):"/"===t||"unit"===t?operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this))):this.factor(e)}simple_factor_or_function_or_parens(e){var t=this.factor(e);return!!(t.length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]&&"sqrt"!==e[1]||t.match(/^\\left\(.*\\right\)$/)||t.match(/^\\left\\langle.*\\right\\rangle$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}stringConvert(e){return e.length>1?(this.convertLatexSymbols[e]&&(e=this.convertLatexSymbols[e]),this.allowedLatexSymbols.includes(e)?"\\"+e:"\\operatorname{"+e+"}"):this.allowedLatexSymbols.includes(e)?"\\"+e:"_"!==e||this.showBlanks?e:""}factor(e){if("string"==typeof e)return this.stringConvert(e);if("number"==typeof e){if(e===1/0)return"\\infty";if(e===-1/0)return"-\\infty";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if("+"===a[0]&&(a=a.slice(1)),null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return r+" \\cdot 10^{"+a+"}"}}if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1]))return n[0]<0?"\\left("+n[0].toString()+"\\right)^{"+n[1].toString()+"}":n[0].toString()+"^{"+n[1].toString()+"}";let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];return this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="\\left("+e.toString()+"\\right)"),e+"^{"+this.statement(n[1])+"}"}if("_"===t){let e=this.factor(n[0]);return this.simple_factor_or_function_or_parens(n[0])||(e="\\left("+e.toString()+"\\right)"),e+"_{"+this.statement(n[1])+"}"}if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="\\left("+r+"\\right)");for(let e=0;e1?o=o.trimRight()+"^{"+i+"}"+this.stringConvert(s):o+=this.stringConvert(s),o="\\frac{ "+o+" }{ ";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,o=o+e+this.stringConvert(i),r>1&&(o=o+"^{"+r+"}"),o+=" "}return o+="}",o}if("apply"===t){if("abs"===n[0])return"\\left|"+this.statement(n[1])+"\\right|";if("floor"===n[0])return"\\left\\lfloor "+this.statement(n[1])+" \\right\\rfloor";if("ceil"===n[0])return"\\left\\lceil "+this.statement(n[1])+" \\right\\rceil";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"\\left("+e+"\\right)!"}if("sqrt"===n[0])return"\\sqrt{"+this.statement(n[1])+"}";let e,t=n[0];if("^"===t[0]&&(t=t[1]),"_"===t[0]&&(t=t[1]),"int"===t){let e,t=this.factor(n[0]),r=n[1];if(Array.isArray(r)&&"*"===r[0]){let t=[],n=["*"];for(let e=1;e0&&(e[e.length-1].match(/[a-zA-Z]/)&&(e+="\\,"),e+=t.map((e=>"d"+this.factor(e[1]))).join("\\,"))}return e||(e=this.term(n[1])),t+" "+e}e="log10"===n[0]?"\\log_{10}":"re"===n[0]?"\\Re":"im"===n[0]?"\\Im":this.factor(n[0]);let r=this.statement(n[1]);return"tuple"!==n[1][0]&&(r="\\left("+r+"\\right)"),e+r}if("angle"===t){let e=n.every((e=>{if("string"==typeof e&&1===e.length)return!0;if(!Array.isArray(e))return!1;let t=e[0];return"_"===t||"^"===t||"prime"===t}));return operators$1[t](n.map(function(e,t){return this.statement(e)}.bind(this)),e)}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"\\left("+this.statement(e)+"\\right)"}factorWithParenthesesIfNegatedOrExplicitPlus(e){var t=this.factor(e);return t.match(/^-/)||t.match(/^\+/)?"\\left("+t+"\\right)":t}termWithPlusIfNotNegated(e){var t=this.term(e);return t.match(/^-/)?t.match(/^-[^ ]/)?"- "+t.slice(1):t:"+ "+t}}const textToAst$2=new textToAst$4,astToLatex=new astToLatex$1;var derivatives={sin:textToAst$2.convert("cos x"),cos:textToAst$2.convert("-(sin x)"),tan:textToAst$2.convert("(sec x)^2"),cot:textToAst$2.convert("-((csc x)^2)"),sec:textToAst$2.convert("(sec x)*(tan x)"),csc:textToAst$2.convert("-(csc x)*(cot x)"),sqrt:textToAst$2.convert("1/(2*sqrt(x))"),log:textToAst$2.convert("1/x"),ln:textToAst$2.convert("1/x"),exp:textToAst$2.convert("exp(x)"),arcsin:textToAst$2.convert("1/sqrt(1 - x^2)"),arccos:textToAst$2.convert("-1/sqrt(1 - x^2)"),arctan:textToAst$2.convert("1/(1 + x^2)"),arccsc:textToAst$2.convert("-1/(sqrt(-1/x^2 + 1)*x^2)"),arcsec:textToAst$2.convert("1/(sqrt(-1/x^2 + 1)*x^2)"),arccot:textToAst$2.convert("-1/(1 + x^2)"),abs:textToAst$2.convert("abs(x)/x")};function derivative(e,t,n=[]){var r=get_tree(e),a="\\frac{d}{d"+t+"} ";if("number"==typeof r)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if(variables(r).indexOf(t)<0)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if("string"==typeof r)return t===r?(n.push("We know the derivative of the identity function is one, that is, \\("+a+astToLatex.convert(r)+" = 1\\)."),1):(n.push("As far as \\("+astToLatex.convert(t)+"\\) is concerned, \\("+astToLatex.convert(r)+"\\) is constant, so "+a+astToLatex.convert(r)+" = 0\\)."),0);if(!Array.isArray(r))return null;var i=r[0],s=r.slice(1);if("+"===i||"-"===i||"~"===i){n.push("Using the sum rule, \\("+a+astToLatex.convert(r)+" = "+s.map((function(e,t){return a+astToLatex.convert(e)})).join(" + ")+"\\).");let e=[i].concat(s.map((function(e,r){return derivative(e,t,n)})));return e=simplify(e),n.push("So using the sum rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("*"===i){let e=[],i=[];for(let n=0;n0){if(0===e.length)return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = 0.\\)"),0;let s=["*"].concat(e);if(1===e.length&&(s=e[0]),s===t){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+"\\).");let e=["*"].concat(i);return e=simplify(e),e}n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+" \\cdot "+a+"\\left("+astToLatex.convert(s)+"\\right)\\).");let o=derivative(s,t,n),l=["*"].concat(i.concat([o]));return l=simplify(l),n.push("And so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the product rule, \\("+a+astToLatex.convert(r)+" = "+s.map((function(e,t){return s.map((function(n,r){return t===r?a+"\\left("+astToLatex.convert(e)+"\\right)":astToLatex.convert(n)})).join(" \\cdot ")})).join(" + ")+"\\).");let o=s.slice(),l=["+"].concat(s.map((function(e,r){return["*"].concat(o.map((function(e,a){if(r===a){let r=derivative(e,t,n);return 1===r?null:r}return e})).filter((function(e){return null!=e})))})));return l=simplify(l),n.push("So using the product rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("/"===i){let e=s[0],i=s[1];if(variables(i).indexOf(t)<0){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(["/",1,i])+" \\cdot "+a+"\\left("+astToLatex.convert(e)+"\\right)\\).");let s=derivative(e,t,n),o=textToAst$2.convert("(1/g)*d"),l=substitute$1(o,{d:s,g:i});return l=simplify(l),n.push("So \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if(variables(e).indexOf(t)<0){1!==e&&n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+" \\cdot "+a+"\\left("+astToLatex.convert(["/",1,i])+"\\right)\\)."),n.push("Since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\cdot \\frac{-1}{ "+astToLatex.convert(i)+"^2} \\cdot "+a+astToLatex.convert(i)+"\\).");let s=derivative(i,t,n),o=textToAst$2.convert("f * (-a/(g^2))"),l=substitute$1(o,{f:e,a:s,g:i});return l=simplify(l),n.push("So since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the quotient rule, \\("+a+astToLatex.convert(r)+" = \\frac{"+a+"\\left("+astToLatex.convert(e)+"\\right) \\cdot "+astToLatex.convert(i)+" - "+astToLatex.convert(e)+"\\cdot "+a+"\\left("+astToLatex.convert(i)+"\\right)}{ \\left( "+astToLatex.convert(i)+" \\right)^2} \\).");let o=derivative(e,t,n),l=derivative(i,t,n),u=textToAst$2.convert("(a * g - f * b)/(g^2)"),c=substitute$1(u,{a:o,b:l,f:e,g:i});return c=simplify(c),n.push("So using the quotient rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}if("^"===i){let e=s[0],i=s[1];if(variables(i).indexOf(t)<0){if("string"==typeof e&&"x"===e){if("number"==typeof i){let t=textToAst$2.convert("n * (f^m)"),s=substitute$1(t,{n:i,m:i-1,f:e});return s=simplify(s),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),s}let t=textToAst$2.convert("n * (f^(n-1))"),s=substitute$1(t,{n:i,f:e});return s=simplify(s),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),s}1!==i&&n.push("By the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"} \\cdot "+a+astToLatex.convert(e)+"\\).");let s=derivative(e,t,n);if(1===i)return s;if("number"==typeof i){let t=textToAst$2.convert("n * (f^m) * a"),o=substitute$1(t,{n:i,m:i-1,f:e,a:s});return o=simplify(o),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}let o=textToAst$2.convert("n * (f^(n-1)) * a"),l=substitute$1(o,{n:i,f:e,a:s});return l=simplify(l),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("e"===e&&math$1.define_e){if("string"==typeof i&&i===t){let e=textToAst$2.convert("e^(f)"),s=substitute$1(e,{f:i});return s=simplify(s),n.push("The derivative of \\(e^"+astToLatex.convert(t)+"\\) is itself, that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+"\\)."),s}n.push("Using the rule for \\(e^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let e=textToAst$2.convert("e^(f)*d"),s=derivative(i,t,n),o=substitute$1(e,{f:i,d:s});return o=simplify(o),n.push("So using the rule for \\(e^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}if("number"==typeof e){if("string"==typeof i&&i===t){let s=textToAst$2.convert("a^(f) * log(a)"),o=substitute$1(s,{a:e,f:i});return o=simplify(o),n.push("The derivative of \\(a^"+astToLatex.convert(t)+"\\) is \\(a^{"+astToLatex.convert(t)+"} \\, \\log a\\), that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}let s=textToAst$2.convert("a^(f) * log(a)"),o=substitute$1(s,{a:e,f:i});n.push("Using the rule for \\(a^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let l=textToAst$2.convert("a^(b)*log(a)*d"),u=derivative(i,t,n),c=substitute$1(l,{a:e,b:i,d:u});return c=simplify(c),n.push("So using the rule for \\(a^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}let o=e,l=i;n.push("Recall the general rule for exponents, namely that \\(\\frac{d}{dx} u(x)^{v(x)} = u(x)^{v(x)} \\cdot \\left( v'(x) \\cdot \\log u(x) + \\frac{v(x) \\cdot u'(x)}{u(x)} \\right)\\). In this case, \\(u(x) = "+astToLatex.convert(o)+"\\) and \\(v(x) = "+astToLatex.convert(l)+"\\).");let u=derivative(o,t,n),c=derivative(l,t,n),p=textToAst$2.convert("(f^g)*(b * log(f) + (g * a)/f)"),d=substitute$1(p,{a:u,b:c,f:o,g:l});return d=simplify(d),n.push("So by the general rule for exponents, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(d)+"\\)."),d}if("apply"===i&&!(s[0]in derivatives)){let e=s[1];n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(["apply",s[0]+"'","x"],{x:e}))+" \\cdot "+a+astToLatex.convert(e)+"\\).");let i=["*",substitute$1(["apply",s[0]+"'","x"],{x:e}),derivative(e,t,n)];return i=simplify(i),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+"\\)."),i}if("apply"===i&&s[0]in derivatives||i in derivatives){let e=!1;"apply"===i&&(i=s[0],s=s.slice(1),e=!0);let o=s[0];if("number"==typeof o){let e=0;return n.push("The derivative of a constant is zero so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof o&&o===t){let e=["*",substitute$1(derivatives[i],{x:o})];return e=simplify(e),n.push("It is the case that \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof o&&o!==t){let e=0;return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}{let s=[i,"u"];e&&(s=["apply"].concat(s)),n.push("Recall \\(\\frac{d}{du}"+astToLatex.convert(s)+" = "+astToLatex.convert(derivative(s,"u",[]))+"\\)."),n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(derivatives[i],{x:o}))+" \\cdot "+a+astToLatex.convert(o)+"\\).");let l=["*",substitute$1(derivatives[i],{x:o}),derivative(o,t,n)];return l=simplify(l),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}}return 0}function lowercaseFirstLetter(e){return e.charAt(0).toLowerCase()+e.slice(1)}function simplify_story(e){for(let t=e.length-1;t>=1;t--)e[t]===e[t-1]&&e.splice(t,1);for(let t=0;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" ≤ ")},ge:function(e){return e.join(" ≥ ")},ne:function(e){return e.join(" ≠ ")},forall:function(e){return"∀ "+e[0]},exists:function(e){return"∃ "+e[0]},in:function(e){return e[0]+" ∈ "+e[1]},notin:function(e){return e[0]+" ∉ "+e[1]},ni:function(e){return e[0]+" ∋ "+e[1]},notni:function(e){return e[0]+" ∌ "+e[1]},subset:function(e){return e[0]+" ⊂ "+e[1]},subseteq:function(e){return e[0]+" ⊆ "+e[1]},notsubset:function(e){return e[0]+" ⊄ "+e[1]},notsubseteq:function(e){return e[0]+" ⊈ "+e[1]},superset:function(e){return e[0]+" ⊃ "+e[1]},superseteq:function(e){return e[0]+" ⊇ "+e[1]},notsuperset:function(e){return e[0]+" ⊅ "+e[1]},notsuperseteq:function(e){return e[0]+" ⊉ "+e[1]},union:function(e){return e.join(" ∪ ")},intersect:function(e){return e.join(" ∩ ")},perp:function(e){return e.join(" ⟂ ")},parallel:function(e){return e.join(" ∥ ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"binom( "+e[0]+", "+e[1]+" )"},vec:function(e){return"vec("+e[0]+")"},linesegment:function(e){return"linesegment( "+e.join(", ")+" )"},angle:function(e,t){return t?"∠"+e.join(""):"∠( "+e.join(", ")+" )"},unit:function(e){return e[0]+" "+e[1]}},nonunicode_operators={"+":function(e){return e.join(" ")},"-":function(e){return"-"+e[0]},"*":function(e){return e.join(" ")},"/":function(e){return e[0]+"/"+e[1]},_:function(e){return e[0]+"_"+e[1]},"^":function(e){return e[0]+"^"+e[1]},prime:function(e){return e[0]+"'"},tuple:function(e){return"( "+e.join(", ")+" )"},array:function(e){return"[ "+e.join(", ")+" ]"},list:function(e){return e.join(", ")},set:function(e){return"{ "+e.join(", ")+" }"},vector:function(e){return"( "+e.join(", ")+" )"},altvector:function(e){return"( "+e.join(", ")+" )"},interval:function(e){return"( "+e.join(", ")+" )"},matrix:function(e){return"( "+e.join(", ")+" )"},and:function(e){return e.join(" and ")},or:function(e){return e.join(" or ")},not:function(e){return"not "+e[0]},"=":function(e){return e.join(" = ")},"<":function(e){return e.join(" < ")},">":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" <= ")},ge:function(e){return e.join(" >= ")},ne:function(e){return e.join(" ne ")},forall:function(e){return"forall "+e[0]},exists:function(e){return"exists "+e[0]},in:function(e){return e[0]+" elementof "+e[1]},notin:function(e){return e[0]+" notelementof "+e[1]},ni:function(e){return e[0]+" containselement "+e[1]},notni:function(e){return e[0]+" notcontainselement "+e[1]},subset:function(e){return e[0]+" subset "+e[1]},subseteq:function(e){return e[0]+" subseteq "+e[1]},notsubset:function(e){return e[0]+" notsubset "+e[1]},notsubseteq:function(e){return e[0]+" notsubseteq "+e[1]},superset:function(e){return e[0]+" superset "+e[1]},superseteq:function(e){return e[0]+" superseteq "+e[1]},notsuperset:function(e){return e[0]+" notsuperset "+e[1]},notsuperseteq:function(e){return e[0]+" notsuperseteq "+e[1]},union:function(e){return e.join(" union ")},intersect:function(e){return e.join(" intersect ")},perp:function(e){return e.join(" perp ")},parallel:function(e){return e.join(" parallel ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"binom( "+e[0]+", "+e[1]+" )"},vec:function(e){return"vec("+e[0]+")"},linesegment:function(e){return"linesegment( "+e.join(", ")+" )"},angle:function(e,t){return t?"angle "+e.join(""):"angle( "+e.join(", ")+" )"},unit:function(e){return e[0]+" "+e[1]}},output_unicodeDefault=!0;class astToText$2{constructor({output_unicode:e=output_unicodeDefault,padToDigits:t=null,padToDecimals:n=null,showBlanks:r=!0}={}){this.output_unicode=e,this.operators=unicode_operators,e||(this.operators=nonunicode_operators),this.padToDigits=t,this.padToDecimals=n,this.showBlanks=r}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);let t=e[0],n=e.slice(1);if("ldots"===t)return"...";if(!(t in this.operators)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\(.*\)$/)?"("+n+")":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);let t=e[0],n=e.slice(1);if("not"===t)return this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\(.*\)$/)?"("+n+")":n}.bind(this)));if("exists"===t||"forall"===t)return this.operators[t]([this.single_statement(n[0])]);if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"subseteq"===t||"notsubseteq"===t||"superset"===t||"notsuperset"===t||"superseteq"===t||"notsuperseteq"===t)return this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":"lts"===t?this.output_unicode?a+=" ≤ ":a+=" <= ":this.output_unicode?a+=" ≥ ":a+=" >= ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);let t=e[0],n=e.slice(1);return"+"===t?1===n.length?"+"+this.term(n[0]):this.operators[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):["union","intersect","perp","parallel"].includes(t)?this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);let t=e[0],n=e.slice(1);if("-"===t)return this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this)));if("*"===t)return this.operators[t](n.map(function(e,t){let r;return t>0?(r=this.factorWithParenthesesIfNegatedOrExplicitPlus(e),r.match(/^[0-9]/)?"* "+r:"angle"===e[0]&&n.length>1?"( "+r+" )":r):(r=this.factor(e),"angle"===e[0]&&n.length>1?"( "+r+" )":r)}.bind(this)));if("/"===t){let e=this.factor(n[0]),r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[0])||(e="("+e+")"),this.simple_factor_or_function_or_parens(n[1])||(r="("+r+")"),this.operators[t]([e,r])}return"unit"===t?this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this))):this.factor(e)}symbolConvert(e){let t={alpha:"α",beta:"β",Gamma:"Γ",gamma:"γ",Delta:"Δ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",Theta:"ϴ",theta:"θ",iota:"ι",kappa:"κ",Lambda:"Λ",lambda:"λ",mu:"μ",nu:"ν",Xi:"Ξ",xi:"ξ",Pi:"Π",pi:"π",rho:"ρ",Sigma:"Σ",sigma:"σ",tau:"τ",Upsilon:"Υ",upsilon:"υ",Phi:"Φ",phi:"ϕ",Psi:"Ψ",psi:"ψ",Omega:"Ω",omega:"ω",perp:"⟂",int:"∫"};return this.output_unicode&&e in t?t[e]:this.showBlanks||"_"!==e?e:""}simple_factor_or_function_or_parens(e){let t=this.factor(e);return!!(t.length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]||t.match(/^\(.*\)$/)||t.match(/^⟨.*⟩$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}factor(e){if("string"==typeof e)return this.symbolConvert(e);if("number"==typeof e){if(e===1/0)return this.output_unicode?"∞":"infinity";if(e===-1/0)return this.output_unicode?"-∞":"-infinity";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if(null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return"+"===a[0]?r+" * 10^"+a.substring(1):r+" * 10^("+a+")"}}if(!Array.isArray(e))return"";let t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1])){let e;return e=n[0]<0?"("+n[0].toString()+")":n[0].toString(),n[1]<0?e+"^("+n[1].toString()+")":e+"^"+n[1].toString()}let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="("+e.toString()+")");let r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||(r="("+r.toString()+")"),e+"^"+r}if("_"===t)return this.operators[t](n.map(function(e,t){let n=this.factor(e);return this.simple_factor_or_function_or_parens(e)?n:"("+n+")"}.bind(this)));if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="("+r+")");for(let e=0;e1&&(o=o+"^"+i),o=o+this.symbolConvert(s)+"/";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,o=o+e+this.symbolConvert(i),r>1&&(o=o+"^"+r)}return o}if("apply"===t){if("abs"===n[0])return"|"+this.statement(n[1])+"|";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"("+e+")!"}let e=n[0];if("^"===e[0]&&(e=e[1]),"_"===e[0]&&(e=e[1]),"int"===e){let e,t=this.factor(n[0]),r=n[1];if(Array.isArray(r)&&"*"===r[0]){let t=[],n=["*"];for(let e=1;e0&&(e+=" "+t.map((e=>"d"+this.factor(e[1]))).join(" "))}return e||(e=this.term(n[1])),t+" "+e}let t=this.factor(n[0]),r=this.statement(n[1]);return"tuple"!==n[1][0]&&(r="("+r+")"),t+r}if("angle"===t){let e=n.every((e=>{if("string"==typeof e&&1===e.length)return!0;if(!Array.isArray(e))return!1;let t=e[0];return"_"===t||"^"===t||"prime"===t}));return this.operators[t](n.map(function(e,t){return this.statement(e)}.bind(this)),e)}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"("+this.statement(e)+")"}factorWithParenthesesIfNegatedOrExplicitPlus(e){var t=this.factor(e);return t.match(/^-/)||t.match(/^\+/)?"("+t+")":t}termWithPlusIfNotNegated(e){let t=this.term(e);return t.match(/^-/)?t.match(/^-[^ ]/)?"- "+t.slice(1):t:"+ "+t}}var astToText$1=new astToText$2;function subscripts_to_strings(e,t=!1){var n=get_tree(e);if(!Array.isArray(n))return n;let r=n[0],a=n.slice(1);return"_"===r&&(t||a.every((e=>["number","string"].includes(typeof e))))?astToText$1.convert(n):[r].concat(a.map((e=>subscripts_to_strings(e,t))))}function strings_to_subscripts(e){var t=get_tree(e);if("string"==typeof t){let e=t.match(/^([0-9a-zA-Z]+)_([a-zA-Z]+|[0-9]+)$/);if(e){let t=Number(e[1]);isNaN(t)&&(t=e[1]);let n=Number(e[2]);return isNaN(n)&&(n=e[2]),["_",t,n]}return t}if(!Array.isArray(t))return t;let n=t[0],r=t.slice(1);return[n].concat(r.map(strings_to_subscripts))}var normalization=Object.freeze({__proto__:null,normalize_function_names:normalize_function_names,normalize_applied_functions:normalize_applied_functions,log_subscript_to_two_arg_log:log_subscript_to_two_arg_log,substitute_abs:substitute_abs,default_order:default_order,constants_to_floats:constants_to_floats,normalize_angle_linesegment_arg_order:normalize_angle_linesegment_arg_order,tuples_to_vectors:tuples_to_vectors,to_intervals:to_intervals,altvectors_to_vectors:altvectors_to_vectors,subscripts_to_strings:subscripts_to_strings,strings_to_subscripts:strings_to_subscripts}),astToText=new astToText$2;function generate_random_integer(e,t,n){return e=math$1.ceil(e),t=math$1.floor(t),math$1.floor(n()*(t-e+1))+e}const equals$5=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i=1e-12,absolute_tolerance:s=0,tolerance_for_zero:o=1e-15,allowed_error_in_numbers:l=0,include_error_in_number_exponents:u=!1,allowed_error_is_absolute:c=!1,rng:p}){if(Array.isArray(e.tree)&&Array.isArray(t.tree)){let d=e.tree[0],m=e.tree.slice(1),h=t.tree[0],f=t.tree.slice(1);if("tuple"===d||"vector"===d||"altvector"===d||"list"===d||"array"===d||"matrix"===d||"interval"===d){if(h!==d)return!1;if(f.length!==m.length)return!1;for(let e=0;e","<","ge","le"].includes(d)){if(2!==f.length)return!1;if(">"===d?(d="<",m=[m[1],m[0]]):"ge"===d&&(d="le",m=[m[1],m[0]]),">"===h?(h="<",f=[f[1],f[0]]):"ge"===h&&(h="le",f=[f[1],f[0]]),d!==h)return!1;let e=["+",m[0],["-",m[1]]],t=["+",f[0],["-",f[1]]],y="="!==d;return component_equals({expr:r.fromAst(e),other:a.fromAst(t),randomBindings:n,expr_context:r,other_context:a,allow_proportional:!0,require_positive_proportion:y,relative_tolerance:i,absolute_tolerance:s,tolerance_for_zero:o,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})}}return component_equals({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i,absolute_tolerance:s,tolerance_for_zero:o,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})},component_equals=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,allow_proportional:i=!1,require_positive_proportion:s=!1,relative_tolerance:o,absolute_tolerance:l,tolerance_for_zero:u,allowed_error_in_numbers:c,include_error_in_number_exponents:p,allowed_error_is_absolute:d,rng:m}){var h=1e-20*Number.MAX_VALUE;e=e.normalize_function_names(),t=t.normalize_function_names(),e=e.log_subscript_to_two_arg_log(),t=t.log_subscript_to_two_arg_log(),e=e.subscripts_to_strings(),t=t.subscripts_to_strings(),e=e.normalize_applied_functions(),t=t.normalize_applied_functions();let f=rename_functions_with_exponents(e.tree),y=rename_functions_with_exponents(t.tree);e=r.fromAst(rename_vecs(f)),t=a.fromAst(rename_vecs(y));var g=[...new Set([...e.variables(),...t.variables()])];math$1.define_pi&&(g=g.filter((function(e){return"pi"!==e}))),math$1.define_i&&(g=g.filter((function(e){return"i"!==e}))),math$1.define_e&&(g=g.filter((function(e){return"e"!==e})));var b=[];for(let e=0;e1===e.length||e.includes("_")||e.includes("^"))),N=v.filter((e=>g.includes(e)));if(v=v.filter((e=>!g.includes(e))),N.length>0){let n=e.tree,i=t.tree,s="x1";for(;[...v,...g].includes(s);)s+="x1";let o="x2";for(;[...v,...g].includes(o);)o+="x2";for(let e of N){let t=e+e;for(;[...v,...g].includes(t);)t+=e;let r=[[["apply",e,s],["apply",t,s],{variables:{[s]:!0}}]];n=applyAllTransformations(n,r),i=applyAllTransformations(i,r),v.push(t)}e=r.fromAst(n),t=a.fromAst(i)}try{var T=e.f(),C=t.f()}catch(n){return e.equalsViaSyntax(t,{allow_blanks:!0})}let A,V,x;if(c>0){let t=replace_numbers_with_parameters({expr:e,variables:g,include_exponents:p});A=r.fromAst(t.expr_with_params),V=t.parameters;let n=Object.keys(V);if(n.length>0){let t=A.derivative(n[0]);if(d||(t=t.multiply(V[n[0]])),n.length>1)for(let e of n.slice(1)){let n=A.derivative(e);d||(n=n.multiply(V[e])),t=t.add(n)}let r=t.multiply(c);try{x=r.f()}catch(e){}}}var S=[10,1,100,.1,1e3,.01],w=0;let E=0,D=!0,O=0;for(let t=0;t<1e3;t++){try{var I=R(S[w],m)}catch(e){continue}if(!1===I.always_zero&&(D=!1),!I.equal&&!I.out_of_bounds&&!I.always_zero&&!1!==I.sufficient_finite_values&&(O++,O>100))return!1;if(I.equal){if(I.always_zero){if(!D)continue;if(E+=1,E>5&&(w+=1,E=0),w>=S.length)return!0;continue}return!0}}return!1;function R(e,t){var r,a=n(t,g,e);for(let e=0;e0)||!(0===m||m>0))return{out_of_bounds:!0,always_zero:!1};var f=Math.min(d,m),y=Math.max(d,m),N=1;let A=0;if(x){try{A=math$1.abs(x(r))}catch(e){return{equal_at_start:!1,always_zero:!1}}if(!Number.isFinite(A))return{equal_at_start:!1,always_zero:!1}}if(A+=f*o,A=Math.min(A,.1*f),A+=0!==A||0!==c&&0!==p?l:u,!(0===y||math$1.abs(math$1.subtract(c,p))0))return{equal_at_start:!1,always_zero:!1}}var S=0===y,w=0;for(let r=0;r<100;r++){var E,D=n(t,g,.01,a);for(let e=0;e=10)return{equal:!0,always_zero:S}}}return{sufficient_finite_values:!1,always_zero:S}}};function replace_numbers_with_parameters({expr:e,variables:t,include_exponents:n=!1}){let r={},a=0;function i(){a++;let e="par"+a;for(;t.includes(e);)a++,e="par"+a;return e}return{expr_with_params:function e(t){if("number"==typeof t){if(0===t)return t;{let e=i();return r[e]=t,e}}if("string"==typeof t){if("pi"===t){if(math$1.define_pi){let e=i();return r[e]=math$1.PI,e}}else if("e"===t&&math$1.define_e){let e=i();return r[e]=math$1.e,e}return t}if(!Array.isArray(t))return t;let a=t[0],s=t.slice(1);return"^"!==a||n?[a,...s.map(e)]:[a,e(s[0]),s[1]]}((e=e.evaluate_numbers({max_digits:1/0})).tree),parameters:r}}function rename_functions_with_exponents(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("apply"===t){let e=n[0];return Array.isArray(e)&&"^"===e[0]&&e.slice(1).every((e=>["number","string"].includes(typeof e)))&&(e=astToText.convert(e)),["apply",e,n[1]]}return[t,...n.map(rename_functions_with_exponents)]}function rename_vecs(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return"vec"===t&&1===n.length?"__vec_"+astToText.convert(n[0]):[t,...n.map(rename_vecs)]}function randomComplexBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=math$1.complex(2*e()*n-n,2*e()*n-n)})):t.forEach((function(t){a[t]=math$1.complex(r[t].re+2*e()*n-n,r[t].im+2*e()*n-n)})),a}const equals$4=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:s=!1,allowed_error_is_absolute:o=!1,allow_blanks:l=!1}={}){if(!l&&(e.variables().includes("_")||t.variables().includes("_")))return!1;let u=seedrandom$1("complex_seed");return e=e.remove_scaling_units(),t=t.remove_scaling_units(),!(!e.isAnalytic({allow_abs:!0,allow_arg:!0,allow_relation:!0})||!t.isAnalytic({allow_abs:!0,allow_arg:!0,allow_relation:!0}))&&equals$5({expr:e,other:t,randomBindings:randomComplexBindings,expr_context:e.context,other_context:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:s,allowed_error_is_absolute:o,rng:u})};function randomRealBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=2*e()*n-n})):t.forEach((function(t){a[t]=r[t]+2*e()*n-n})),a}const equals$3=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:s=!1,allowed_error_is_absolute:o=!1}={}){if(!e.isAnalytic()||!t.isAnalytic())return!1;let l=seedrandom("real_seed");return equals$5({expr:e,other:t,randomBindings:randomRealBindings,expr_context:e.context,other_content:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:s,allowed_error_is_absolute:o,rng:l})},equals$2=function(e,t,{allowed_error_in_numbers:n=0,include_error_in_number_exponents:r=!1,allowed_error_is_absolute:a=!1,allow_blanks:i=!1}={}){if(!i&&(e.variables().includes("_")||t.variables().includes("_")))return!1;let s=e.normalize_function_names().normalize_applied_functions().normalize_angle_linesegment_arg_order(),o=t.normalize_function_names().normalize_applied_functions().normalize_angle_linesegment_arg_order();return equal(s.tree,o.tree,{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})},equals$1=function(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_discrete_infinite_set(e))return!1;if(is_discrete_infinite_set(t)){var a=[];let n=e.context.get_assumptions(e);if(void 0!==n&&a.push(n),n=t.context.get_assumptions(t),void 0!==n&&a.push(n),a=0===a.length?void 0:1===a.length?a[0]:clean_assumptions(["and"].concat(a)),r){let n=contained_in(e.tree,t.tree,a,r);if(!1===n)return 0;let i=contained_in(t.tree,e.tree,a,r);return!1===i?0:!0===n?!0===i?1:i:!0===i?n:Math.min(n,i)}return contained_in(e.tree,t.tree,a,r)&&contained_in(t.tree,e.tree,a,r)}{let r=t.tree;if("list"!==r[0])return!1;let a=r.length-2;if("ldots"!==r[a+1][0])return!1;if(acontained_in(e,t,n)))}var a=e[1],i=e[2],s=e[3],o=e[4];if(!Array.isArray(s)||"-"!==s[0]||s[1]!==1/0||o!==1/0)return!1;a=simplify(["/",a,i],n,1/0);var l=t.slice(1),u=[];for(let e=0;ee[0])))];let p=0;for(let e of c){let t=u.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),i=[];for(let r of t){let t=r[0],s=r[1],o=r[2],l=u[o][2],c=u[o][3];for(let r=0;rp&&(p=t)}}return!!(r&&p>0)&&p}function sequence_from_discrete_infinite(e,t){var n=e.tree.slice(1);if(n.length>1)return;let r=n[0][1],a=n[0][2],i=evaluate_numbers(n[0][3]),s=n[0][4];if(!Number.isInteger(i)||s!==1/0)return;let o=[];for(let e=0;e0))throw Error(`Have not implemented equality check with ${r} sign errors.`);if(r>1){let e=n;n=function(t,n){return equalSpecifiedSignErrors(t,n,{equalityFunction:e,n_sign_errors:r-1})}}var a,i,s=e.tree,o=[[s]],l=0;e.tree=["-",s];var u=n(e,t);if(e.tree=s,u)return!0;for(;a=o[l++];)if(a=a[0],Array.isArray(a))for(i=1;i"];function isAnalytic(e,{allow_abs:t=!1,allow_arg:n=!1,allow_relation:r=!1}={}){var a=normalize_applied_functions(normalize_function_names(e)),i=operators$3(a=subscripts_to_strings(a));for(let e=0;e+
")},"-":function(e){return"-"+e.join("-")+""},"*":function(e){return e.join('\\cdot*')},"/":function(e){return astToGuppy$1.dfrac(e[0],e[1])},"^":function(e){return astToGuppy$1.power(e[0],e[1])},sin:function(e){return astToGuppy$1.trig("sin",e[0])},cos:function(e){return astToGuppy$1.trig("cos",e[0])},tan:function(e){return astToGuppy$1.trig("tan",e[0])},arcsin:function(e){return astToGuppy$1.trig("arcsin",e[0])},arccos:function(e){return astToGuppy$1.trig("arccos",e[0])},arctan:function(e){return astToGuppy$1.trig("arctan",e[0])},arccsc:function(e){return astToGuppy$1.trig("arccsc",e[0])},arcsec:function(e){return astToGuppy$1.trig("arcsec",e[0])},arccot:function(e){return astToGuppy$1.trig("arccot",e[0])},csc:function(e){return astToGuppy$1.trig("csc",e[0])},sec:function(e){return astToGuppy$1.trig("sec",e[0])},cot:function(e){return astToGuppy$1.trig("cot",e[0])},log:function(e){return astToGuppy$1.trig("log",e[0])},exp:function(e){return astToGuppy$1.trig("exp",e[0])},ln:function(e){return astToGuppy$1.trig("ln",e[0])},sqrt:function(e){return astToGuppy$1.sqrt(e[0])},abs:function(e){return astToGuppy$1.abs(e[0])}}}static dfrac(e,t){return'\\dfrac{}{}\\frac{}{}()/()'+e+''+t+""}static trig(e,t){return'\\'+e+'\\left(\\right) '+e+'()'+t+""}static sqrt(e){return'\\sqrt{}sqrt()'+e+""}static power(e,t){return'{}^{}()^()'+e+''+t+""}static abs(e){return'\\left|\\right|abs()'+e+""}static paren(e){return'\\left(\\right)()'+e+""}static isFunctionSymbol(e){return-1!==["sin","cos","tan","csc","sec","cot","arcsin","arccos","arctan","arccsc","arcsec","arccot","log","ln","exp","sqrt","abs","this.factorial"].indexOf(e)}static isGreekLetterSymbol(e){return-1!==["pi","theta","theta","Theta","alpha","nu","beta","xi","Xi","gamma","Gamma","delta","Delta","pi","Pi","epsilon","epsilon","rho","rho","zeta","sigma","Sigma","eta","tau","upsilon","Upsilon","iota","phi","phi","Phi","kappa","chi","lambda","Lambda","psi","Psi","omega","Omega"].indexOf(e)}factorWithParenthesesIfNegated(e){var t=this.factor(e);return t.toString().match(/^-/)?astToGuppy$1.paren(t.toString()):t}factor(e){if("string"==typeof e)return astToGuppy$1.isGreekLetterSymbol(e)?'\\'+e+' $'+e+"":""+e+"";if("number"==typeof e)return""+e+"";if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);return"apply"===t&&(t=e[1],n=e.slice(2)),"abs"===t?this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this))):astToGuppy$1.isFunctionSymbol(t)?"this.factorial"!==t||1!==n[0].toString().length&&!n[0].toString().match(/^[0-9]*$/)?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.operators[t](n):"^"===t||"~"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):astToGuppy$1.paren(this.expression(e))}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"*"===t?this.operators[t](n.map(function(e,t){var n=this.factorWithParenthesesIfNegated(e);return n.toString().match(/^[0-9]/)&&t>0?" * "+n:n}.bind(this))):"/"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.factor(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t||"-"===t?this.operators[t](n.map(function(e,t){return this.factorWithParenthesesIfNegated(e)}.bind(this))):this.term(e)}convert(e){return(""+this.expression(e)+"").replace(/<\/e>/g,"")}}const glslOperators={"+":function(e){var t=e[0];return e.slice(1).forEach((function(e){t=t+"+"+e})),t},"-":function(e){var t="-"+e[0];return e.slice(1).forEach((function(e){t=t+"-"+e})),t},"~":function(e){var t="vec2(0.0,0.0)";return e.forEach((function(e){t=t+"-"+e})),t},"*":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cmul("+t+","+e+")"})),t},"/":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cdiv("+t+","+e+")"})),t},sin:function(e){return"csin("+e[0]+")"},cos:function(e){return"ccos("+e[0]+")"},tan:function(e){return"ctan("+e[0]+")"},sinh:function(e){return"csinh("+e[0]+")"},cosh:function(e){return"ccosh("+e[0]+")"},arcsin:function(e){return"carcsin("+e[0]+")"},arccos:function(e){return"carccos("+e[0]+")"},arctan:function(e){return"carctan("+e[0]+")"},arccsc:function(e){return"carcsin(cdiv(vec2(1.0,0),"+e[0]+"))"},arcsec:function(e){return"carccos(cdiv(vec2(1.0,0),"+e[0]+"))"},arccot:function(e){return"carctan(cdiv(vec2(1.0,0),"+e[0]+"))"},csc:function(e){return"ccsc("+e[0]+")"},sec:function(e){return"csec("+e[0]+")"},cot:function(e){return"ccot("+e[0]+")"},exp:function(e){return"cexp("+e[0]+")"},conj:function(e){return"conjugate("+e[0]+")"},sqrt:function(e){return"cpower("+e[0]+",vec2(0.5,0.0))"},log:function(e){return"clog("+e[0]+")"},ln:function(e){return"clog("+e[0]+")"},"^":function(e){return"cpower("+e[0]+","+e[1]+")"},abs:function(e){return"cabs("+e[0]+")"},apply:function(e){return"vec2(NaN,NaN)"}};class astToGLSL$1{constructor(){}convert(e){if("boolean"==typeof e)throw Error("no support for boolean");if("string"==typeof e)return"e"===e?"vec2(2.71828182845905,0.0)":"pi"===e?"vec2(3.14159265358979,0.0)":"i"===e?"vec2(0.0,1.0)":String(e);if("number"==typeof e)return"vec2("+String(e)+",0.0)";if("real"in e&&"imaginary"in e)return e;if(!Array.isArray(e))throw Error("Invalid ast");var t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to GLSL");return t=n[0],n=n.slice(1),glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)))}if(t in glslOperators)return glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var astToGuppy=new astToGuppy$1,astToGLSL=new astToGLSL$1;const tex=function(e,t){return new astToLatex$1(t).convert(e.tree)},toLatex=tex,toString=function(e,t){return new astToText$2(t).convert(e.tree)},toGLSL=function(e){return astToGLSL.convert(e.tree)},toXML=function(e){return astToGuppy.convert(e.tree)};var printing=Object.freeze({__proto__:null,tex:tex,toLatex:toLatex,toString:toString,toXML:toXML,toGLSL:toGLSL});const integrateNumerically=function(e,t,n,r){for(var a=0,i={},s=0;s<100;s++){var o=n+(r-n)*(s+.5)/100;i[t]=o,a+=e.evaluate(i)}return a*(r-n)/100};var integration=Object.freeze({__proto__:null,integrateNumerically:integrateNumerically});function expression_to_polynomial(e){var t=get_tree(e);if("string"==typeof t)return"pi"===t&&math$1.define_pi||"i"===t&&math$1.define_i||"e"===t&&math$1.define_e?t:["polynomial",t,[[1,1]]];if("number"==typeof t)return t;let n=evaluate_to_constant(t,!1);if(null!==n&&Number.isFinite(n))return simplify(t);if(!Array.isArray(t))return!1;if(!operators$3(t).every((e=>["+","-","*","^","/","_","prime"].includes(e))))return!1;var r=t[0],a=t.slice(1);if("+"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_add(e,t)))}if("-"===r){let e=expression_to_polynomial(a[0]);return!!e&&polynomial_neg(e)}if("*"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_mul(e,t)))}if("^"===r){let e=a[0],n=expression_to_polynomial(e);if(!1===n)return!1;let r=simplify(a[1]);if("number"!=typeof r||r<0||!Number.isInteger(r)){let n=evaluate_to_constant(r,!1);if(null!==n||Number.isFinite(n)){let t=math$1.fraction(n);if(t.d<=100){e=t.s<0?["^",e,["/",-1,t.d]]:["^",e,["/",1,t.d]];var i=["polynomial",simplify(e),[]];return i[2].push([t.n,1]),i}}return["polynomial",t,[[1,1]]]}return 0===r?1:1===r?n:polynomial_pow(n,r)}if("/"===r){var s=a[1],o=evaluate_to_constant(s,!1);return null!==o&&Number.isFinite(o)?polynomial_mul(expression_to_polynomial(a[0]),["/",1,o]):["polynomial",t,[[1,1]]]}return["polynomial",t,[[1,1]]]}function polynomials_in_same_leading_variable(e,t){return e[1]!==t[1]&&(compare_function(e[1],t[1])<0?t=["polynomial",e[1],[[0,t]]]:e=["polynomial",t[1],[[0,e]]]),[e,t]}function polynomial_add(e,t){if("polynomial"!==e[0]){if("polynomial"!==t[0])return simplify(["+",e,t]);e=["polynomial",t[1],[[0,e]]]}else if("polynomial"!==t[0])t=["polynomial",e[1],[[0,t]]];else{let n=polynomials_in_same_leading_variable(e,t);e=n[0],t=n[1]}let n=["polynomial",e[1],[]],r=e[2],a=t[2],i=n[2],s=r.length,o=a.length,l=0,u=0;for(;l0;)1&t&&(n=polynomial_mul(n,e)),e=polynomial_mul(e,e),t>>=1;return n}function polynomial_to_expression(e){if(!Array.isArray(e)||"polynomial"!==e[0])return e;let t=e[1],n=e[2],r=[],a=n.length;for(var i=0;ir[o][1])return!1}return a!==i&&s!==i}function mono_gcd(e,t){if(!Array.isArray(e)||!Array.isArray(t)||"monomial"!==e[0]||"monomial"!==t[0])return 1;let n=e[2],r=t[2],a=[],i=n.length,s=r.length,o=0,l=0;for(;o=0;){var r=[];r.push([e[2][t][1],n]),n=["polynomial",e[2][t][0],r],t-=1}return n}function max_div_init(e,t){if(0===e)return 0;let n=e,r=[];for(;Array.isArray(n)&&"polynomial"===n[0];){let e=n[1],t=n[2],a=t[t.length-1][0];n=t[t.length-1][1],r.push([e,a])}let a=["monomial",n,r],i=t.length;for(var s=0;s0?choice_lowest_degree(i):0}function update_hij_table(e,t,n){let r=t.length;t.push(n);let a=0,i=1,s=[];for(;i0?choice_lowest_degree(s):0}function choice_lowest_degree(e){let t=[],n=e.length;for(a=0;a15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\left\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\right\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\left\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\right\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\left\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\right\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],[",",","],[":",":"],["\\\\mid(?![a-zA-Z])","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\subseteq(?![a-zA-Z])","SUBSETEQ"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\not\\s*\\\\subseteq(?![a-zA-Z])","NOTSUBSETEQ"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\supseteq(?![a-zA-Z])","SUPERSETEQ"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\not\\s*\\\\supseteq(?![a-zA-Z])","NOTSUPERSETEQ"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["\\\\perp(?![a-zA-Z])","PERP"],["\\\\bot(?![a-zA-Z])","PERP"],["\\\\parallel(?![a-zA-Z])","PARALLEL"],["\\\\\\|","PARALLEL"],["\\\\angle(?![a-zA-Z])","ANGLE"],["\\\\int(?![a-zA-Z])","INT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots(?![a-zA-Z])","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\operatorname\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["\\\\[$%]","LATEXCOMMAND"],["[a-zA-Z_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","angle","circ","%","$"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","Re","Im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault=["f","g"],operatorSymbolsDefault={frac:{nargs:2,substitute:"/"},binom:{nargs:2},vec:{nargs:1},overline:{nargs:1,substitute:"linesegment",remove_products:!0}},unitsDefault=get_all_units();unitsDefault.circ=unitsDefault.deg,unitsDefault.circ.substitute="deg",unitsDefault.circ.isExponent=!0,delete unitsDefault.deg;const parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,operatorSymbols:a=operatorSymbolsDefault,units:i=unitsDefault,parseLeibnizNotation:s=parseLeibnizNotationDefault,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.operatorSymbols=a,this.units=i,this.parseLeibnizNotation=s;let l=base_latex_rules;l=o?[...number_rules_sci,...l]:[...number_rules_non_sci,...l],this.lexer=new lexer(l,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=n.length;for(let[t,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&t0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===t?["unit",n[0],s]:["unit",["*",...n.slice(0,t).map(this.convert_units_in_term.bind(this))],s],t===e-1?i:this.convert_units_in_term(["*",i,...n.slice(t+1)])}}}return[t,...n.map(this.convert_units_in_term.bind(this))]}if("/"===t)return["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])];if("^"===t){let e=this.units[n[1]];if(e&&e.isExponent){let t=n[1];return e.substitute&&(t=e.substitute),["unit",n[0],t]}return[t,...n.map(this.convert_units_in_term.bind(this))]}return[t,...n.map(this.convert_units_in_term.bind(this))]}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_single_digit_as_number(){if("NUMBER"===this.token.token_type&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.token.token_text.length>1&&this.lexer.unput(this.token.token_text.slice(1)),this.advance(),e}return null}get_subsuperscript({parse_absolute_value:e}){let t=this.get_single_digit_as_number();if(null!==t)return t;if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,r=0,i=[],s=[],o=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,o=0,s=[],l=this.token.token_type,this.advance()):(s.push(this.statement({parse_absolute_value:t})),o+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,this.advance(),a=["matrix",["tuple",n,r]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n=2?a[0]="("===n||"{"===n?"tuple":"["===n?"array":"LBRACE"===n?"set":"altvector":"LBRACE"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type[0]||!t||0!==e&&n&&"L"!==this.token.token_type[1]){if("LFLOOR"===this.token.token_type||"LCEIL"===this.token.token_type){let e,t;if("LFLOOR"===this.token.token_type?(e="RFLOOR",t="floor"):"LCEIL"===this.token.token_type&&(e="RCEIL",t="ceil"),this.advance(),a=["apply",t,a=this.statement()],this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance()}else if("ANGLE"===this.token.token_type)if(this.advance(),"{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]?a=["angle",...t.slice(1)]:"*"===t[0]&&(a=["angle",t])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;tn)return!1;if(s===n){if("}"!==this.token.token_type)return!1;this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var s=n(/^<([\w-:.]+)\s*/);if(s){for(var o,l={name:s[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();o=i();)l.children.push(o);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$2,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=s<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=o.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},c=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,o=a/(4*i),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&s|~a&o):u<40?1859775393+(a^s^o):u<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,l=o,o=s,s=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+s|0,n[3]=n[3]+o|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(s),e.HmacSHA1=r._createHmacHelper(s)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,s=0;s>>6-s%4*2;a[i>>>2]|=(o|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,o=0;o<4&&i+.75*o>>6*(3-o)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&s.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],s=!1;if(!Number.isFinite(i))if(deepCompare(i,t))s=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?s?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:s?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let s=r[2];return Number.isFinite(s)||(s=me$3.fromAst(s).evaluate_to_constant(),Number.isFinite(s)||s===1/0||s===-1/0)?a[0]?a[1]?new OpenInterval(i,s):new OpenClosedInterval(i,s):a[1]?new ClosedOpenInterval(i,s):new ClosedInterval(i,s):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var s;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(s in i){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1}for(s in t){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1;switch(typeof t[s]){case"object":case"function":if(r.push(t),a.push(i),!e(t[s],i[s]))return!1;r.pop(),a.pop();break;default:if(!(t[s]===i[s]||Number.isNaN(t[s])&&Number.isNaN(i[s])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],s=!1,o=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[o-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(s=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),s=0;for(let i=0;is){let n=t?i:i+1,r=e.substring(s,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],s=i+1}n--}else if(0===n&&!o.match(/\s/))return{success:!1}}if(e.length>s){let t=e.substring(s,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let s=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(s=!0)}for(;s&&n&&n(e.type,e.from,e.to,i),s=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;s=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));o=i[o+3]);return s}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,s=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?s.length:-1;e!=l;e+=t){let l=s[e],u=o[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let s=l.findChild(0,l.buffer.length,t,n-u,r);if(s>-1)return new BufferNode(new BufferContext(i,l,e,u),null,s)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let s;if(!(1&a)&&l.props&&(s=l.prop(NodeProp.mounted))&&!s.overlay)return new TreeNode(s.tree,u,e,i);let o=new TreeNode(l,u,e,i);return 1&a||!o.type.isAnonymous?o:o.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],s=n.buffer[this.index+2];e.push(n.slice(r,a,i,s)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:s=r.types.length}=e,o=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,f,y){let{id:g,start:b,end:v,size:N}=o,T=c;for(;N<0;){if(o.next(),-1==N){let t=i[g];return n.push(t),void f.push(b-e)}if(-3==N)return void(u=g);if(-4==N)return void(c=g);throw new RangeError(`Unrecognized record size: ${N}`)}let C,A,V=l[g],x=b-e;if(v-b<=a&&(A=function(e,t){let n=o.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let o=n.pos-e;if(e<0||o=s?4:0,d=n.start;for(n.next();n.pos>o;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=s&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(o.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=o.pos-A.size,a=t.length;for(;o.pos>n;)a=h(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=o.pos-N;o.next();let t=[],n=[],r=g>=s?g:-1,i=0,l=v;for(;o.pos>e;)r>=0&&o.id==r&&o.size>=0?(o.end<=l-a&&(d(t,n,b,i,o.end,l,r,T),i=t.length,l=o.end),o.next()):p(b,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,s=0,o=t.length-1;if(o>=0&&(a=t[o])instanceof Tree){if(!o&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(s=n[o]+a.length+i)}return m(e,t,n,r,s)}}(V);C=balanceRange(V,t,n,0,t.length,0,v-b,e,e)}else C=m(V,t,n,v-b,T-v)}n.push(C),f.push(x)}function d(e,t,n,a,i,s,o,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[o],u,c,s-i,l-s)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function h(e,t,n){let{id:r,start:a,end:i,size:l}=o;if(o.next(),l>=0&&r4){let r=o.pos-(l-4);for(;o.pos>r;)n=h(e,t,n)}t[--n]=s,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let f=[],y=[];for(;o.pos>0;)p(e.start||0,e.bufferStart||0,f,y,-1);let g=null!==(t=e.length)&&void 0!==t?t:f.length?y[0]+f[0].length:0;return new Tree(l[e.topID],f.reverse(),y.reverse(),g)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,s,o,l){let u=0;for(let n=r;n=c)break;h+=t}if(u==a+1){if(h>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+o);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+o-i)}}(t,n,r,a,0),(o||l)(p,d,s)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,s,o,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=s,this.bufferBase=o,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(o.allows(n)&&(-1==t.token.value||t.token.value==n||s.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,s=e[a+2];i>1,l=n+o+(o<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=o+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),s=e.curContext?e.curContext.hash:0,o=0;for(let r=0;ru.end+25&&(o=Math.max(u.lookAhead,o)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return o&&e.setLookAhead(o),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(s);else{if(this.advanceStack(s,a,n))continue;{e||(e=[],t=[]),e.push(s);let n=this.tokens.getMainToken(s);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let s=this.fragments.nodeAt(r);s;){let r=this.parser.nodeSet.types[s.type.id]==s.type?a.getGoto(e.state,s.type.id):-1;if(r>-1&&s.length&&(!t||(s.prop(NodeProp.contextHash)||0)==n))return e.useNode(s,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(s.type.id)})`),!0;if(!(s instanceof Tree)||0==s.children.length||s.positions[0]>0)break;let o=s.children[0];if(!(o instanceof Tree&&0==s.positions[0]))break;s=o}}let s=a.stateSlot(e.state,4);if(s>0)return e.reduce(s),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&s)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let o=this.tokens.getActions(e);for(let s=0;sr?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(s.deadEnd){if(a)continue;if(a=!0,s.restart(),verbose&&console.log(u+this.stackID(s)+" (restarted)"),this.advanceFully(s,n))continue}let c=s.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of s.recoverByInsert(o))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>s.pos?(l==s.pos&&(l++,o=0),s.recoverByDelete(o,l),verbose&&console.log(u+this.stackID(s)+` (via recover-delete ${this.parser.getName(o)})`),pushStackDedup(s,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id,this.reduce=e.reduce||id,this.reuse=e.reuse||id,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let s=-r;s>0;s--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,s=r[a++];if(i&&n)return s;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=a}n.parent()}n.parent();let s=n.to,o={componentType:r,props:{...i},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&o.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}o.children.push(t(n.node.cursor))}return o.range={openBegin:a,openEnd:s,closeBegin:n.from,closeEnd:n.to},o}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],s=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},o=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,s,o,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,h=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3),c[p++]=255&(l<<5|u);var f=d-h;return 2===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1)):7===f&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],o=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,o=0;i191&&t<=223?(n=31&t,o=1):t<=239?(n=15&t,o=2):t<=247?(n=7&t,o=3):s(i,r);for(var l=0;l191)&&s(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&s(i,r),n>1114111&&s(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(o(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",h=e.indexOf("=");-1===h&&(h=e.length);for(var f=0,y=h>>3<<3;f>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var g=h-y;return 2===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===g&&(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],c=a[e.charAt(f++)],p=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e[u],o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):t?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e.charCodeAt(u),o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):function(e){var t,n,a,s,o,l,u,c=!1,p="",d=0,m=0,h=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===h&&++d,d>h&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],s=i[3],o=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[31&(s<<3|o>>>5)]+r[31&o]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],s=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[s<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=o,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,s=retrieveTextFileFromIPFS(e),o=s.promise,l=s.controller,u=!1,c=!1;o.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let s=retrieveTextFileFromServer(e,t),o=s.promise;a=s.controller,o.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let s=n.toLowerCase();if(s in a){let t=a[s];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(s in t){let e=t[s];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,s=t({componentType:i,includeNonStandard:!1}),o=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!s){if(e||r)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t,n=""){for(let[r,a]of e.entries()){if(a.props&&["copy","updateValue","animateFromSequence"].includes(a.componentType)){let i,s,o,l,u,c,p;for(let e of Object.keys(a.props)){if("target"===e.toLowerCase()){if(i)throw Error(`Cannot repeat attribute ${e}. Found in component type ${a.componentType}${indexRangeString(a)}`);i=e,p=a.props[e];let t=buildSourcePieces(p,!0);t.success&&t.matchLength===p.length&&(s=t.sourceName,o=t.componentIndex,l=t.componentAttributes,u=t.propArray,c=t.subNames)}}if(i&&s)if(o||l||u.length>0){if(a.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);let d=createComponentFromExtendedSource({sourceName:s,componentIndex:o,subNames:c,componentAttributes:l,propArray:u,componentInfoObjects:t});if(d.success){let t=d.newComponent;if("copy"===a.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes),a.doenetAttributes.createNameFromComponentType||(a.doenetAttributes.createNameFromComponentType=a.componentType),a.componentType=t.componentType,0!==u.length||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes.isPlainCopy=!0),t.children&&(a.children=t.children);else if("copy"===t.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes);else{let s=createUniqueName("extract","fromExtendedSource"+n+"|"+r);t.doenetAttributes.prescribedName=s,t.doenetAttributes.createdFromMacro=!0;let o={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(o),delete a.props[i],a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.target=s,a.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===a.componentType?console.warn(`invalid copy source: ${p}`):console.warn(`invalid target: ${p}`)}else"copy"!==a.componentType||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isPlainCopy=!0)}a.children&&breakUpTargetIntoPropsAndIndices(a.children,t,n+"|"+r)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},s=Object.assign({},n.props);if(n.props)for(let o in n.props){let l=a[o.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}else if(!["name","assignnames","target"].includes(o.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${o} for component of type ${n.componentType}${indexRangeString(n)}`);i[o]=componentFromAttribute({value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:s,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let s={component:a};return e.ignoreFixed&&(s.ignoreFixed=!0),s}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}if(e&&e.createTargetComponentNames){return{targetComponentNames:t.rawString.trim().split(/\s+/).map((e=>("$"===e[0]&&"$"!==e[1]&&"("===(e=e.slice(1))[0]&&")"===e[e.length-1]&&(e=e.slice(1,e.length-1)),{relativeName:e})))}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===s.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),o=[l];let m=1,h=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let s=c+r[0].length,l=[],p=!1;i.length>u+s&&(p=!0,l.push(i.substring(u+s))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:o,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}o=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,h=""}let f=[];u>0&&f.push(i.substring(0,u)),f.push(...o),h.length>0&&f.push(h),e.splice(n,m,...f),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let s={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),s.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),s.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let o=!1;if(n){o=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(s.attributes,e.newAttributes),e.assignNames&&(s.props={assignNames:e.assignNames})}for(let e of r){if(o&&(s.doenetAttributes.createdFromMacro=!0,s={componentType:"extract",attributes:{},doenetAttributes:{},children:[s]}),s.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),s.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(s.attributes,t.newAttributes),t.assignNames&&(s.props={assignNames:t.assignNames})}o=!0}return{success:!0,newComponent:s}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,s=findWordOrDelimitedGroup(a,r);"("===s.startDelim&&(r=!0,a=s.group,i=s.group.length);let o=buildSourcePieces(a,r);if(o.success){if(r){if(o.matchLength!==i)return{success:!1};o.matchLength+=2}return o.nDollarSigns=t,o.firstIndMatched=n-t,o.matchLength+=t,o}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let s=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),s.push(a)}return a.propArray=s,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let s=[],o={"(":")","{":"}","[":"]"},l=Object.values(o),u=e[0],c=o[u];if(!c)return{success:!1};s.push(c);for(let t=1;t0?t[i]=s.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return o.length>0&&c.push(o),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[s,o]of e.entries()){if("object"!=typeof o)continue;let e=o.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+s,c={};for(let e in o.attributes){let t=o.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(o.children){let a={};if(!o.skipSugar)for(let[s,p]of l.returnSugarInstructions().entries()){let l=o.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==o.children.length)continue}let d=deepClone(o.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let h=!1;o.doenetAttributes&&o.doenetAttributes.createdFromMacro&&(h=!0);let f=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+s,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:h});if(f.success){let t=f.newChildren,n=f.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let s=[...r,...i];if(s.length!==m||!s.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}f.parametersForChildrenSugar&&Object.assign(a,f.parametersForChildrenSugar),o.children=t||[],n&&(o.attributes||(o.attributes={}),Object.assign(o.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(o.children=o.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:o.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(o.attributes)for(let e in o.attributes){let t=o.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,attributesByTargetComponentName:s,indOffset:o=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],h=d.doenetAttributes;void 0===h&&(h=d.doenetAttributes={});let f=d.attributes;f||(f=d.attributes={}),h.createNameFromComponentType&&(e=h.createNameFromComponentType);let y,g=h.prescribedName,b=h.assignNames,v=h.target,N=h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||h.createUniqueName;(f.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let T=void 0!==g,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==g)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);g=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==b)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);b=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(g){if(!T&&!h.createdFromSugar){if(!/[a-zA-Z]/.test(g.substring(0,1)))throw Error(`Invalid component name: ${g}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(g))throw Error(`Invalid component name: ${g}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}h.prescribedName=g}else if(N){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+o+"|"+l,g=createUniqueName(e.toLowerCase(),t)}if(!b&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(b=d.originalDoenetAttributes.assignNames),b){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(h.assignNames=b,!h.createUniqueAssignNames){let t=flattenDeep(b);if(!h.fromCopyTarget&&!h.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(f.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||(p.componentCounts[e]=++A);let V="";for(let e=0;e<=c;e++)V+=t[e].namespace+"/";if(!g){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");g=d.originalName.substring(e+1)}g||(g="_"+e.toLowerCase()+A)}if(h.nameBecomesAssignNames){y&&(f.assignNewNamespaces={primitive:!0},delete f.newNamespace,y=!1),b=h.assignNames=[g],delete h.nameBecomesAssignNames;let e=a+"|createUniqueName|";h.createUniqueName=!0,delete h.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+o+"|"+l,g=createUniqueName("copy",e)}if(V+=g,d.componentName=V,g){if(g in p.namesUsed)throw Error(`Duplicate component name ${V}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[g]=!0}if(!y&&b)for(let t of flattenDeep(b)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${V}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=V+"|createUniqueName|assignNames|",a="";if(y)a=V+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,attributesByTargetComponentName:s});b=d.doenetAttributes.assignNames=i}if(renameMatchingTargetNames(d,s),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${V}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);h.target=v,h.targetComponentName=convertComponentTarget({relativeName:v,oldAbsoluteName:h.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}for(let e in f){let n=f[e];if(n.targetComponentNames)for(let e of n.targetComponentNames)e.absoluteName=convertComponentTarget({relativeName:e.relativeName,oldAbsoluteName:e.absoluteName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}if(d.children)if(y||f.assignNewNamespaces?.primitive){let e={};b&&flattenDeep(b).forEach((t=>e[t]=!0));let r=d.children;if(h.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:g,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}let a={namespace:g,componentCounts:{},namesUsed:e};if(h.haveNewNamespaceOnlyFromShadow){let e=!0,o=[...r];for(;o.length>0;){let r=[];for(let t of o){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}o.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}else{let e=d.children;if(h.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}}return e}function createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,attributesByTargetComponentName:a}){let i=[];for(let[s,o]of e.entries())if(Array.isArray(o)){let e=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:o,longNameIdBase:t+s+"_",namespace:n,oldNamespace:r,attributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+s);i.push(e),renameMatchingTargetNames({componentName:n+e,originalName:r+o},a,!0)}return i}function convertComponentTarget({relativeName:e,oldAbsoluteName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:s=0,originalNamesAreConsistent:o=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(o){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],attributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],attributesByTargetComponentName:c})}}let d=[],m=0;for(let h=0;h0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(g)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)g=[g];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||s?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,attributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!o})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,attributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}for(let t in a.attributes){let i=a.attributes[t];if(i.targetComponentNames)for(let t of i.targetComponentNames){let a=t.absoluteName;void 0!==a&&(a.substring(0,r)!==e&&(t.relativeName=a),n[a]||(n[a]=[]),n[a].push(t))}}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,attributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],attributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,attributesByTargetComponentName:n})}}}function renameMatchingTargetNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.relativeName?(n.relativeName=e.componentName,n.absoluteName=e.componentName):(n.target=e.componentName,n.targetComponentName=e.componentName);if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.relativeName?(r.relativeName=e.componentName+"/"+n,r.absoluteName=e.componentName+"/"+n):(r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n)}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let s of e){if(s.doenetAttributes&&s.doenetAttributes.target){let e=s.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),s=!0;break}r&&o.indBegin>t&&a.push({begin:t,end:o.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:o.indBegin,stopInd:o.indEnd,enclosingComponentName:o.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=o.indEnd+1}return!s&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:s=!1,copiesByTargetComponentName:o={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,h=e[d];if("object"==typeof h){if(h.originalName){if(s){if(l.push(h.originalName),h.originalDoenetAttributes&&h.originalDoenetAttributes.assignNames){let e;if(h.attributes.newNamespace?.primitive)e=h.originalName;else{let t=h.originalName.lastIndexOf("/");e=h.originalName.substring(0,t)}for(let t of h.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}h.attributes&&(h.attributes.alias&&c.push(h.attributes.alias.primitive),h.attributes.indexAlias&&c.push(h.attributes.indexAlias.primitive))}if(m=i+h.originalName+"|shadow",!h.originalNameFromSerializedComponent)if(n){let e={[h.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[h.originalName][0].firstLevelReplacement=!0),r&&(e[h.originalName][0].isPrimaryShadow=!0),h.state){let t=Object.keys(h.state);e[h.originalName].downstreamStateVariables=t,e[h.originalName].upstreamStateVariables=t}h.downstreamDependencies=e}else h.unlinkedCopySource=h.originalName}else m=i+h.componentType+"|shadowUnnamed";if("copy"===h.componentType&&s){let e=h.doenetAttributes.targetComponentName;if(e)c.includes(h.doenetAttributes.target)?h.doenetAttributes.targetComponentName=h.doenetAttributes.target:(void 0===o[e]&&(o[e]=[]),o[e].push(h));else if(!h.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}h.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&s)for(let e in o)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of o[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let s=n.allComponentClasses[t],o=s.createAttributesObject(),l={};for(let e in o)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=o[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else s.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:s,flags:o}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m&&n&&(1===n.length&&n[0].numberReplacementsToReplace===p?d=n[0].serializedReplacements:m=!1),m?d||(d=t):(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let h=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:s=!1,ignoreReplacementsOfEncounteredComposites:o=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],s=!1,o=!1;if(r)n=r.component,n.adaptedFrom&&(o=!0),e.activeChildren.includes(n)&&(s=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,s=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(o=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(o&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(s||a)&&p.push(n))}if(s||o){let e=[];for(let t of p){let n=c(t);o&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:s,ignoreReplacementsOfEncounteredComposites:o,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let s=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await s.initialize(),s.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let s,o=this.downstreamDependencies[e][t].__determine_dependencies;if(o){let t=!0;if(o.originalDownstreamVariableNames.length>0)for(let[r,a]of o.downstreamComponentNames.entries()){let s=this._components[a];for(let l of o.mappedDownstreamVariableNamesByComponent[r]){let r=s.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};s=await o.getValue()}else s={changes:{},value:{stateValues:{}}};if(0===Object.keys(s.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},s.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,s=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let o in n)if(o in a){if(!deepCompare(n[o],a[o].definition)){i=!0,a[o].deleteDependency();let l=n[o],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),s.push(u)}}else{i=!0;let a=n[o],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),s.push(l)}return{changedDependency:i,newlyCreatedDependencies:s}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:s,usedDefault:o}=await i[e].getValue();n[e]=t,Object.keys(s).length>0&&(r[e]=s),o&&(a[e]=o)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),s=i.valuesChanged[a][t];if(!s&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(s=upValuesChangedSub[n]);if(!s){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);s=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===s.changed?s.changed={arrayKeysChanged:{}}:!0===s.changed&&(s.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(s.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(s.changed.arraySizeChanged=!0),Object.assign(s.changed.arrayKeysChanged,n.arrayKeysChanged))):s.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:s,dependencyBlocked:o}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;s&&(u+="|"+s,o&&(u+="|"+o));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:s,dependency:o}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[s];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:s});let t=this.upstreamDependencies[a][s];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:s,dependency:o}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:s,dependency:o})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:s});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let o=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(o.determineDependencies)for(let t of o.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let o=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});o=Object.assign({},o);for(let l in o)for(let u of[...o[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),s){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:s}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:s=!0,numPreviouslyNeeded:o}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:s});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:s});if(!o.success){if(!a)return o;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:s});if(!o.success)return o}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:s});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===o||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],o=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&o.push(t))}}let l=!1;for(let e of i)if(o.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,s],!this.circularResolveBlockedCheckPassed[s]){this.circularResolveBlockedCheckPassed[s]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let s=this.dependencyHandler.upstreamDependencies[e];s||(s=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===s[e]&&(s[e]=[]),s[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let s,o={componentType:i.componentType};if(this.skipComponentNames||(o.componentName=t),s=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,s.length>0){o.stateValues={};let t={},n=!1;for(let[a,l]of s.entries()){let s=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?s:l;if(!this.variablesOptional||s in i.state){let a=i.state[s];if(!a.deferred)if(o.stateValues[u]=await a.value,this.valuesChanged[e][s].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][s]),this.valuesChanged[e][s]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(o)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],s=this.mappedDownstreamVariableNamesByComponent[0][0],o=this.useMappedVariableNames?s:i;if((!this.variablesOptional||s in r.state)&&!r.state[s].deferred){let e=r.state[s];if(await e.value,a.stateValues[o]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[o]=t}this.valuesChanged[0][s].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][o]=this.valuesChanged[0][s]),this.valuesChanged[0][s]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];s||(s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let o of t)if(!i.variableNames.includes(o)){i.variableNames.push(o);let t=s[o];t||(t=s[o]=[]),t.includes(this)||t.push(this);let l=a.state[o];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][o];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let s=e.allChildren[i].component;if("object"==typeof s){let e=this.gatherUnexpandedComposites(s);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let s of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:s,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:s}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:s,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let o=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(o.unexpandedCompositesNotReady.length>0||o.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...o.unexpandedCompositesReady,...o.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of o.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=o.newReplacements,this.compositesFound.push(...o.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function h({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let s of e){let e=s.componentName+"/"+t[0],o=r.dependencyHandler._components[e];if(o)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(o);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=h({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let f of t)"object"==typeof f?(this.replacementPrimitives.push(null),n.push(f.componentName),r.push(f.componentType)):this.replacementPrimitives.push(f);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class AttributeTargetComponentNamesDependency extends StateVariableDependency{static dependencyType="attributeTargetComponentNames";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.targetComponentNames:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributeTargetComponentNamesDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class DoenetMLDependency extends Dependency{static dependencyType="doenetML";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.displayOnlyChildren=this.definition.displayOnlyChildren}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler.core.requestComponentDoenetML(this.componentName,this.displayOnlyChildren),changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DoenetMLDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace","nPr","nCr"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace","nPr","nCr"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset","angle","circ","$","%"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if(!vectorOperators.includes(e.tree[0])||!e.tree.includes())return{desiredValue:e};let i,s=n+"Ast";if(void 0!==r&&(s+=`_${r}`),a[s])i=a[s].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),a&&vectorOperators.includes(a.tree[0])&&(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[s]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return[...vectorOperators,"list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\operatorname{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}const vectorOperators=["vector","altvector","tuple"];function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],s=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of s)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let o=r.inverseDefinition;o&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await o(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?rcrypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),s=[],o=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(s.push(i),o++,o>=n))return s}return s}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],s=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let s,o=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],s=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:s});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:s},o=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),o?l.push({value:n,originalIndex:c}):l.push(n),u++,u===s)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:s}){if(!(e>=0&&(void 0===r||e0&&("math"===i?o=o.add(n.multiply(me$3.fromAst(e))).expand().simplify():o+=n*e),"math"===i){if(a.some((e=>e&&e.equals(o))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-o)<=1e-14*Math.max(Math.abs(e),Math.abs(o)))))return null}else if(a.includes(o))return null;return"letters"===i&&(o=numberToLetters(o,s)),o}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],s=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};s.push(r.desiredVariant)}return{success:!0,desiredVariants:s}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let s=[...a];if(s.lengthe.toLowerCase())),o=[...new Set(o)];for(let e of o)if(!s.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!s.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];o=o?o.filter((e=>!l.includes(e))):[...s].filter((e=>!l.includes(e)));let u=o.map((e=>s.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),h=void 0!==r?.attributes.uniqueVariants,f=r?.attributes.uniqueVariants?.primitive;if(f||!h){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),f=!!d.success&&(f||d.numberOfVariants<=i)}let y=[],g=[],b=[];if(f)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(g.push(t),y.push(o[e]),b.push(m[e]));else y=o,g=u,b=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=f,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=s,e.variants.allPossibleVariantUniqueIndices=g,e.variants.allPossibleVariantSeeds=b,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:s,componentInfoObjects:o,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=o,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in s)this.state[e]=Object.assign({},s[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants),n.range&&(this.doenetMLrange=n.range),this.actions={copyDoenetMLToClipboard:this.copyDoenetMLToClipboard.bind(this)}}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e.doenetML={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({doenetML:{dependencyType:"doenetML"}}),definition({dependencyValues:e}){let t=e.doenetML;return t||(t=""),{setValue:{doenetML:t}}}},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,s]of t.additionalStateVariablesDefined.entries()){let o={};for(let e of a)e in t&&(o[e]=t[e]);o.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],o.additionalStateVariablesDefined[n]=e,r(o.additionalStateVariablesDefined);let l=s;"object"==typeof s&&(l=s.variableName,s=Object.assign({},s),delete s.variableName,Object.assign(o,s)),i[l]=o}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],s=i.createStateVariable;if(s&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[s]={createComponentOfType:e,public:!0}}else r[s]={}}let s=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in s){let o=s[n];if(o.isAlias)i[n]=o.targetVariableName;else if((!e||o.public)&&(!t||o.forRenderer)&&(o.public?r[n]={createComponentOfType:o.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},o.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===o.nDimensions?1:o.nDimensions,r[n].wrappingComponents=o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents():[],e=o.entryPrefixes?o.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:o.returnEntryDimensions?o.returnEntryDimensions(t):1,wrappingComponents:o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents(t):[]};o.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=o.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let s=this.state[t];if(void 0===s||!s.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=s.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,s=e.variants.descendantVariantComponents,o=[];if(s.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=s[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};o.push(i.desiredVariant),a=!0}else o.push({})}let l={index:t};return a&&(l.subvariants=o),{success:!0,desiredVariant:l}}async copyDoenetMLToClipboard({actionId:e}){let t=await this.stateValues.doenetML;t?this.coreFunctions.copyToClipboard(t,e):this.coreFunctions.resolveAction({actionId:e})}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveText:this.moveText.bind(this)})}static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}replacements=[];replacementsToWithhold=0;get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}const vectorAndListOperators=["list",...vectorOperators];class MathComponent extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],s=t.stringChildren.length;if(0===s)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!vectorOperators.includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let s=1;s=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(vectorAndListOperators.includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===s[0]){let e=s[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],s[2]&&i.push(s[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(vectorAndListOperators.includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null},setEssentialValue:{expressionWithCodes:null}}}let n,r,a,i,s="",o=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let s=r===t;if(!s)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){s=!0;break}s&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)s+=" "+c+" ";else{let t,r=e.codePre+o;o++,t="latex"===e.format?"\\operatorname{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):s+=t}if(t===r){let o=s.trimEnd(),c=!1;if(0===o.length)c=!0;else{let n=o[o.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),s+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===s)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+s)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+s)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\operatorname{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\operatorname{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,s]of e.mathChildrenModifiable.entries()){let o=e.codePre+i;!0===s.stateValues.canBeModified?(t.push(i),n.push(o)):(r.push(o),a[o]=i)}let i=e.codePre+"expr",s=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(s.foundLinear){let e={},r=s.template,o=new Set;for(let r in s.mappings){e[r]=s.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,o.add(Number(i))}}return o.has=o.has.bind(o),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:o}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let s=e[0],o=e.slice(1);if(vectorAndListOperators.includes(s)){let e={mappings:{},template:[s]},i=0;for(let s=0;s!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let s=t.mathChildren,o=t.stringChildren.length;if(1===s.length&&0===o)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===s.length){let f=[];return o>0?f.push({setDependency:"expressionWithCodes",desiredValue:l}):f.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:f}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let g of c)y[g]&&m.push(...y[g])}let h=await n.mathChildrenWithCanBeModified;for(let[b,v]of s.entries())if(n.mathChildrenMapped.has(b)&&h[b].stateValues.canBeModified){if(!m.includes(b)){let N=p[b],T={},C=!1,A=await n.constantChildIndices;for(let V in A){let x=A[V];T[V]=s[x].stateValues.value,C=!0}C&&(N=N.substitute(T)),N=N.simplify(),d.push({setDependency:"mathChildren",desiredValue:N,childIndex:b,variableIndex:0})}delete p[b]}if(o>0){let S=t.expressionWithCodes,w=t.codePre,E=w.length;function D(e){return"string"==typeof e&&e.substring(0,E)===w}function O(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(D):D(e)}if(vectorAndListOperators.includes(S.tree[0])&&!S.tree.slice(1).every(O)){let I=await n.inverseMaps;for(let R in p){let _=I[R];if(void 0!==_.mathChildInd)continue;let M=_.components;S=S.substitute_component(M,p[R])}d.push({setDependency:"expressionWithCodes",desiredValue:S})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveLabel:this.moveLabel.bind(this)})}static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createTargetComponentNames:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={returnDependencies:()=>({forObject:{dependencyType:"attributeTargetComponentNames",attributeName:"forObject"}}),definition({dependencyValues:e}){let t;return t=1===e.forObject?.length?e.forObject[0].absoluteName:null,{setValue:{forObjectComponentName:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function s(){let n=!1;if(t){if(1===i.length){let t=i[0],s=t.componentType;"copy"===s&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(s=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:s,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?s():i.push(n);for(let e of t.slice(1))s(),""!==e&&i.push(e)}return s(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],s=await a.childIndexByArrayKey,o=[];for(let l in e.maths){if(!n[l])continue;if(o.includes(l))continue;let u;if(void 0!==s[l][2]){let t=Number(l)-s[l][1],n=t+s[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let s=t;s<=n;s++)void 0!==e.maths[s]?i.desiredMaths[s]=convertValueToMathExpression(e.maths[s]):void 0===i.desiredMaths[s]&&(i.desiredMaths[s]=(await a.maths)[s]),r.push(i.desiredMaths[s].tree),o.push(s.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let s=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:s}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),s=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return!1;let o=a[0][3],l=a[0][4];if(o!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,s);if(!(me$3.math.min(d,s-d)<1e-10*s))return!1;let m=1;for(let e=1;e=n)return!0;let h=m/Math.max(p,n);return h*=(9+c/2)/10,h}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],s=e[4];if(i!==-1/0||s!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var o=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=s.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],s=n[2],o=l[s][2],u=l[s][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}const nonTupleVectorOperators=["vector","altvector"];function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:s="none",expand:o=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:h=!1}){let f=!1;if(e instanceof me$3.class){if(f=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(f=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,g=function(e,t=!1){e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree)));let n=s,r=o;return t&&(n="full",r=!0),"none"===n?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===n?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===n?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:n,expand:r})};y=f?i?function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=g(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let b=!1,v=!1;if(f){e=g(e,!i),t=g(t,!i);let s=e.tree[0],o=t.tree[0];if("periodic_set"===s||"periodic_set"===o){let n=e,a=t;"periodic_set"!==s&&(n=t,a=e);let i=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===i?{fraction_equal:1}:!1===i?{fraction_equal:0}:{fraction_equal:i}}if("list"===s)e=e.tree.slice(1),t="list"===o?t.tree.slice(1):[t.tree];else if("list"===o)t=t.tree.slice(1),e=[e.tree];else if(nonTupleVectorOperators.includes(s)){if(e=e.tree.slice(1),"interval"===o||"matrix"===o||"array"===o||"set"===o)return{fraction_equal:0};t=vectorOperators.includes(o)?t.tree.slice(1):[t.tree]}else if(nonTupleVectorOperators.includes(o)){if(t=t.tree.slice(1),"interval"===s||"matrix"===s||"array"===s||"set"===s)return{fraction_equal:0};e="tuple"===s?e.tree.slice(1):[e.tree]}else if("interval"===s){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===o||"set"===o)return{fraction_equal:0};if("tuple"===o){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===o){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==o)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===o){a=!0;let n=t.tree[2],r=n[1],i=n[2];if(t=t.tree[1].slice(1),"matrix"===s||"set"===s)return{fraction_equal:0};if("tuple"===s){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==i)return{fraction_equal:0};e=t}else{if("array"!==s)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==i)return{fraction_equal:0};e=t}}}else if("matrix"===s){if("matrix"!==o)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,b=!0}else{if("matrix"===o)return{fraction_equal:0};if("set"===s){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===o||"array"===o)return{fraction_equal:0};if("set"===o){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===o){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===s||"array"===s)return{fraction_equal:0};e=[e.tree]}else if("tuple"===s){if(e=e.tree.slice(1),"array"===o)return{fraction_equal:0};t="tuple"===o?t.tree.slice(1):[t.tree]}else if("tuple"===o){if(t=t.tree.slice(1),"array"===s)return{fraction_equal:0};e=[e.tree]}else if("array"===s)e=e.tree.slice(1),t="array"===o?t.tree.slice(1):[t.tree];else{if("array"!==o)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let N=e.length,T=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(N,T);for(let r=0;rArray(T+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(V+=r,A.add(e))}return N===T&&N===V?(C.fraction_equal=1,C):r?(C.fraction_equal=V/Math.max(N,T),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],s=e.slice(1);if("not"===i)return 1!==s.length?(console.warn("Invalid format for boolean condition"),r):0===a(s[0])?1:0;if("and"===i)return n.matchPartial?s.reduce(((e,t)=>e+a(t)),0)/s.length:s.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?s.reduce(((e,t)=>Math.max(a(t),e)),0):s.some((e=>1===a(e)))?1:0;let o=!1,l=!1,u=!1,c=!1;s.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?o=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(s[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(s[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===s[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(o||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(s=s.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(o||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(s=s.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(o)return console.warn("Invalid format for boolean condition"),r;let e=!1;return s=s.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?s.slice(1).every((e=>deepCompare(e,s[0])))?1:0:"ne"===i?2!==s.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(s[0],s[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=s[1].slice(1),s=s[0].slice(1));let m=!1,h=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(h)]:e},f=s.map((function(e){return me$3.fromAst(h(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=f[0];if(Number.isNaN(e.tree))return f.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=f.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return f.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:f[0],object2:f[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=f[0],t=f[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let g=f.map((e=>e.simplify().evaluate_to_constant()));if(g.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return g[0]"===i)return g[0]>g[1]?1:0;if("le"===i)return g[0]<=g[1]?1:0;if("ge"===i)return g[0]>=g[1]?1:0;for(let e=0;eg[e+1]))return 0}else if(!(g[e]>=g[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);if(["and","not","or"].includes(a))return[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))];if(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a){i=[i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))];let e=!1;if("int"===i[0]?e=!0:Array.isArray(i[0])&&("^"===i[0][0]?("int"===i[0][1]||Array.isArray(i[0][1])&&"_"===i[0][1][0]&&"int"===i[0][1][1])&&(e=!0):"_"===i[0][0]&&"int"===i[0][1]&&(e=!0)),e){i=me$3.fromAst([a,...i]).tree.slice(1);let e=i[1];if(Array.isArray(e)&&"*"===e[0]){let t=[];for(let n=0;nsplitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s={},o={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:s,textListChildrenByCode:o,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"}))r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})){let t=s.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(s.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"}))r.push(...s.stateValues.numbers),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN));else{let t=s.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN))}let s=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(s.stateValues.value)),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})?(r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})?(r.push(...s.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN))):(r.push(...s.stateValues.maths),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN)));let s=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,s=!1,o=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?s=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?o=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||s&&n===t||o&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let s=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let s=[];for(let t=0;tNaN;let l=e-1;t[0][o];let u,c,p=t[l][o],d=n.map((e=>e[o]));return i&&(u=s[o]),r&&(c=a[o]),function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:NaN;if(e>=l)return r?(e-=l,(c[2]*e+c[1])*e+c[0]):e===l?p:NaN;let t=Math.floor(e);e-=t;let n=d[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,s=1/0,o=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?o=!e.tree[2][1]:i=-1/0,s=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(s)?l=!e.tree[2][2]:s=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=s)||o&&n===i||l&&n===s)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let h=Math.max(0,m);n-=e[h];let f=t[h];return((f[3]*n+f[2])*n+f[1])*n+f[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let s=n.map((e=>e.subscripts_to_strings().tree)),o=s.length;return o>3||!s.every((e=>e===r))||s.includes("_")?e=>0:0===o||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===o?(3*e[3]*n+2*e[2])*n+e[1]:2===o?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===o?(3*a[3]*n+2*a[2])*n+a[1]:2===o?6*a[3]*n+2*a[2]:6*a[3]}for(var r,s=0,l=e.length-1;s<=l;){r=Math.floor(.5*(s+l));let a=e[r];if(an))return 1===o?t[r][1]:2===o?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===o?(3*c[3]*n+2*c[2])*n+c[1]:2===o?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$1 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],s=null,o=e[r].throughSlopes;null!==o&&(s=o.stateValues["math"+a],void 0===s&&(s=null)),n[r]={x:i[0],y:i[1],slope:s}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}:{};return{setValue:{fDefinitions:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.fDefinitions[r];return{setValue:{fDefinitions:t}}}if(e.numericalfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}},t.fDefinition={isAlias:!0,targetVariableName:"fDefinition1"},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]+r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]-r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,s=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(s=t.slope.evaluate_to_constant(),Number.isFinite(s)||(console.warn("Ignoring non-numerical slope"),s=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:s})}else n.push({type:e,x:a,y:i,slope:s});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,s=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:o});l=n.type,i=n.x,o=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let h=p[p.length-1];if("maximum"===h.type){let e={type:"point",x:h.x+u,y:h.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===h.type){let e={type:"point",x:h.x+u,y:h.y+c,slope:2*c/u};p.push(e)}else if("point"===h.type)if(1===p.length){let e={type:"point",x:h.x+u,y:h.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-h.y)/(e.x-h.x);if("maximum"===e.type||"minimum"===e.type)null===h.slope&&(h.slope=2*t);else{2===p.length?null===h.slope&&(h.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:p[p.length-3],nextPoint:h})),null===h.slope&&(h.slope=2*(e.y-h.y)/(e.x-h.x)-e.slope));let n={x:h.x+u,y:h.y+u*h.slope,slope:h.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("point"===n||"point"===r){let o="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(o="minimum"),"minimum"===o?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t})}return null!==e.y&&e.ys-c){let n,a,o=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(s,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=s-c),p.push({type:a,x:o,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],s=[i-c,t+c],o=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:o[e],value:s[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=s[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===s?i:"minimum"===o.type?Math.min(i,s):Math.min(i,s-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,h=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===h.success?(l="maximum",n=h.point.y,r.splice(h.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===s?i-c:"minimum"===o.type?Math.min(i-c,s):Math.min(i,s)-c;else if(t>i-c){let n,i,s=(e+a)/2,o=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),o=0):(i="point",n=t+c),p.push({type:i,x:s,y:n,slope:o})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...s]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:r,arraySize:a}){if(e.operatorBasedOnFormula){let t={};for(let n of r)t[n]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:n};return{setValue:{fDefinitions:t}}}if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},s=!1,o=!1;void 0===t?(i.location=!0,o=!0):(a.location=t,s=!0),void 0===r?(i.value=!0,o=!0):(a.value=r,s=!0);let l={};return s&&(l.setValue=a),o&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,s]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(s)?"location":"value":"x"+(Number(s)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"ol",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,s=e.chunkSize,o=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*s,p=me$3.math.dopri(c,c+s,r,l,o,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+s)){t.maxPossibleTime=d;let e="For chunksize "+s+" and tolerance "+o+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this),mouseDownOnPolyline:this.mouseDownOnPolyline.bind(this)})}static componentType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.verticesDraggable={createComponentOfType:"boolean"},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.verticesDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({verticesDraggableAttr:{dependencyType:"attributeComponent",attributeName:"verticesDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.verticesDraggableAttr?{setValue:{verticesDraggable:e.verticesDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{verticesDraggable:{defaultValue:e.draggable}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].vertices;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){if(1===Object.keys(e).length){if(!await this.stateValues.verticesDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPolyline({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,s]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let s,o,l;try{s=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],o=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(o[0]);l=[o[0],t]}else l=[o[1],o[1]];Math.pow(s[0]-l[0],2)+Math.pow(s[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this),mouseDownOnPoint:this.mouseDownOnPoint.bind(this)})}static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&vectorOperators.includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},s=!1;if(null!==e.coords?(s=!0,r=e.coords.stateValues.value):e.coordsShadow&&(s=!0,r=e.coordsShadow),s){let e=r.tree;if(Array.isArray(e)&&vectorOperators.includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let o={};return Object.keys(a).length>0&&(o.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(o.useEssentialOrDefaultValue={unconstrainedXs:i}),o},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,s,o=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",s=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",s=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)o.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)s[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)o.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)o.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?o.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):o.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(s[1]):(s[0]="vector",e=me$3.fromAst(s));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),o.push(t)}return{success:!0,instructions:o}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&vectorOperators.includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPoint({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this),mouseDownOnLine:this.mouseDownOnLine.bind(this)})}static componentType="line";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let s=a[0],o=a[1],l=t*s,u=n*o,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/s,h=d/o,f={};return f.x1=(u*(u*m-l*h)-l*r)*s/c,f.x2=(l*(-u*m+l*h)-u*r)*o/c,void 0!==e.x3&&(f.x3=0),f}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLine({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let s=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),o=[];o=Array.isArray(s.tree)&&"+"===s.tree[0]?s.tree.slice(1):[s.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of o){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,s=0,o=0;if("string"==typeof e)e===a?t=1:e===i?s=1:o=e;else if("number"==typeof e)o=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],s=["-",e.coeffvar2.tree],o=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this),mouseDownOnCurve:this.mouseDownOnCurve.bind(this)})}static componentType="curve";static rendererType="curve";static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}if(0===a.length)return{success:!1};let o=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=o({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...s]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.domainForFunctions={returnDependencies:()=>({parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"}}),definition:({dependencyValues:e})=>({setValue:{domainForFunctions:[me$3.fromAst(["interval",["tuple",e.parMin,e.parMax],["tuple",!0,!0]])]}})},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].through;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let s=e[0],o=t.vectorControlDirections[s],l=[];"none"===o?l=[s-1,s,s+1]:"previous"===o?l=[s,s+1]:"next"===o&&(l=[s-1,s]);for(let e of l)e>=0&&eNumber(e))),s=r.map((e=>e+1)),o=s.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,s,o=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),s=i.map((e=>e+1)),o=s.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+o]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,s=e.controlPoints[r];s.tree&&(s=s.tree);let o=me$3.fromAst(["+",s,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:o})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,s=e[r].nextVector,o=[];for(let e=0;e<2;e++)o.push(initCubicPoly(t[e],a[e],3*i[e],-3*s[e]));n[r]=o}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],s=n[0],o=n[1],l=a*a+o*o,u=(o*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[s,n,0]],extrapolateBackwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],s=n[0]+n[1]+n[2]+n[3],o=n[1]+2*n[2]+3*n[3],l=a*a+o*o,u=(o*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[s,n,0]],extrapolateForwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0,entryPrefixes:["fDefinition"]}],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"fDefinitions"},domain:{stateVariableToShadow:"domainForFunctions"}}},returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType){let t={functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},n={},r={};return t.component=0,n[0]=returnBezierFunctions(t),r[0]=t,t={...t},t.component=1,n[1]=returnBezierFunctions(t),r[1]=t,{setValue:{fs:n,fDefinitions:r}}}let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,s,o]=n[0],[l,u,c,p]=n[1],d=3*(s*p-c*o),m=3*(r*p-u*o),h=r*c-u*s;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-h/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*h;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let s=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(s=!0)}i=s}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnCurve({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,s=e.parMin;return function({variables:o,scales:l}){let u,c,p,d,m=o.x1?.evaluate_to_constant(),h=o.x2?.evaluate_to_constant(),f=l[0],y=l[1];if(s!==-1/0){if(u=s,c=r(s),!Number.isFinite(c)){let e=.99999*s+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*s+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(h)){let e,t;if(n?(t=h,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(s-h),a=Math.abs(i-h)):(r=Math.abs(s-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),s=n?n.map((e=>e.evaluate_to_constant())):[2*o[0]-l[0],2*o[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};s=n.map((e=>e.evaluate_to_constant())),l=[2*o[0]-s[0],2*o[1]-s[1]]}let c=[];if("centripetal"===i){let n=u(s,o),r=u(o,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],s=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(s)&&s>0))return null;let o,l=`${n}${i}`;o="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(o).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let s=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))s.push(t(e));else s.push(t(i.tree));n.push({orbitalText:r,boxes:s})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class OrbitalDiagramInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.splice(s,1);let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"U");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"D");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length>0&&(n[a].boxes[s]=n[a].boxes[s].slice(0,-1));let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let s=t.type;s||(s=n.type),s?["number","letters","math","text","boolean"].includes(s)||(console.warn(`Invalid type ${s}, setting type to number`),s="number"):s="number";let o="letters"===s?"text":s;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:o})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:o})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+s))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,s=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:s}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,s=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let s={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(s.useEssentialOrDefaultValue={specifiedMargins:a}),s},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+s))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={valigns:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let s=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DisplayDoenetML extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="displayDoenetML";static rendererType="text";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({childrenDoenetML:{dependencyType:"doenetML",displayOnlyChildren:!0}}),definition:({dependencyValues:e})=>({setValue:{value:e.childrenDoenetML}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre,DisplayDoenetML:DisplayDoenetML});class Paginator extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={returnDependencies:()=>({paginator:{dependencyType:"attributeTargetComponentNames",attributeName:"paginator"}}),definition({dependencyValues:e}){let t;return t=1===e.paginator?.length?e.paginator[0].absoluteName:null,{setValue:{paginatorComponentName:t}}}},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:vectorOperators.includes(e)&&(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1===await n.numColumns&&Array.isArray(e)&&vectorOperators.includes(e[0])){let t=e.length-1;if(rt){let s=deepClone(e),o=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:Array.isArray(t[1])&&vectorOperators.includes(t[1][0])&&("^"===e&&"T"===t[2]||"prime"===e)&&(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,s=i[0];if(Array.isArray(i[1])&&vectorOperators.includes(i[1][0])&&("^"===s&&"T"===i[2]||"prime"===s)){let t=i[1].length-1;if(rt){let s=deepClone(i),o=(await n.accumulatedComponents)[0];o||(o=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if(vectorOperators.includes(e)){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&vectorOperators.includes(r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;eo&&(u=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,o+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else u-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,s=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;eo&&(c=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,o+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else c-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let s=await r(t),o=await r(i);deepCompare(o.tree,s.tree)||a.push({setDependency:"immediateValue",desiredValue:o,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,s]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,s]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,s=e.propName;if(e.isPlainMacro?s=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(s=t.allComponentClasses[a.componentType].variableForPlainCopy),s){n["propName"+r]={dependencyType:"value",value:s};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:s,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:s}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let o=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],s=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);s.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let h=await e.stateValues.effectivePropNameBySource;for(let t in d){if(h[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let f=[],y=[],g=[],b=0,v=0;for(let i in d){let o,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;o=Math.floor(t/n),i"string"!=typeof e)).length,b+=y[i],v+=g[i],f.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=g,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:f,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],h=await e.stateValues.link;h&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let f=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,g=(await e.stateValues.effectivePropNameBySource)[t];if(g){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:g,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let b=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,N=[await m.serialize({copyAll:!h,copyVariants:!h,sourceAttributesToIgnore:b,sourceAttributesToIgnoreRecursively:v})];h||void 0===N[0].state?.fixed||delete N[0].state.fixed,N=postProcessCopy({serializedComponents:N,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:h,unlinkExternalCopies:!h}),N.length>0&&delete N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:s,compositeCreatesNewNamespace:f,flags:c});Object.assign(t.attributes,n)}return N[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),N=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:N,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o,originalNamesAreConsistent:f&&!y}).serializedComponents,p&&1===N.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:N,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:o}),{serializedReplacements:N}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let s=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of s.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...s.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:s,publicCaseInsensitiveAliasSubstitutions:o}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let s=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:s.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await s({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await s({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let h=0,f=0,y=[],g=[],b=[],v=Math.max(c.length,r.numReplacementsBySource.length),N=!1;for(let t=0;t0){if(!N){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToDelete:e};m.push(t)}N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,g[t]=0,b.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||N;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){h+=r.numReplacementsBySource[t],f+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],g[t]=r.numNonStringReplacementsBySource[t];continue}let T=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:h,numNonStringReplacementsSoFar:f,uniqueIdentifiersUsed:T,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:o,flags:i}),A=C.propVariablesCopiedByReplacement,V=C.serializedReplacements,x=V.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToReplace:e,serializedReplacements:V,assignNamesOffset:f};m.push(n),N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(s=!1,i=!0):e.replacements[h+a].componentType!==V[a].componentType&&(i=!0)),0==a&&i&&s){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h+a,numberReplacementsToReplace:1,serializedReplacements:[V[a]],assignNamesOffset:f+n};m.push(e)}"string"!=typeof V[a]&&n++}}let S=V.filter((e=>"string"!=typeof e)).length;h+=x,f+=S,y[t]=x,g[t]=S,b[t]=A}let T=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=g,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=b;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return T&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:s,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:s,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,h=d.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:h,assignNamesOffset:r};return{numReplacements:h.length,numNonStringReplacements:h.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:f}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,h=t[n.componentName],f=l({stateVariables:[r],componentClass:h.constructor})[0];if(void 0===f||"__not_public"===f.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=h.state[f],g=await y.value,b=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,g;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=h.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,g=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,N=v.length,T=o;if(y.isArray)T=l.slice(0,l.length-N).reduce(((e,t)=>e*t),1);else if(0===g.length)T=0;else if(0===N)T=g.length;else if(N>=y.nDimensions)T=1;else if(N===y.nDimensions-1)T=r.length;else{T=flattenLevels(r,y.nDimensions-N-1).length}if(0===N){let o=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await o(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,o,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),f=t.shadowingInstructions.createComponentOfType;if(Array.isArray(f)&&(f=f[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=h.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){o={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=h.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),o[e]={stateVariableToShadow:n}}}if(b){let t={};if(r){let n=s.allComponentClasses[f].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,s={componentType:n[a].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:s}}}l.push({componentType:f,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:o}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=h.state[n],s=await a.value;a.isArray&&(s=s[a.keyToIndex[i]]),h.state[n].usedDefault||(t[e]=s)}let n=convertAttributesForComponentType({attributes:t,componentType:f,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=s.allComponentClasses[f];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let o=t.keyToIndex(i);Array.isArray(o)||(o=[o]);let c=await t.value;for(let e of o)c=c[e];let p={componentType:f,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await o(r,y.nDimensions),N=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),b&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,ignorePrimaryStateVariable:!0}]})}if(m+=N.length,c.push(...N),N.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(g[e])]:n[e]));let s={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(s.doenetAttributes=r),c.push(s)}else if(N>T)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(f);let t=getUniqueIdentifierFromBase(h.componentName+"|shadow|"+f,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(b){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=s.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[h.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await h.state[n].value;h.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=s.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:g},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:o}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:o}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToDelete:e};s.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let h=n.sourceNames[a],f=void 0===h||d.componentName!==h||m;if(!f)for(let t=0;te+t),0);g.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}s.push(g);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],g=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:o,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),b=g.propVariablesCopiedByReplacement,v=g.serializedReplacements,N=v.length;if(N!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:o};s.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==b[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:o+e};s.push(t)}o+=N,l[a]=N,u[a]=b}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:s}){if(!await e.stateValues.targetComponent)return{replacements:[]};let o=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:o}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let h=e.attributes.newNamespace?.primitive,f=(await e.stateValues.effectivePropNameByComponent)[n];if(f){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:f,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:s,compositeCreatesNewNamespace:h,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:h,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let f=r.collectedNames[t];if(void 0===f||l.componentName!==f||y){let l=0;void 0!==f&&(l=r.numReplacementsByCollected[t]);let h=l;y&&(h=0);let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:h,components:n,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let N=v.replacementInstruction;if(m[t]=N.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);N.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(N);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}),N=v.propVariablesCopiedByReplacement,T=v.serializedReplacements,C=T.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:T,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==N[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[T[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=N,m[t]=T.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=h.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:h}}}class Ref extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{navigateToTarget:this.navigateToTarget.bind(this)})}static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,s=null,o=e.uri.match(/[:&]cid=([^&^#]+)/i);return o&&(t=o[1]),o=e.uri.match(/[:&]doenetid=([^&^#]+)/i),o&&(n=o[1]),o=e.uri.match(/[:&]variant=([^&^#]+)/i),o&&(r=Number(o[1]),!Number.isInteger(r)&&r>=1&&(r=1)),o=e.uri.match(/[:&]edit=([^&^#]+)/i),o&&(i="true"===o[1].toLowerCase()),o=e.uri.match(/[:&]draft=([^&^#]+)/i),o&&(a="true"===o[1].toLowerCase()),o=e.uri.match(/(#.+)/i),o&&(s=o[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:s}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}async navigateToTarget({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.cid,n=await this.stateValues.doenetId,r=await this.stateValues.variantIndex,a=await this.stateValues.edit,i=await this.stateValues.hash,s=await this.stateValues.page,o=await this.stateValues.uri,l=await this.stateValues.targetName,u=this.componentOrAdaptedName;this.coreFunctions.navigateToTarget({cid:t,doenetId:n,variantIndex:r,edit:a,hash:i,page:s,uri:o,targetName:l,actionId:e,componentName:this.componentName,effectiveName:u})}}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this),mouseDownOnLineSegment:this.mouseDownOnLineSegment.bind(this)})}static componentType="lineSegment";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpointsDraggable={createComponentOfType:"boolean"},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.endpointsDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({endpointsDraggableAttr:{dependencyType:"attributeComponent",attributeName:"endpointsDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.endpointsDraggableAttr?{setValue:{endpointsDraggable:e.endpointsDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{endpointsDraggable:{defaultValue:e.draggable}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),s=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+s]?r[n]=e[n].endpointsAttr.stateValues["pointX"+s]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.endpoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+o]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoints:{dependencyType:"stateVariable",variableName:"endpoints"}}),definition({dependencyValues:e}){let t=0,n=e.endpoints[0],r=e.endpoints[1],a=!0;for(let i=0;ie+t*t),0));r=r.map((e=>e/o));let l=e.length.evaluate_to_constant();if(!Number.isFinite(l)||l<0)return{success:!1};let u=[],c=[],p=l/2;for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e}async moveLineSegment({point1coords:e,point2coords:t,transient:n,actionId:r}){if(void 0===e||void 0===t){if(!await this.stateValues.endpointsDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};return void 0!==e&&(a["0,0"]=me$3.fromAst(e[0]),a["0,1"]=me$3.fromAst(e[1])),void 0!==t&&(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{point1:e,point2:t}}})}async lineSegmentClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLineSegment({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Ray extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveRay:this.moveRay.bind(this),rayClicked:this.rayClicked.bind(this),mouseDownOnRay:this.mouseDownOnRay.bind(this)})}static componentType="ray";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoint={createComponentOfType:"point"},e.through={createComponentOfType:"point"},e.direction={createComponentOfType:"vector"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):s=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(s=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?s=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let s=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnRay({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{constructor(e){super(e),Object.assign(this.actions,{movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this),mouseDownOnPolygon:this.mouseDownOnPolygon.bind(this)})}static componentType="polygon";static representsClosedPath=!0;get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}get mouseDownOnPolygon(){return this.mouseDownOnPolyline}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),s=Number(t)+1+"_"+(Number(i)+1),o=e[a].vertices;null!==o&&o.stateValues["pointX"+s]?n[a]=o.stateValues["pointX"+s]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+o]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let s=Number(r),o=t[r].vertex0,l=t[r].vertex2,u=e.center[s].subtract(i[s]),c=o.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),s="2_"+(Number(a)+1);e="0"===r?i:"2"===r?s:"1"===r?"0"===a?s:i:"0"===a?i:s,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:s}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let o,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(o=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==o){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[o].specifiedWidth,desiredValue:e},{setDependency:s[o].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[l].specifiedHeight,desiredValue:e},{setDependency:s[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:s[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:s[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:s[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:s[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,s=await this.stateValues.vertices,o=s[i][0],l=s[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(o).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(o).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=o.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=o.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{constructor(e){super(e),Object.assign(this.actions,{moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this),mouseDownOnCircle:this.mouseDownOnCircle.bind(this)})}static componentType="circle";static rendererType="circle";static representsClosedPath=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],s=e.numericalThroughPoints[0][1],o=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&s===o)if(r===i&&s===l)t=[r,s],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&s===l||a===i&&o===l){let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[a,o]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+s*s,u=a*a+o*o,c=i*i+l*l,p=r*(o-l)-s*(a-i)+a*l-i*o,d=e*(l-o)+u*(s-l)+c*(o-s),m=e*(a-i)+u*(i-r)+c*(r-a),h=e*(i*o-a*l)+u*(r*l-i*s)+c*(a*s-r*o);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*h)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],s=Math.pow(n-r,2)+Math.pow(a-i,2),o=t*t;return t<0||4*o0)return{success:!0,instructions:s};if(0===t.nThroughPoints){for(let t in e.numericalCenter)s.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:s}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,s=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],s=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){s=!1;break}i.push(t)}if(s&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),s=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let o=Math.atan2(s-r,i-n),l={x1:n+t*Math.cos(o),x2:r+t*Math.sin(o)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],s=await this.stateValues.nThroughPoints,o=await this.stateValues.numericalPrescribedCenter;if((s<=1||null!==o)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),s>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;if(null!==s&&s.stateValues["pointX"+i]){let e=s.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],s=t[1],o=e.numericalThroughPoints[0],l=o[0];return n=(o[1]-s)/(l-i)**2,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return s===c?o==p?(r=-2*n*s,a=n*l+o):(i=!1,n=NaN,r=NaN,a=NaN):(r=(o-p-n*(l-d))/(s-c),a=o-n*l-r*s),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],h=m[0],f=m[1],y=h*h,g=l-y,b=d-y,v=s-h,N=c-h,T=o-f,C=p-f,A=g*N-b*v;if(0===A){let t,u,d,m=!1;s===c?o===p?s===h?o==f?t=1:m=!0:(t=2,u=h,d=f):m=!0:s===h?o===f?(t=2,u=c,d=p):m=!0:c===h&&p===f?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*s,a=n*s*s+o):(n=e.aShadow,r=(o-d-n*(l-u*u))/(s-u),a=o-n*l-r*s)}else n=(T*N-C*v)/A,r=(C*g-T*b)/A,a=o-r*s-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let s=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await s("a"),t=await s("b"),n=await s("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await s("a"),n=await s("b"),r=await s("c"),i=t.numericalThroughPoints[0][0],o=t.numericalThroughPoints[1][0];if(i===o){i=-n/(2*e);let t=r-n*n/(4*e),s=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&s.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:s}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[o,e*o*o+n*o+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await s("a"),r=await s("b"),i=await s("c"),o=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(o===l?o===u?c=1:(c=2,e=3):o===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[l,n*l*l+r*l+i],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{o=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let s=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*s*a,additionalDependencyValues:{c:i+s*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],s=t.x1?.evaluate_to_constant(),o=t.x2?.evaluate_to_constant();if(!Number.isFinite(s)||!Number.isFinite(o))return{};s/=a,o/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(s+u*o-u*c)/e*a,n.x2=(u*(s+u*o)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-o,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-s)/d,1e-14),h=m[0],f=e.f(h*a)/i,y=(s-h)**2+(o-f)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(s-n)**2+(o-r)**2;l0){const t=Math.sqrt(s/108),n=2*Math.sqrt(Math.cbrt(i*i/4+s/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const o=Math.sqrt(-s/108);return[Math.cbrt(-i/2+o)+Math.cbrt(-i/2-o)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let s=t.pointIndMap[e[0]];void 0!==s&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[s]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[s]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),s=e[n].direction;if(0===t[1])if("none"===s||"next"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}o&&("symmetric"===s?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===s||"previous"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length)if("both"===s){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===s?me$3.fromAst(-e):me$3.fromAst(e))}o&&("symmetric"===s?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let s=i.split(",").map((e=>Number(e))),o=s.map((e=>e+1)),l=n[i].direction;if(l)if(0===s[1]){if("none"!==l&&"next"!==l){let s=n[i].controlChild,u=!0;if(s&&1===s.length){s[0].stateValues["vectorX1_"+o[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===s[1]&&"none"!==l&&"previous"!==l){let s,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+o[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+o[2]]&&(c=!1)}s="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(s=s.evaluate_to_constant(),Number.isFinite(s)||(s=NaN),s=me$3.fromAst(s),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:s}):a[i]=s):r.push({setDependency:t[i].controlChild,desiredValue:s,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!s.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),s=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,s],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this),mouseDownOnVector:this.mouseDownOnVector.bind(this)})}static componentType="vector";static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.displayWithAngleBrackets={createComponentOfType:"boolean",createStateVariable:"displayWithAngleBrackets",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros","displayWithAngleBrackets"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let s=t[i].componentAttr;null===s?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=s.stateValues.value.simplify();break;default:let o=e.displacementShadow.tree;Array.isArray(o)&&vectorOperators.includes(o[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:s=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(s=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?s=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.magnitude={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=0,n=!0;for(let r=0;re/i));let s=e.magnitude.evaluate_to_constant();if(!Number.isFinite(s)||s<0)return{success:!1};let o=[];for(let e=0;e({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"},displayWithAngleBrackets:{dependencyType:"stateVariable",variableName:"displayWithAngleBrackets"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");if(t.length>1){t=[e.displayWithAngleBrackets?"altvector":"vector",...t]}else t=1===t.length?t[0]:"_";return{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.slice(1).map((e=>me$3.fromAst(e))):[e.displacementCoords],{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let s=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnVector({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.emphasizeRightAngle={createComponentOfType:"boolean",createStateVariable:"emphasizeRightAngle",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),s=t.stateValues.points[1][1].evaluate_to_constant(),o=Math.atan2(s-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(o)),"0,1":me$3.fromAst(n.x2+Math.sin(o)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=o+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),s=t.stateValues.points[0][1].evaluate_to_constant(),o=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];i=n.stateValues.points[0][0].evaluate_to_constant(),s=n.stateValues.points[0][1].evaluate_to_constant(),o=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),s=r["1,1"].evaluate_to_constant(),o=Math.atan2(a-s,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(o)),r["2,1"]=me$3.fromAst(s+Math.sin(o))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),s=t.stateValues.coeffvar2.evaluate_to_constant(),o=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(o)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*s-i*r;if(Math.abs(l)<1e-14)return Math.abs(o*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===s&&0===o?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(o*r-a*s)/l,c=(a*i-o*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$2=util$1.isObject,isArray$3=util$1.isArray,isRegex=util$1.isRegex,assign$1=util$1.assign,keys$1=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$1({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,s=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const o=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$2(u)||null===u)return i(u);if(isArray$3(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(s=!0,p=!0):i(e,"text")||i(e,"textList")?(o=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(h.push(!1),s=!0,c=!0):i(t,"textInput")?(h.push(!1),o=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(h.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,h.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(t.handGraded&&!m&&(p=!0),!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let f=[],y=[],g=[];if(0===h.filter((e=>!e)).length)f=e;else{if(!h[0]){let t=h.indexOf(!0);-1!==t&&(y=e.slice(0,t),e=e.slice(t),h=h.slice(t))}let t=h.indexOf(!1);-1===t?f=e:(f=e.slice(0,t),g=e.slice(t))}for(;"string"==typeof f[0]&&""===f[0].trim();)f=f.slice(1);let b,v,N=f.length;for(;"string"==typeof f[N-1]&&""===f[N-1].trim();)f=f.slice(0,N-1),N=f.length;if(t.type?(v=t.type,["math","text","boolean"].includes(v)||(console.warn(`Invalid type ${v}`),v="math")):v=s?"math":o?"text":l?"boolean":"math",0===f.length)b=[...y,...g];else{let e;e=f.length>1||n.isInheritedComponentType({inheritedComponentType:f[0].componentType,baseComponentType:"_composite"})&&!f[0].props?.componentType?[{componentType:v,children:f}]:f,b=[...y,{componentType:"award",children:e},...g]}if(p&&!c){b=[{componentType:v+"Input"},...b]}return{success:!0,newChildren:b}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag&&!e.handGraded:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!(e.haveAwardThatRequiresInput||e.handGraded)||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","formula","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):void 0!==e.stateValues.value?(n.push(e.stateValues.value),r.push(t)):e.stateValues.formula instanceof me$3.class?(n.push(e.stateValues.formula),r.push("math")):(n.push(""),r.push("text"))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[s,o]of a.entries())if(e>o||null===o){r.splice(s,0,t.componentName),r=r.slice(0,n),a.splice(s,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit;await this.stateValues.handGraded&&(n=0);let r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],s=await this.stateValues.inputChildrenWithValues;if(1===s.length){let e=s[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let o=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:o}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of o)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:o,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:o,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,s=!1,o=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?s=!0:i(t,"text")||i(t,"textList")?o=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=s?"math":o?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let s=await t.unionFromU,o=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,s=await t.functionSymbols,o=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:s,splitSymbols:o,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let s;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let o=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{s=o(e)}catch(e){s=me$3.fromAst("_")}return s}class Textinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0,fallBackToParentStateVariable:"expanded"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateBoolean:this.updateBoolean.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateSelectedIndices:this.updateSelectedIndices.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s=0,o=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=o+s;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,s+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,s=await e.stateValues.step,o=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:s,type:o,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:s,length:i,exclude:l,type:o,lowercase:await e.stateValues.lowercase}),p=o;"letters"===o&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let s=await e.stateValues.from,o=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(s)}else{let t=!1;"math"===u?s.equals(a.from)&&l.equals(a.step)||(t=!0):s===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,h=0,f=d;if(od&&(m=o-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,h+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,h+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(h=d,f=0),h>0)for(let t=f;t0){let t=[],a=e.attributes.newNamespace?.primitive,o={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(o[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:o,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let h={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(h)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=s,a.length=o,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,o),s.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:o,iterateNumber:r,componentInfoObjects:a,flags:i});s.push(...n.replacements),r=n.iterateNumber}return{replacements:s,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let s=n.lastReplacementParameters,o=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==s.sourcesNames.length)l=!1;else for(let e=0;e1&&(o=!0)}else o=!0;if(o){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(s),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let h=await e.stateValues.minNIterates,f=s.minNIterates,y=0,g=e.replacementsToWithhold;g||(g=0);let b=s.withheldSubstitutionChildNames,v=!1;if(hf){let t=h-f;if(g>0)if(g>=t){y=g-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=g,f+=g,y=0;if(t>0){let t=[];for(let n=f;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),Object.assign(this.actions,{changeValue:this.changeValue})}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:s}){let o=e;if(0===r.length){if(!Number.isFinite(o))return;let e=Math.round((o-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return o>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(o-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}class Pegboard extends GraphicalComponent{static componentType="pegboard";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0,forRenderer:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0,forRenderer:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0,forRenderer:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0,forRenderer:!0},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let s=t({variables:{[i]:e[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={returnDependencies:()=>({graphComponentName:{dependencyType:"attributeTargetComponentNames",attributeName:"baseOnGraph"}}),definition:({dependencyValues:e})=>1===e.graphComponentName?.length?{setValue:{graphComponentName:e.graphComponentName[0].absoluteName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,s={["x"+n]:t[i].x},o=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:s,scales:e.scales});r.constrained&&(s["x"+n]=convertValueToMathExpression(r.variables["x"+n]),o=!0)}r[i]=s["x"+n],a[i]=o}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,s={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:s,scales:t.scales});n.constrained&&(s["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:s["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let s={};for(let e in i.desiredConstraintResults)s[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:s}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:s}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:s}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x1:Math.max(s,Math.min(o,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x2:Math.max(s,Math.min(o,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(!Number.isFinite(s))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)n&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let s=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,s={};for(let e in t)s[e]=findFiniteNumericalValue(t[e]);for(let o of e.nearestPointFunctions){let e=o({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==s.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(s.x1-e.x1,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(s.x2-e.x2,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(s.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,s={},o={};for(let e in r)o[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==o.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((o.x1-e.x1)/t,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((o.x2-e.x2)/n,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(o.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:s}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,s={};for(let[o,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],s=r[1];if(2!==i.stateValues.nDimensions||2!==s.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let o=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=s.stateValues.numericalCoeffvar1,p=s.stateValues.numericalCoeffvar2,d=s.stateValues.numericalCoeff0;if(!(Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=o*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*o-u*c)>1e-14)return{replacements:[]};if(0===o&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}}let h=(d*l-u*p)/m,f=(u*c-d*o)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",h,f]),draggable:!1,fixed:!0}}],g=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:g,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,s=!0;if(i===e.replacements.length){s=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let s=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>s&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let s,o,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===s)return[];if(!s){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=s,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=s,[e]}}let o=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return o.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=s,o}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t} +let n=poly_div(e,[t]),r=0,a=n[0].length;for(var i=0;i15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\left\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\right\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\left\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\right\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\left\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\right\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],[",",","],[":",":"],["\\\\mid(?![a-zA-Z])","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\forall(?![a-zA-Z])","FORALL"],["\\\\exists(?![a-zA-Z])","EXISTS"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\subseteq(?![a-zA-Z])","SUBSETEQ"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\not\\s*\\\\subseteq(?![a-zA-Z])","NOTSUBSETEQ"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\supseteq(?![a-zA-Z])","SUPERSETEQ"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\not\\s*\\\\supseteq(?![a-zA-Z])","NOTSUPERSETEQ"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["\\\\perp(?![a-zA-Z])","PERP"],["\\\\bot(?![a-zA-Z])","PERP"],["\\\\parallel(?![a-zA-Z])","PARALLEL"],["\\\\\\|","PARALLEL"],["\\\\angle(?![a-zA-Z])","ANGLE"],["\\\\int(?![a-zA-Z])","INT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots(?![a-zA-Z])","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\operatorname\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["\\\\[$%]","LATEXCOMMAND"],["[a-zA-Z_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","angle","circ","%","$"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","Re","Im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault=["f","g"],operatorSymbolsDefault={frac:{nargs:2,substitute:"/"},binom:{nargs:2},vec:{nargs:1},overline:{nargs:1,substitute:"linesegment",remove_products:!0}},unitsDefault=get_all_units();unitsDefault.circ=unitsDefault.deg,unitsDefault.circ.substitute="deg",unitsDefault.circ.isExponent=!0,delete unitsDefault.deg;const parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,operatorSymbols:a=operatorSymbolsDefault,units:i=unitsDefault,parseLeibnizNotation:s=parseLeibnizNotationDefault,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.operatorSymbols=a,this.units=i,this.parseLeibnizNotation=s;let l=base_latex_rules;l=o?[...number_rules_sci,...l]:[...number_rules_non_sci,...l],this.lexer=new lexer(l,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];if("FORALL"===this.token.token_type||"EXISTS"===this.token.token_type){let t=this.token.token_type.toLowerCase();return this.advance(),[t,this.relation(e)]}for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=n.length;for(let[t,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&t0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===t?["unit",n[0],s]:["unit",["*",...n.slice(0,t).map(this.convert_units_in_term.bind(this))],s],t===e-1?i:this.convert_units_in_term(["*",i,...n.slice(t+1)])}}}return[t,...n.map(this.convert_units_in_term.bind(this))]}if("/"===t)return["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])];if("^"===t){let e=this.units[n[1]];if(e&&e.isExponent){let t=n[1];return e.substitute&&(t=e.substitute),["unit",n[0],t]}return[t,...n.map(this.convert_units_in_term.bind(this))]}return[t,...n.map(this.convert_units_in_term.bind(this))]}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_single_digit_as_number(){if("NUMBER"===this.token.token_type&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.token.token_text.length>1&&this.lexer.unput(this.token.token_text.slice(1)),this.advance(),e}return null}get_subsuperscript({parse_absolute_value:e}){let t=this.get_single_digit_as_number();if(null!==t)return t;if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,r=0,i=[],s=[],o=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,o=0,s=[],l=this.token.token_type,this.advance()):(s.push(this.statement({parse_absolute_value:t})),o+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,this.advance(),a=["matrix",["tuple",n,r]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n=2?a[0]="("===n||"{"===n?"tuple":"["===n?"array":"LBRACE"===n?"set":"altvector":"LBRACE"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type[0]||!t||0!==e&&n&&"L"!==this.token.token_type[1]){if("LFLOOR"===this.token.token_type||"LCEIL"===this.token.token_type){let e,t;if("LFLOOR"===this.token.token_type?(e="RFLOOR",t="floor"):"LCEIL"===this.token.token_type&&(e="RCEIL",t="ceil"),this.advance(),a=["apply",t,a=this.statement()],this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance()}else if("ANGLE"===this.token.token_type)if(this.advance(),"{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]?a=["angle",...t.slice(1)]:"*"===t[0]&&(a=["angle",t])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;tn)return!1;if(s===n){if("}"!==this.token.token_type)return!1;this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var s=n(/^<([\w-:.]+)\s*/);if(s){for(var o,l={name:s[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();o=i();)l.children.push(o);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$2,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=s<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=o.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},c=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,o=a/(4*i),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&s|~a&o):u<40?1859775393+(a^s^o):u<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,l=o,o=s,s=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+s|0,n[3]=n[3]+o|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(s),e.HmacSHA1=r._createHmacHelper(s)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,s=0;s>>6-s%4*2;a[i>>>2]|=(o|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,o=0;o<4&&i+.75*o>>6*(3-o)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&s.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],s=!1;if(!Number.isFinite(i))if(deepCompare(i,t))s=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?s?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:s?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let s=r[2];return Number.isFinite(s)||(s=me$3.fromAst(s).evaluate_to_constant(),Number.isFinite(s)||s===1/0||s===-1/0)?a[0]?a[1]?new OpenInterval(i,s):new OpenClosedInterval(i,s):a[1]?new ClosedOpenInterval(i,s):new ClosedInterval(i,s):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var s;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(s in i){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1}for(s in t){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1;switch(typeof t[s]){case"object":case"function":if(r.push(t),a.push(i),!e(t[s],i[s]))return!1;r.pop(),a.pop();break;default:if(!(t[s]===i[s]||Number.isNaN(t[s])&&Number.isNaN(i[s])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],s=!1,o=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[o-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(s=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),s=0;for(let i=0;is){let n=t?i:i+1,r=e.substring(s,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],s=i+1}n--}else if(0===n&&!o.match(/\s/))return{success:!1}}if(e.length>s){let t=e.substring(s,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let s=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(s=!0)}for(;s&&n&&n(e.type,e.from,e.to,i),s=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;s=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));o=i[o+3]);return s}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,s=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?s.length:-1;e!=l;e+=t){let l=s[e],u=o[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let s=l.findChild(0,l.buffer.length,t,n-u,r);if(s>-1)return new BufferNode(new BufferContext(i,l,e,u),null,s)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let s;if(!(1&a)&&l.props&&(s=l.prop(NodeProp.mounted))&&!s.overlay)return new TreeNode(s.tree,u,e,i);let o=new TreeNode(l,u,e,i);return 1&a||!o.type.isAnonymous?o:o.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],s=n.buffer[this.index+2];e.push(n.slice(r,a,i,s)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:s=r.types.length}=e,o=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,f,y){let{id:g,start:b,end:v,size:N}=o,T=c;for(;N<0;){if(o.next(),-1==N){let t=i[g];return n.push(t),void f.push(b-e)}if(-3==N)return void(u=g);if(-4==N)return void(c=g);throw new RangeError(`Unrecognized record size: ${N}`)}let C,A,V=l[g],x=b-e;if(v-b<=a&&(A=function(e,t){let n=o.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let o=n.pos-e;if(e<0||o=s?4:0,d=n.start;for(n.next();n.pos>o;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=s&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(o.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=o.pos-A.size,a=t.length;for(;o.pos>n;)a=h(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=o.pos-N;o.next();let t=[],n=[],r=g>=s?g:-1,i=0,l=v;for(;o.pos>e;)r>=0&&o.id==r&&o.size>=0?(o.end<=l-a&&(d(t,n,b,i,o.end,l,r,T),i=t.length,l=o.end),o.next()):p(b,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,s=0,o=t.length-1;if(o>=0&&(a=t[o])instanceof Tree){if(!o&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(s=n[o]+a.length+i)}return m(e,t,n,r,s)}}(V);C=balanceRange(V,t,n,0,t.length,0,v-b,e,e)}else C=m(V,t,n,v-b,T-v)}n.push(C),f.push(x)}function d(e,t,n,a,i,s,o,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[o],u,c,s-i,l-s)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function h(e,t,n){let{id:r,start:a,end:i,size:l}=o;if(o.next(),l>=0&&r4){let r=o.pos-(l-4);for(;o.pos>r;)n=h(e,t,n)}t[--n]=s,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let f=[],y=[];for(;o.pos>0;)p(e.start||0,e.bufferStart||0,f,y,-1);let g=null!==(t=e.length)&&void 0!==t?t:f.length?y[0]+f[0].length:0;return new Tree(l[e.topID],f.reverse(),y.reverse(),g)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,s,o,l){let u=0;for(let n=r;n=c)break;h+=t}if(u==a+1){if(h>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+o);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+o-i)}}(t,n,r,a,0),(o||l)(p,d,s)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,s,o,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=s,this.bufferBase=o,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(o.allows(n)&&(-1==t.token.value||t.token.value==n||s.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,s=e[a+2];i>1,l=n+o+(o<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=o+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),s=e.curContext?e.curContext.hash:0,o=0;for(let r=0;ru.end+25&&(o=Math.max(u.lookAhead,o)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return o&&e.setLookAhead(o),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(s);else{if(this.advanceStack(s,a,n))continue;{e||(e=[],t=[]),e.push(s);let n=this.tokens.getMainToken(s);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let s=this.fragments.nodeAt(r);s;){let r=this.parser.nodeSet.types[s.type.id]==s.type?a.getGoto(e.state,s.type.id):-1;if(r>-1&&s.length&&(!t||(s.prop(NodeProp.contextHash)||0)==n))return e.useNode(s,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(s.type.id)})`),!0;if(!(s instanceof Tree)||0==s.children.length||s.positions[0]>0)break;let o=s.children[0];if(!(o instanceof Tree&&0==s.positions[0]))break;s=o}}let s=a.stateSlot(e.state,4);if(s>0)return e.reduce(s),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&s)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let o=this.tokens.getActions(e);for(let s=0;sr?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(s.deadEnd){if(a)continue;if(a=!0,s.restart(),verbose&&console.log(u+this.stackID(s)+" (restarted)"),this.advanceFully(s,n))continue}let c=s.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of s.recoverByInsert(o))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>s.pos?(l==s.pos&&(l++,o=0),s.recoverByDelete(o,l),verbose&&console.log(u+this.stackID(s)+` (via recover-delete ${this.parser.getName(o)})`),pushStackDedup(s,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id,this.reduce=e.reduce||id,this.reuse=e.reuse||id,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let s=-r;s>0;s--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,s=r[a++];if(i&&n)return s;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=a}n.parent()}n.parent();let s=n.to,o={componentType:r,props:{...i},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&o.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}o.children.push(t(n.node.cursor))}return o.range={openBegin:a,openEnd:s,closeBegin:n.from,closeEnd:n.to},o}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],s=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},o=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,s,o,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,h=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3),c[p++]=255&(l<<5|u);var f=d-h;return 2===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1)):7===f&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],o=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,o=0;i191&&t<=223?(n=31&t,o=1):t<=239?(n=15&t,o=2):t<=247?(n=7&t,o=3):s(i,r);for(var l=0;l191)&&s(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&s(i,r),n>1114111&&s(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(o(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",h=e.indexOf("=");-1===h&&(h=e.length);for(var f=0,y=h>>3<<3;f>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var g=h-y;return 2===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===g&&(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],c=a[e.charAt(f++)],p=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e[u],o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):t?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e.charCodeAt(u),o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):function(e){var t,n,a,s,o,l,u,c=!1,p="",d=0,m=0,h=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===h&&++d,d>h&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],s=i[3],o=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[31&(s<<3|o>>>5)]+r[31&o]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],s=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[s<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=o,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,s=retrieveTextFileFromIPFS(e),o=s.promise,l=s.controller,u=!1,c=!1;o.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let s=retrieveTextFileFromServer(e,t),o=s.promise;a=s.controller,o.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let s=n.toLowerCase();if(s in a){let t=a[s];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(s in t){let e=t[s];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,s=t({componentType:i,includeNonStandard:!1}),o=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!s){if(e||r)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t,n=""){for(let[r,a]of e.entries()){if(a.props&&["copy","updateValue","animateFromSequence"].includes(a.componentType)){let i,s,o,l,u,c,p;for(let e of Object.keys(a.props)){if("target"===e.toLowerCase()){if(i)throw Error(`Cannot repeat attribute ${e}. Found in component type ${a.componentType}${indexRangeString(a)}`);i=e,p=a.props[e];let t=buildSourcePieces(p,!0);t.success&&t.matchLength===p.length&&(s=t.sourceName,o=t.componentIndex,l=t.componentAttributes,u=t.propArray,c=t.subNames)}}if(i&&s)if(o||l||u.length>0){if(a.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);let d=createComponentFromExtendedSource({sourceName:s,componentIndex:o,subNames:c,componentAttributes:l,propArray:u,componentInfoObjects:t});if(d.success){let t=d.newComponent;if("copy"===a.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes),a.doenetAttributes.createNameFromComponentType||(a.doenetAttributes.createNameFromComponentType=a.componentType),a.componentType=t.componentType,0!==u.length||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes.isPlainCopy=!0),t.children&&(a.children=t.children);else if("copy"===t.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes);else{let s=createUniqueName("extract","fromExtendedSource"+n+"|"+r);t.doenetAttributes.prescribedName=s,t.doenetAttributes.createdFromMacro=!0;let o={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(o),delete a.props[i],a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.target=s,a.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===a.componentType?console.warn(`invalid copy source: ${p}`):console.warn(`invalid target: ${p}`)}else"copy"!==a.componentType||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isPlainCopy=!0)}a.children&&breakUpTargetIntoPropsAndIndices(a.children,t,n+"|"+r)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},s=Object.assign({},n.props);if(n.props)for(let o in n.props){let l=a[o.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}else if(!["name","assignnames","target"].includes(o.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${o} for component of type ${n.componentType}${indexRangeString(n)}`);i[o]=componentFromAttribute({value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:s,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let s={component:a};return e.ignoreFixed&&(s.ignoreFixed=!0),s}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}if(e&&e.createTargetComponentNames){return{targetComponentNames:t.rawString.trim().split(/\s+/).map((e=>("$"===e[0]&&"$"!==e[1]&&"("===(e=e.slice(1))[0]&&")"===e[e.length-1]&&(e=e.slice(1,e.length-1)),{relativeName:e})))}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===s.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),o=[l];let m=1,h=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let s=c+r[0].length,l=[],p=!1;i.length>u+s&&(p=!0,l.push(i.substring(u+s))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:o,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}o=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,h=""}let f=[];u>0&&f.push(i.substring(0,u)),f.push(...o),h.length>0&&f.push(h),e.splice(n,m,...f),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let s={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),s.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),s.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let o=!1;if(n){o=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(s.attributes,e.newAttributes),e.assignNames&&(s.props={assignNames:e.assignNames})}for(let e of r){if(o&&(s.doenetAttributes.createdFromMacro=!0,s={componentType:"extract",attributes:{},doenetAttributes:{},children:[s]}),s.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),s.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(s.attributes,t.newAttributes),t.assignNames&&(s.props={assignNames:t.assignNames})}o=!0}return{success:!0,newComponent:s}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,s=findWordOrDelimitedGroup(a,r);"("===s.startDelim&&(r=!0,a=s.group,i=s.group.length);let o=buildSourcePieces(a,r);if(o.success){if(r){if(o.matchLength!==i)return{success:!1};o.matchLength+=2}return o.nDollarSigns=t,o.firstIndMatched=n-t,o.matchLength+=t,o}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let s=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),s.push(a)}return a.propArray=s,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let s=[],o={"(":")","{":"}","[":"]"},l=Object.values(o),u=e[0],c=o[u];if(!c)return{success:!1};s.push(c);for(let t=1;t0?t[i]=s.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return o.length>0&&c.push(o),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[s,o]of e.entries()){if("object"!=typeof o)continue;let e=o.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+s,c={};for(let e in o.attributes){let t=o.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(o.children){let a={};if(!o.skipSugar)for(let[s,p]of l.returnSugarInstructions().entries()){let l=o.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==o.children.length)continue}let d=deepClone(o.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let h=!1;o.doenetAttributes&&o.doenetAttributes.createdFromMacro&&(h=!0);let f=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+s,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:h});if(f.success){let t=f.newChildren,n=f.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let s=[...r,...i];if(s.length!==m||!s.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}f.parametersForChildrenSugar&&Object.assign(a,f.parametersForChildrenSugar),o.children=t||[],n&&(o.attributes||(o.attributes={}),Object.assign(o.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(o.children=o.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:o.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(o.attributes)for(let e in o.attributes){let t=o.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,attributesByTargetComponentName:s,indOffset:o=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],h=d.doenetAttributes;void 0===h&&(h=d.doenetAttributes={});let f=d.attributes;f||(f=d.attributes={}),h.createNameFromComponentType&&(e=h.createNameFromComponentType);let y,g=h.prescribedName,b=h.assignNames,v=h.target,N=h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||h.createUniqueName;(f.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let T=void 0!==g,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==g)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);g=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==b)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);b=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(g){if(!T&&!h.createdFromSugar){if(!/[a-zA-Z]/.test(g.substring(0,1)))throw Error(`Invalid component name: ${g}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(g))throw Error(`Invalid component name: ${g}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}h.prescribedName=g}else if(N){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+o+"|"+l,g=createUniqueName(e.toLowerCase(),t)}if(!b&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(b=d.originalDoenetAttributes.assignNames),b){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(h.assignNames=b,!h.createUniqueAssignNames){let t=flattenDeep(b);if(!h.fromCopyTarget&&!h.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(f.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||(p.componentCounts[e]=++A);let V="";for(let e=0;e<=c;e++)V+=t[e].namespace+"/";if(!g){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");g=d.originalName.substring(e+1)}g||(g="_"+e.toLowerCase()+A)}if(h.nameBecomesAssignNames){y&&(f.assignNewNamespaces={primitive:!0},delete f.newNamespace,y=!1),b=h.assignNames=[g],delete h.nameBecomesAssignNames;let e=a+"|createUniqueName|";h.createUniqueName=!0,delete h.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+o+"|"+l,g=createUniqueName("copy",e)}if(V+=g,d.componentName=V,g){if(g in p.namesUsed)throw Error(`Duplicate component name ${V}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[g]=!0}if(!y&&b)for(let t of flattenDeep(b)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${V}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=V+"|createUniqueName|assignNames|",a="";if(y)a=V+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,attributesByTargetComponentName:s});b=d.doenetAttributes.assignNames=i}if(renameMatchingTargetNames(d,s),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${V}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);h.target=v,h.targetComponentName=convertComponentTarget({relativeName:v,oldAbsoluteName:h.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}for(let e in f){let n=f[e];if(n.targetComponentNames)for(let e of n.targetComponentNames)e.absoluteName=convertComponentTarget({relativeName:e.relativeName,oldAbsoluteName:e.absoluteName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}if(d.children)if(y||f.assignNewNamespaces?.primitive){let e={};b&&flattenDeep(b).forEach((t=>e[t]=!0));let r=d.children;if(h.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:g,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}let a={namespace:g,componentCounts:{},namesUsed:e};if(h.haveNewNamespaceOnlyFromShadow){let e=!0,o=[...r];for(;o.length>0;){let r=[];for(let t of o){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}o.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}else{let e=d.children;if(h.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}}return e}function createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,attributesByTargetComponentName:a}){let i=[];for(let[s,o]of e.entries())if(Array.isArray(o)){let e=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:o,longNameIdBase:t+s+"_",namespace:n,oldNamespace:r,attributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+s);i.push(e),renameMatchingTargetNames({componentName:n+e,originalName:r+o},a,!0)}return i}function convertComponentTarget({relativeName:e,oldAbsoluteName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:s=0,originalNamesAreConsistent:o=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(o){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],attributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],attributesByTargetComponentName:c})}}let d=[],m=0;for(let h=0;h0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(g)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)g=[g];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||s?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,attributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!o})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,attributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}for(let t in a.attributes){let i=a.attributes[t];if(i.targetComponentNames)for(let t of i.targetComponentNames){let a=t.absoluteName;void 0!==a&&(a.substring(0,r)!==e&&(t.relativeName=a),n[a]||(n[a]=[]),n[a].push(t))}}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,attributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],attributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,attributesByTargetComponentName:n})}}}function renameMatchingTargetNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.relativeName?(n.relativeName=e.componentName,n.absoluteName=e.componentName):(n.target=e.componentName,n.targetComponentName=e.componentName);if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.relativeName?(r.relativeName=e.componentName+"/"+n,r.absoluteName=e.componentName+"/"+n):(r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n)}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let s of e){if(s.doenetAttributes&&s.doenetAttributes.target){let e=s.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),s=!0;break}r&&o.indBegin>t&&a.push({begin:t,end:o.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:o.indBegin,stopInd:o.indEnd,enclosingComponentName:o.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=o.indEnd+1}return!s&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:s=!1,copiesByTargetComponentName:o={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,h=e[d];if("object"==typeof h){if(h.originalName){if(s){if(l.push(h.originalName),h.originalDoenetAttributes&&h.originalDoenetAttributes.assignNames){let e;if(h.attributes.newNamespace?.primitive)e=h.originalName;else{let t=h.originalName.lastIndexOf("/");e=h.originalName.substring(0,t)}for(let t of h.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}h.attributes&&(h.attributes.alias&&c.push(h.attributes.alias.primitive),h.attributes.indexAlias&&c.push(h.attributes.indexAlias.primitive))}if(m=i+h.originalName+"|shadow",!h.originalNameFromSerializedComponent)if(n){let e={[h.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[h.originalName][0].firstLevelReplacement=!0),r&&(e[h.originalName][0].isPrimaryShadow=!0),h.state){let t=Object.keys(h.state);e[h.originalName].downstreamStateVariables=t,e[h.originalName].upstreamStateVariables=t}h.downstreamDependencies=e}else h.unlinkedCopySource=h.originalName}else m=i+h.componentType+"|shadowUnnamed";if("copy"===h.componentType&&s){let e=h.doenetAttributes.targetComponentName;if(e)c.includes(h.doenetAttributes.target)?h.doenetAttributes.targetComponentName=h.doenetAttributes.target:(void 0===o[e]&&(o[e]=[]),o[e].push(h));else if(!h.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}h.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&s)for(let e in o)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of o[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let s=n.allComponentClasses[t],o=s.createAttributesObject(),l={};for(let e in o)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=o[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else s.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:s,flags:o}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m&&n&&(1===n.length&&n[0].numberReplacementsToReplace===p?d=n[0].serializedReplacements:m=!1),m?d||(d=t):(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let h=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:s=!1,ignoreReplacementsOfEncounteredComposites:o=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],s=!1,o=!1;if(r)n=r.component,n.adaptedFrom&&(o=!0),e.activeChildren.includes(n)&&(s=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,s=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(o=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(o&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(s||a)&&p.push(n))}if(s||o){let e=[];for(let t of p){let n=c(t);o&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:s,ignoreReplacementsOfEncounteredComposites:o,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let s=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await s.initialize(),s.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let s,o=this.downstreamDependencies[e][t].__determine_dependencies;if(o){let t=!0;if(o.originalDownstreamVariableNames.length>0)for(let[r,a]of o.downstreamComponentNames.entries()){let s=this._components[a];for(let l of o.mappedDownstreamVariableNamesByComponent[r]){let r=s.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};s=await o.getValue()}else s={changes:{},value:{stateValues:{}}};if(0===Object.keys(s.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},s.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,s=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let o in n)if(o in a){if(!deepCompare(n[o],a[o].definition)){i=!0,a[o].deleteDependency();let l=n[o],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),s.push(u)}}else{i=!0;let a=n[o],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),s.push(l)}return{changedDependency:i,newlyCreatedDependencies:s}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:s,usedDefault:o}=await i[e].getValue();n[e]=t,Object.keys(s).length>0&&(r[e]=s),o&&(a[e]=o)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),s=i.valuesChanged[a][t];if(!s&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(s=upValuesChangedSub[n]);if(!s){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);s=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===s.changed?s.changed={arrayKeysChanged:{}}:!0===s.changed&&(s.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(s.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(s.changed.arraySizeChanged=!0),Object.assign(s.changed.arrayKeysChanged,n.arrayKeysChanged))):s.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:s,dependencyBlocked:o}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;s&&(u+="|"+s,o&&(u+="|"+o));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:s,dependency:o}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[s];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:s});let t=this.upstreamDependencies[a][s];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:s,dependency:o}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:s,dependency:o})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:s});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let o=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(o.determineDependencies)for(let t of o.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let o=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});o=Object.assign({},o);for(let l in o)for(let u of[...o[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),s){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:s}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:s=!0,numPreviouslyNeeded:o}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:s});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:s});if(!o.success){if(!a)return o;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:s});if(!o.success)return o}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:s});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===o||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],o=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&o.push(t))}}let l=!1;for(let e of i)if(o.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,s],!this.circularResolveBlockedCheckPassed[s]){this.circularResolveBlockedCheckPassed[s]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let s=this.dependencyHandler.upstreamDependencies[e];s||(s=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===s[e]&&(s[e]=[]),s[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let s,o={componentType:i.componentType};if(this.skipComponentNames||(o.componentName=t),s=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,s.length>0){o.stateValues={};let t={},n=!1;for(let[a,l]of s.entries()){let s=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?s:l;if(!this.variablesOptional||s in i.state){let a=i.state[s];if(!a.deferred)if(o.stateValues[u]=await a.value,this.valuesChanged[e][s].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][s]),this.valuesChanged[e][s]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(o)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],s=this.mappedDownstreamVariableNamesByComponent[0][0],o=this.useMappedVariableNames?s:i;if((!this.variablesOptional||s in r.state)&&!r.state[s].deferred){let e=r.state[s];if(await e.value,a.stateValues[o]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[o]=t}this.valuesChanged[0][s].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][o]=this.valuesChanged[0][s]),this.valuesChanged[0][s]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];s||(s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let o of t)if(!i.variableNames.includes(o)){i.variableNames.push(o);let t=s[o];t||(t=s[o]=[]),t.includes(this)||t.push(this);let l=a.state[o];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][o];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let s=e.allChildren[i].component;if("object"==typeof s){let e=this.gatherUnexpandedComposites(s);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let s of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:s,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:s}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:s,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let o=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(o.unexpandedCompositesNotReady.length>0||o.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...o.unexpandedCompositesReady,...o.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of o.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=o.newReplacements,this.compositesFound.push(...o.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function h({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let s of e){let e=s.componentName+"/"+t[0],o=r.dependencyHandler._components[e];if(o)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(o);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=h({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let f of t)"object"==typeof f?(this.replacementPrimitives.push(null),n.push(f.componentName),r.push(f.componentType)):this.replacementPrimitives.push(f);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class AttributeTargetComponentNamesDependency extends StateVariableDependency{static dependencyType="attributeTargetComponentNames";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.targetComponentNames:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributeTargetComponentNamesDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class DoenetMLDependency extends Dependency{static dependencyType="doenetML";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.displayOnlyChildren=this.definition.displayOnlyChildren}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler.core.requestComponentDoenetML(this.componentName,this.displayOnlyChildren),changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DoenetMLDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace","nPr","nCr"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace","nPr","nCr"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset","angle","circ","$","%"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if(!vectorOperators.includes(e.tree[0])||!e.tree.includes())return{desiredValue:e};let i,s=n+"Ast";if(void 0!==r&&(s+=`_${r}`),a[s])i=a[s].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),a&&vectorOperators.includes(a.tree[0])&&(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[s]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return[...vectorOperators,"list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\operatorname{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}const vectorOperators=["vector","altvector","tuple"];function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],s=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of s)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let o=r.inverseDefinition;o&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await o(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?rcrypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),s=[],o=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(s.push(i),o++,o>=n))return s}return s}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],s=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let s,o=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],s=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:s});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:s},o=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),o?l.push({value:n,originalIndex:c}):l.push(n),u++,u===s)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:s}){if(!(e>=0&&(void 0===r||e0&&("math"===i?o=o.add(n.multiply(me$3.fromAst(e))).expand().simplify():o+=n*e),"math"===i){if(a.some((e=>e&&e.equals(o))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-o)<=1e-14*Math.max(Math.abs(e),Math.abs(o)))))return null}else if(a.includes(o))return null;return"letters"===i&&(o=numberToLetters(o,s)),o}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],s=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};s.push(r.desiredVariant)}return{success:!0,desiredVariants:s}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let s=[...a];if(s.lengthe.toLowerCase())),o=[...new Set(o)];for(let e of o)if(!s.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!s.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];o=o?o.filter((e=>!l.includes(e))):[...s].filter((e=>!l.includes(e)));let u=o.map((e=>s.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),h=void 0!==r?.attributes.uniqueVariants,f=r?.attributes.uniqueVariants?.primitive;if(f||!h){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),f=!!d.success&&(f||d.numberOfVariants<=i)}let y=[],g=[],b=[];if(f)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(g.push(t),y.push(o[e]),b.push(m[e]));else y=o,g=u,b=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=f,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=s,e.variants.allPossibleVariantUniqueIndices=g,e.variants.allPossibleVariantSeeds=b,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:s,componentInfoObjects:o,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=o,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in s)this.state[e]=Object.assign({},s[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants),n.range&&(this.doenetMLrange=n.range),this.actions={copyDoenetMLToClipboard:this.copyDoenetMLToClipboard.bind(this)}}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e.doenetML={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({doenetML:{dependencyType:"doenetML"}}),definition({dependencyValues:e}){let t=e.doenetML;return t||(t=""),{setValue:{doenetML:t}}}},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,s]of t.additionalStateVariablesDefined.entries()){let o={};for(let e of a)e in t&&(o[e]=t[e]);o.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],o.additionalStateVariablesDefined[n]=e,r(o.additionalStateVariablesDefined);let l=s;"object"==typeof s&&(l=s.variableName,s=Object.assign({},s),delete s.variableName,Object.assign(o,s)),i[l]=o}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],s=i.createStateVariable;if(s&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[s]={createComponentOfType:e,public:!0}}else r[s]={}}let s=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in s){let o=s[n];if(o.isAlias)i[n]=o.targetVariableName;else if((!e||o.public)&&(!t||o.forRenderer)&&(o.public?r[n]={createComponentOfType:o.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},o.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===o.nDimensions?1:o.nDimensions,r[n].wrappingComponents=o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents():[],e=o.entryPrefixes?o.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:o.returnEntryDimensions?o.returnEntryDimensions(t):1,wrappingComponents:o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents(t):[]};o.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=o.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let s=this.state[t];if(void 0===s||!s.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=s.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,s=e.variants.descendantVariantComponents,o=[];if(s.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=s[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};o.push(i.desiredVariant),a=!0}else o.push({})}let l={index:t};return a&&(l.subvariants=o),{success:!0,desiredVariant:l}}async copyDoenetMLToClipboard({actionId:e}){let t=await this.stateValues.doenetML;t?this.coreFunctions.copyToClipboard(t,e):this.coreFunctions.resolveAction({actionId:e})}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveText:this.moveText.bind(this)})}static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}replacements=[];replacementsToWithhold=0;get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}const vectorAndListOperators=["list",...vectorOperators];class MathComponent extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],s=t.stringChildren.length;if(0===s)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!vectorOperators.includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let s=1;s=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(vectorAndListOperators.includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===s[0]){let e=s[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],s[2]&&i.push(s[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(vectorAndListOperators.includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null},setEssentialValue:{expressionWithCodes:null}}}let n,r,a,i,s="",o=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let s=r===t;if(!s)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){s=!0;break}s&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)s+=" "+c+" ";else{let t,r=e.codePre+o;o++,t="latex"===e.format?"\\operatorname{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):s+=t}if(t===r){let o=s.trimEnd(),c=!1;if(0===o.length)c=!0;else{let n=o[o.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),s+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===s)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+s)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+s)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\operatorname{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\operatorname{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,s]of e.mathChildrenModifiable.entries()){let o=e.codePre+i;!0===s.stateValues.canBeModified?(t.push(i),n.push(o)):(r.push(o),a[o]=i)}let i=e.codePre+"expr",s=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(s.foundLinear){let e={},r=s.template,o=new Set;for(let r in s.mappings){e[r]=s.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,o.add(Number(i))}}return o.has=o.has.bind(o),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:o}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let s=e[0],o=e.slice(1);if(vectorAndListOperators.includes(s)){let e={mappings:{},template:[s]},i=0;for(let s=0;s!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let s=t.mathChildren,o=t.stringChildren.length;if(1===s.length&&0===o)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===s.length){let f=[];return o>0?f.push({setDependency:"expressionWithCodes",desiredValue:l}):f.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:f}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let g of c)y[g]&&m.push(...y[g])}let h=await n.mathChildrenWithCanBeModified;for(let[b,v]of s.entries())if(n.mathChildrenMapped.has(b)&&h[b].stateValues.canBeModified){if(!m.includes(b)){let N=p[b],T={},C=!1,A=await n.constantChildIndices;for(let V in A){let x=A[V];T[V]=s[x].stateValues.value,C=!0}C&&(N=N.substitute(T)),N=N.simplify(),d.push({setDependency:"mathChildren",desiredValue:N,childIndex:b,variableIndex:0})}delete p[b]}if(o>0){let S=t.expressionWithCodes,w=t.codePre,E=w.length;function D(e){return"string"==typeof e&&e.substring(0,E)===w}function O(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(D):D(e)}if(vectorAndListOperators.includes(S.tree[0])&&!S.tree.slice(1).every(O)){let I=await n.inverseMaps;for(let R in p){let _=I[R];if(void 0!==_.mathChildInd)continue;let M=_.components;S=S.substitute_component(M,p[R])}d.push({setDependency:"expressionWithCodes",desiredValue:S})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveLabel:this.moveLabel.bind(this)})}static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createTargetComponentNames:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={returnDependencies:()=>({forObject:{dependencyType:"attributeTargetComponentNames",attributeName:"forObject"}}),definition({dependencyValues:e}){let t;return t=1===e.forObject?.length?e.forObject[0].absoluteName:null,{setValue:{forObjectComponentName:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function s(){let n=!1;if(t){if(1===i.length){let t=i[0],s=t.componentType;"copy"===s&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(s=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:s,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?s():i.push(n);for(let e of t.slice(1))s(),""!==e&&i.push(e)}return s(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],s=await a.childIndexByArrayKey,o=[];for(let l in e.maths){if(!n[l])continue;if(o.includes(l))continue;let u;if(void 0!==s[l][2]){let t=Number(l)-s[l][1],n=t+s[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let s=t;s<=n;s++)void 0!==e.maths[s]?i.desiredMaths[s]=convertValueToMathExpression(e.maths[s]):void 0===i.desiredMaths[s]&&(i.desiredMaths[s]=(await a.maths)[s]),r.push(i.desiredMaths[s].tree),o.push(s.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let s=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:s}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),s=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return!1;let o=a[0][3],l=a[0][4];if(o!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,s);if(!(me$3.math.min(d,s-d)<1e-10*s))return!1;let m=1;for(let e=1;e=n)return!0;let h=m/Math.max(p,n);return h*=(9+c/2)/10,h}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],s=e[4];if(i!==-1/0||s!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var o=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=s.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],s=n[2],o=l[s][2],u=l[s][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}const nonTupleVectorOperators=["vector","altvector"];function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:s="none",expand:o=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:h=!1}){let f=!1;if(e instanceof me$3.class){if(f=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(f=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,g=function(e,t=!1){e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree)));let n=s,r=o;return t&&(n="full",r=!0),"none"===n?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===n?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===n?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:n,expand:r})};y=f?i?function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=g(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let b=!1,v=!1;if(f){e=g(e,!i),t=g(t,!i);let s=e.tree[0],o=t.tree[0];if("periodic_set"===s||"periodic_set"===o){let n=e,a=t;"periodic_set"!==s&&(n=t,a=e);let i=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===i?{fraction_equal:1}:!1===i?{fraction_equal:0}:{fraction_equal:i}}if("list"===s)e=e.tree.slice(1),t="list"===o?t.tree.slice(1):[t.tree];else if("list"===o)t=t.tree.slice(1),e=[e.tree];else if(nonTupleVectorOperators.includes(s)){if(e=e.tree.slice(1),"interval"===o||"matrix"===o||"array"===o||"set"===o)return{fraction_equal:0};t=vectorOperators.includes(o)?t.tree.slice(1):[t.tree]}else if(nonTupleVectorOperators.includes(o)){if(t=t.tree.slice(1),"interval"===s||"matrix"===s||"array"===s||"set"===s)return{fraction_equal:0};e="tuple"===s?e.tree.slice(1):[e.tree]}else if("interval"===s){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===o||"set"===o)return{fraction_equal:0};if("tuple"===o){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===o){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==o)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===o){a=!0;let n=t.tree[2],r=n[1],i=n[2];if(t=t.tree[1].slice(1),"matrix"===s||"set"===s)return{fraction_equal:0};if("tuple"===s){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==i)return{fraction_equal:0};e=t}else{if("array"!==s)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==i)return{fraction_equal:0};e=t}}}else if("matrix"===s){if("matrix"!==o)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,b=!0}else{if("matrix"===o)return{fraction_equal:0};if("set"===s){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===o||"array"===o)return{fraction_equal:0};if("set"===o){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===o){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===s||"array"===s)return{fraction_equal:0};e=[e.tree]}else if("tuple"===s){if(e=e.tree.slice(1),"array"===o)return{fraction_equal:0};t="tuple"===o?t.tree.slice(1):[t.tree]}else if("tuple"===o){if(t=t.tree.slice(1),"array"===s)return{fraction_equal:0};e=[e.tree]}else if("array"===s)e=e.tree.slice(1),t="array"===o?t.tree.slice(1):[t.tree];else{if("array"!==o)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let N=e.length,T=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(N,T);for(let r=0;rArray(T+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(V+=r,A.add(e))}return N===T&&N===V?(C.fraction_equal=1,C):r?(C.fraction_equal=V/Math.max(N,T),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],s=e.slice(1);if("not"===i)return 1!==s.length?(console.warn("Invalid format for boolean condition"),r):0===a(s[0])?1:0;if("and"===i)return n.matchPartial?s.reduce(((e,t)=>e+a(t)),0)/s.length:s.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?s.reduce(((e,t)=>Math.max(a(t),e)),0):s.some((e=>1===a(e)))?1:0;let o=!1,l=!1,u=!1,c=!1;s.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?o=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(s[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(s[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===s[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(o||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(s=s.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(o||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(s=s.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(o)return console.warn("Invalid format for boolean condition"),r;let e=!1;return s=s.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?s.slice(1).every((e=>deepCompare(e,s[0])))?1:0:"ne"===i?2!==s.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(s[0],s[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=s[1].slice(1),s=s[0].slice(1));let m=!1,h=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(h)]:e},f=s.map((function(e){return me$3.fromAst(h(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=f[0];if(Number.isNaN(e.tree))return f.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=f.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return f.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:f[0],object2:f[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=f[0],t=f[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let g=f.map((e=>e.simplify().evaluate_to_constant()));if(g.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return g[0]"===i)return g[0]>g[1]?1:0;if("le"===i)return g[0]<=g[1]?1:0;if("ge"===i)return g[0]>=g[1]?1:0;for(let e=0;eg[e+1]))return 0}else if(!(g[e]>=g[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);if(["and","not","or"].includes(a))return[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))];if(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a){i=[i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))];let e=!1;if("int"===i[0]?e=!0:Array.isArray(i[0])&&("^"===i[0][0]?("int"===i[0][1]||Array.isArray(i[0][1])&&"_"===i[0][1][0]&&"int"===i[0][1][1])&&(e=!0):"_"===i[0][0]&&"int"===i[0][1]&&(e=!0)),e){i=me$3.fromAst([a,...i]).tree.slice(1);let e=i[1];if(Array.isArray(e)&&"*"===e[0]){let t=[];for(let n=0;nsplitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s={},o={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:s,textListChildrenByCode:o,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"}))r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})){let t=s.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(s.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"}))r.push(...s.stateValues.numbers),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN));else{let t=s.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN))}let s=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(s.stateValues.value)),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})?(r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})?(r.push(...s.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN))):(r.push(...s.stateValues.maths),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN)));let s=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,s=!1,o=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?s=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?o=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||s&&n===t||o&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let s=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let s=[];for(let t=0;tNaN;let l=e-1;t[0][o];let u,c,p=t[l][o],d=n.map((e=>e[o]));return i&&(u=s[o]),r&&(c=a[o]),function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:NaN;if(e>=l)return r?(e-=l,(c[2]*e+c[1])*e+c[0]):e===l?p:NaN;let t=Math.floor(e);e-=t;let n=d[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,s=1/0,o=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?o=!e.tree[2][1]:i=-1/0,s=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(s)?l=!e.tree[2][2]:s=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=s)||o&&n===i||l&&n===s)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let h=Math.max(0,m);n-=e[h];let f=t[h];return((f[3]*n+f[2])*n+f[1])*n+f[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let s=n.map((e=>e.subscripts_to_strings().tree)),o=s.length;return o>3||!s.every((e=>e===r))||s.includes("_")?e=>0:0===o||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===o?(3*e[3]*n+2*e[2])*n+e[1]:2===o?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===o?(3*a[3]*n+2*a[2])*n+a[1]:2===o?6*a[3]*n+2*a[2]:6*a[3]}for(var r,s=0,l=e.length-1;s<=l;){r=Math.floor(.5*(s+l));let a=e[r];if(an))return 1===o?t[r][1]:2===o?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===o?(3*c[3]*n+2*c[2])*n+c[1]:2===o?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$1 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],s=null,o=e[r].throughSlopes;null!==o&&(s=o.stateValues["math"+a],void 0===s&&(s=null)),n[r]={x:i[0],y:i[1],slope:s}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}:{};return{setValue:{fDefinitions:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.fDefinitions[r];return{setValue:{fDefinitions:t}}}if(e.numericalfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}},t.fDefinition={isAlias:!0,targetVariableName:"fDefinition1"},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]+r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]-r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,s=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(s=t.slope.evaluate_to_constant(),Number.isFinite(s)||(console.warn("Ignoring non-numerical slope"),s=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:s})}else n.push({type:e,x:a,y:i,slope:s});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,s=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:o});l=n.type,i=n.x,o=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let h=p[p.length-1];if("maximum"===h.type){let e={type:"point",x:h.x+u,y:h.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===h.type){let e={type:"point",x:h.x+u,y:h.y+c,slope:2*c/u};p.push(e)}else if("point"===h.type)if(1===p.length){let e={type:"point",x:h.x+u,y:h.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-h.y)/(e.x-h.x);if("maximum"===e.type||"minimum"===e.type)null===h.slope&&(h.slope=2*t);else{2===p.length?null===h.slope&&(h.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:p[p.length-3],nextPoint:h})),null===h.slope&&(h.slope=2*(e.y-h.y)/(e.x-h.x)-e.slope));let n={x:h.x+u,y:h.y+u*h.slope,slope:h.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("point"===n||"point"===r){let o="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(o="minimum"),"minimum"===o?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t})}return null!==e.y&&e.ys-c){let n,a,o=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(s,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=s-c),p.push({type:a,x:o,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],s=[i-c,t+c],o=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:o[e],value:s[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=s[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===s?i:"minimum"===o.type?Math.min(i,s):Math.min(i,s-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,h=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===h.success?(l="maximum",n=h.point.y,r.splice(h.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===s?i-c:"minimum"===o.type?Math.min(i-c,s):Math.min(i,s)-c;else if(t>i-c){let n,i,s=(e+a)/2,o=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),o=0):(i="point",n=t+c),p.push({type:i,x:s,y:n,slope:o})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...s]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:r,arraySize:a}){if(e.operatorBasedOnFormula){let t={};for(let n of r)t[n]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:n};return{setValue:{fDefinitions:t}}}if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},s=!1,o=!1;void 0===t?(i.location=!0,o=!0):(a.location=t,s=!0),void 0===r?(i.value=!0,o=!0):(a.value=r,s=!0);let l={};return s&&(l.setValue=a),o&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,s]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(s)?"location":"value":"x"+(Number(s)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"ol",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,s=e.chunkSize,o=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*s,p=me$3.math.dopri(c,c+s,r,l,o,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+s)){t.maxPossibleTime=d;let e="For chunksize "+s+" and tolerance "+o+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this),mouseDownOnPolyline:this.mouseDownOnPolyline.bind(this)})}static componentType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.verticesDraggable={createComponentOfType:"boolean"},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.verticesDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({verticesDraggableAttr:{dependencyType:"attributeComponent",attributeName:"verticesDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.verticesDraggableAttr?{setValue:{verticesDraggable:e.verticesDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{verticesDraggable:{defaultValue:e.draggable}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].vertices;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){if(1===Object.keys(e).length){if(!await this.stateValues.verticesDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPolyline({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,s]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let s,o,l;try{s=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],o=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(o[0]);l=[o[0],t]}else l=[o[1],o[1]];Math.pow(s[0]-l[0],2)+Math.pow(s[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this),mouseDownOnPoint:this.mouseDownOnPoint.bind(this)})}static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&vectorOperators.includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},s=!1;if(null!==e.coords?(s=!0,r=e.coords.stateValues.value):e.coordsShadow&&(s=!0,r=e.coordsShadow),s){let e=r.tree;if(Array.isArray(e)&&vectorOperators.includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let o={};return Object.keys(a).length>0&&(o.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(o.useEssentialOrDefaultValue={unconstrainedXs:i}),o},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,s,o=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",s=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",s=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)o.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)s[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)o.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)o.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?o.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):o.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(s[1]):(s[0]="vector",e=me$3.fromAst(s));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),o.push(t)}return{success:!0,instructions:o}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&vectorOperators.includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPoint({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this),mouseDownOnLine:this.mouseDownOnLine.bind(this)})}static componentType="line";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let s=a[0],o=a[1],l=t*s,u=n*o,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/s,h=d/o,f={};return f.x1=(u*(u*m-l*h)-l*r)*s/c,f.x2=(l*(-u*m+l*h)-u*r)*o/c,void 0!==e.x3&&(f.x3=0),f}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLine({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let s=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),o=[];o=Array.isArray(s.tree)&&"+"===s.tree[0]?s.tree.slice(1):[s.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of o){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,s=0,o=0;if("string"==typeof e)e===a?t=1:e===i?s=1:o=e;else if("number"==typeof e)o=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],s=["-",e.coeffvar2.tree],o=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this),mouseDownOnCurve:this.mouseDownOnCurve.bind(this)})}static componentType="curve";static rendererType="curve";static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}if(0===a.length)return{success:!1};let o=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=o({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...s]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.domainForFunctions={returnDependencies:()=>({parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"}}),definition:({dependencyValues:e})=>({setValue:{domainForFunctions:[me$3.fromAst(["interval",["tuple",e.parMin,e.parMax],["tuple",!0,!0]])]}})},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].through;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let s=e[0],o=t.vectorControlDirections[s],l=[];"none"===o?l=[s-1,s,s+1]:"previous"===o?l=[s,s+1]:"next"===o&&(l=[s-1,s]);for(let e of l)e>=0&&eNumber(e))),s=r.map((e=>e+1)),o=s.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,s,o=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),s=i.map((e=>e+1)),o=s.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+o]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,s=e.controlPoints[r];s.tree&&(s=s.tree);let o=me$3.fromAst(["+",s,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:o})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,s=e[r].nextVector,o=[];for(let e=0;e<2;e++)o.push(initCubicPoly(t[e],a[e],3*i[e],-3*s[e]));n[r]=o}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],s=n[0],o=n[1],l=a*a+o*o,u=(o*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[s,n,0]],extrapolateBackwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],s=n[0]+n[1]+n[2]+n[3],o=n[1]+2*n[2]+3*n[3],l=a*a+o*o,u=(o*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[s,n,0]],extrapolateForwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0,entryPrefixes:["fDefinition"]}],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"fDefinitions"},domain:{stateVariableToShadow:"domainForFunctions"}}},returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType){let t={functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},n={},r={};return t.component=0,n[0]=returnBezierFunctions(t),r[0]=t,t={...t},t.component=1,n[1]=returnBezierFunctions(t),r[1]=t,{setValue:{fs:n,fDefinitions:r}}}let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,s,o]=n[0],[l,u,c,p]=n[1],d=3*(s*p-c*o),m=3*(r*p-u*o),h=r*c-u*s;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-h/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*h;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let s=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(s=!0)}i=s}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnCurve({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,s=e.parMin;return function({variables:o,scales:l}){let u,c,p,d,m=o.x1?.evaluate_to_constant(),h=o.x2?.evaluate_to_constant(),f=l[0],y=l[1];if(s!==-1/0){if(u=s,c=r(s),!Number.isFinite(c)){let e=.99999*s+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*s+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(h)){let e,t;if(n?(t=h,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(s-h),a=Math.abs(i-h)):(r=Math.abs(s-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),s=n?n.map((e=>e.evaluate_to_constant())):[2*o[0]-l[0],2*o[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};s=n.map((e=>e.evaluate_to_constant())),l=[2*o[0]-s[0],2*o[1]-s[1]]}let c=[];if("centripetal"===i){let n=u(s,o),r=u(o,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],s=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(s)&&s>0))return null;let o,l=`${n}${i}`;o="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(o).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let s=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))s.push(t(e));else s.push(t(i.tree));n.push({orbitalText:r,boxes:s})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class OrbitalDiagramInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.splice(s,1);let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"U");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"D");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length>0&&(n[a].boxes[s]=n[a].boxes[s].slice(0,-1));let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let s=t.type;s||(s=n.type),s?["number","letters","math","text","boolean"].includes(s)||(console.warn(`Invalid type ${s}, setting type to number`),s="number"):s="number";let o="letters"===s?"text":s;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:o})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:o})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+s))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,s=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:s}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,s=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let s={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(s.useEssentialOrDefaultValue={specifiedMargins:a}),s},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+s))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={valigns:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let s=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DisplayDoenetML extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="displayDoenetML";static rendererType="text";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({childrenDoenetML:{dependencyType:"doenetML",displayOnlyChildren:!0}}),definition:({dependencyValues:e})=>({setValue:{value:e.childrenDoenetML}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre,DisplayDoenetML:DisplayDoenetML});class Paginator extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={returnDependencies:()=>({paginator:{dependencyType:"attributeTargetComponentNames",attributeName:"paginator"}}),definition({dependencyValues:e}){let t;return t=1===e.paginator?.length?e.paginator[0].absoluteName:null,{setValue:{paginatorComponentName:t}}}},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:vectorOperators.includes(e)&&(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1===await n.numColumns&&Array.isArray(e)&&vectorOperators.includes(e[0])){let t=e.length-1;if(rt){let s=deepClone(e),o=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:Array.isArray(t[1])&&vectorOperators.includes(t[1][0])&&("^"===e&&"T"===t[2]||"prime"===e)&&(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,s=i[0];if(Array.isArray(i[1])&&vectorOperators.includes(i[1][0])&&("^"===s&&"T"===i[2]||"prime"===s)){let t=i[1].length-1;if(rt){let s=deepClone(i),o=(await n.accumulatedComponents)[0];o||(o=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if(vectorOperators.includes(e)){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&vectorOperators.includes(r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;eo&&(u=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,o+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else u-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,s=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;eo&&(c=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,o+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else c-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let s=await r(t),o=await r(i);deepCompare(o.tree,s.tree)||a.push({setDependency:"immediateValue",desiredValue:o,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,s]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,s]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,s=e.propName;if(e.isPlainMacro?s=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(s=t.allComponentClasses[a.componentType].variableForPlainCopy),s){n["propName"+r]={dependencyType:"value",value:s};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:s,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:s}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let o=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],s=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);s.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let h=await e.stateValues.effectivePropNameBySource;for(let t in d){if(h[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let f=[],y=[],g=[],b=0,v=0;for(let i in d){let o,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;o=Math.floor(t/n),i"string"!=typeof e)).length,b+=y[i],v+=g[i],f.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=g,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:f,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],h=await e.stateValues.link;h&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let f=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,g=(await e.stateValues.effectivePropNameBySource)[t];if(g){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:g,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let b=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,N=[await m.serialize({copyAll:!h,copyVariants:!h,sourceAttributesToIgnore:b,sourceAttributesToIgnoreRecursively:v})];h||void 0===N[0].state?.fixed||delete N[0].state.fixed,N=postProcessCopy({serializedComponents:N,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:h,unlinkExternalCopies:!h}),N.length>0&&delete N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:s,compositeCreatesNewNamespace:f,flags:c});Object.assign(t.attributes,n)}return N[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),N=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:N,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o,originalNamesAreConsistent:f&&!y}).serializedComponents,p&&1===N.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:N,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:o}),{serializedReplacements:N}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let s=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of s.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...s.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:s,publicCaseInsensitiveAliasSubstitutions:o}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let s=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:s.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await s({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await s({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let h=0,f=0,y=[],g=[],b=[],v=Math.max(c.length,r.numReplacementsBySource.length),N=!1;for(let t=0;t0){if(!N){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToDelete:e};m.push(t)}N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,g[t]=0,b.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||N;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){h+=r.numReplacementsBySource[t],f+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],g[t]=r.numNonStringReplacementsBySource[t];continue}let T=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:h,numNonStringReplacementsSoFar:f,uniqueIdentifiersUsed:T,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:o,flags:i}),A=C.propVariablesCopiedByReplacement,V=C.serializedReplacements,x=V.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToReplace:e,serializedReplacements:V,assignNamesOffset:f};m.push(n),N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(s=!1,i=!0):e.replacements[h+a].componentType!==V[a].componentType&&(i=!0)),0==a&&i&&s){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h+a,numberReplacementsToReplace:1,serializedReplacements:[V[a]],assignNamesOffset:f+n};m.push(e)}"string"!=typeof V[a]&&n++}}let S=V.filter((e=>"string"!=typeof e)).length;h+=x,f+=S,y[t]=x,g[t]=S,b[t]=A}let T=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=g,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=b;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return T&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:s,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:s,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,h=d.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:h,assignNamesOffset:r};return{numReplacements:h.length,numNonStringReplacements:h.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:f}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,h=t[n.componentName],f=l({stateVariables:[r],componentClass:h.constructor})[0];if(void 0===f||"__not_public"===f.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=h.state[f],g=await y.value,b=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,g;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=h.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,g=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,N=v.length,T=o;if(y.isArray)T=l.slice(0,l.length-N).reduce(((e,t)=>e*t),1);else if(0===g.length)T=0;else if(0===N)T=g.length;else if(N>=y.nDimensions)T=1;else if(N===y.nDimensions-1)T=r.length;else{T=flattenLevels(r,y.nDimensions-N-1).length}if(0===N){let o=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await o(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,o,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),f=t.shadowingInstructions.createComponentOfType;if(Array.isArray(f)&&(f=f[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=h.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){o={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=h.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),o[e]={stateVariableToShadow:n}}}if(b){let t={};if(r){let n=s.allComponentClasses[f].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,s={componentType:n[a].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:s}}}l.push({componentType:f,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:o}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=h.state[n],s=await a.value;a.isArray&&(s=s[a.keyToIndex[i]]),h.state[n].usedDefault||(t[e]=s)}let n=convertAttributesForComponentType({attributes:t,componentType:f,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=s.allComponentClasses[f];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let o=t.keyToIndex(i);Array.isArray(o)||(o=[o]);let c=await t.value;for(let e of o)c=c[e];let p={componentType:f,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await o(r,y.nDimensions),N=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),b&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,ignorePrimaryStateVariable:!0}]})}if(m+=N.length,c.push(...N),N.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(g[e])]:n[e]));let s={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(s.doenetAttributes=r),c.push(s)}else if(N>T)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(f);let t=getUniqueIdentifierFromBase(h.componentName+"|shadow|"+f,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(b){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=s.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[h.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await h.state[n].value;h.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=s.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:g},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:o}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:o}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToDelete:e};s.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let h=n.sourceNames[a],f=void 0===h||d.componentName!==h||m;if(!f)for(let t=0;te+t),0);g.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}s.push(g);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],g=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:o,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),b=g.propVariablesCopiedByReplacement,v=g.serializedReplacements,N=v.length;if(N!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:o};s.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==b[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:o+e};s.push(t)}o+=N,l[a]=N,u[a]=b}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:s}){if(!await e.stateValues.targetComponent)return{replacements:[]};let o=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:o}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let h=e.attributes.newNamespace?.primitive,f=(await e.stateValues.effectivePropNameByComponent)[n];if(f){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:f,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:s,compositeCreatesNewNamespace:h,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:h,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let f=r.collectedNames[t];if(void 0===f||l.componentName!==f||y){let l=0;void 0!==f&&(l=r.numReplacementsByCollected[t]);let h=l;y&&(h=0);let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:h,components:n,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let N=v.replacementInstruction;if(m[t]=N.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);N.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(N);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}),N=v.propVariablesCopiedByReplacement,T=v.serializedReplacements,C=T.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:T,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==N[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[T[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=N,m[t]=T.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=h.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:h}}}class Ref extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{navigateToTarget:this.navigateToTarget.bind(this)})}static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,s=null,o=e.uri.match(/[:&]cid=([^&^#]+)/i);return o&&(t=o[1]),o=e.uri.match(/[:&]doenetid=([^&^#]+)/i),o&&(n=o[1]),o=e.uri.match(/[:&]variant=([^&^#]+)/i),o&&(r=Number(o[1]),!Number.isInteger(r)&&r>=1&&(r=1)),o=e.uri.match(/[:&]edit=([^&^#]+)/i),o&&(i="true"===o[1].toLowerCase()),o=e.uri.match(/[:&]draft=([^&^#]+)/i),o&&(a="true"===o[1].toLowerCase()),o=e.uri.match(/(#.+)/i),o&&(s=o[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:s}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}async navigateToTarget({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.cid,n=await this.stateValues.doenetId,r=await this.stateValues.variantIndex,a=await this.stateValues.edit,i=await this.stateValues.hash,s=await this.stateValues.page,o=await this.stateValues.uri,l=await this.stateValues.targetName,u=this.componentOrAdaptedName;this.coreFunctions.navigateToTarget({cid:t,doenetId:n,variantIndex:r,edit:a,hash:i,page:s,uri:o,targetName:l,actionId:e,componentName:this.componentName,effectiveName:u})}}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this),mouseDownOnLineSegment:this.mouseDownOnLineSegment.bind(this)})}static componentType="lineSegment";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpointsDraggable={createComponentOfType:"boolean"},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.endpointsDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({endpointsDraggableAttr:{dependencyType:"attributeComponent",attributeName:"endpointsDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.endpointsDraggableAttr?{setValue:{endpointsDraggable:e.endpointsDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{endpointsDraggable:{defaultValue:e.draggable}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),s=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+s]?r[n]=e[n].endpointsAttr.stateValues["pointX"+s]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.endpoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+o]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoints:{dependencyType:"stateVariable",variableName:"endpoints"}}),definition({dependencyValues:e}){let t=0,n=e.endpoints[0],r=e.endpoints[1],a=!0;for(let i=0;ie+t*t),0));r=r.map((e=>e/o));let l=e.length.evaluate_to_constant();if(!Number.isFinite(l)||l<0)return{success:!1};let u=[],c=[],p=l/2;for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e}async moveLineSegment({point1coords:e,point2coords:t,transient:n,actionId:r}){if(void 0===e||void 0===t){if(!await this.stateValues.endpointsDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};return void 0!==e&&(a["0,0"]=me$3.fromAst(e[0]),a["0,1"]=me$3.fromAst(e[1])),void 0!==t&&(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{point1:e,point2:t}}})}async lineSegmentClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLineSegment({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Ray extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveRay:this.moveRay.bind(this),rayClicked:this.rayClicked.bind(this),mouseDownOnRay:this.mouseDownOnRay.bind(this)})}static componentType="ray";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoint={createComponentOfType:"point"},e.through={createComponentOfType:"point"},e.direction={createComponentOfType:"vector"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):s=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(s=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?s=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let s=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnRay({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{constructor(e){super(e),Object.assign(this.actions,{movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this),mouseDownOnPolygon:this.mouseDownOnPolygon.bind(this)})}static componentType="polygon";static representsClosedPath=!0;get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}get mouseDownOnPolygon(){return this.mouseDownOnPolyline}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),s=Number(t)+1+"_"+(Number(i)+1),o=e[a].vertices;null!==o&&o.stateValues["pointX"+s]?n[a]=o.stateValues["pointX"+s]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+o]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let s=Number(r),o=t[r].vertex0,l=t[r].vertex2,u=e.center[s].subtract(i[s]),c=o.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),s="2_"+(Number(a)+1);e="0"===r?i:"2"===r?s:"1"===r?"0"===a?s:i:"0"===a?i:s,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:s}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let o,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(o=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==o){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[o].specifiedWidth,desiredValue:e},{setDependency:s[o].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[l].specifiedHeight,desiredValue:e},{setDependency:s[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:s[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:s[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:s[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:s[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,s=await this.stateValues.vertices,o=s[i][0],l=s[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(o).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(o).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=o.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=o.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{constructor(e){super(e),Object.assign(this.actions,{moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this),mouseDownOnCircle:this.mouseDownOnCircle.bind(this)})}static componentType="circle";static rendererType="circle";static representsClosedPath=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],s=e.numericalThroughPoints[0][1],o=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&s===o)if(r===i&&s===l)t=[r,s],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&s===l||a===i&&o===l){let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[a,o]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+s*s,u=a*a+o*o,c=i*i+l*l,p=r*(o-l)-s*(a-i)+a*l-i*o,d=e*(l-o)+u*(s-l)+c*(o-s),m=e*(a-i)+u*(i-r)+c*(r-a),h=e*(i*o-a*l)+u*(r*l-i*s)+c*(a*s-r*o);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*h)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],s=Math.pow(n-r,2)+Math.pow(a-i,2),o=t*t;return t<0||4*o0)return{success:!0,instructions:s};if(0===t.nThroughPoints){for(let t in e.numericalCenter)s.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:s}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,s=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],s=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){s=!1;break}i.push(t)}if(s&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),s=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let o=Math.atan2(s-r,i-n),l={x1:n+t*Math.cos(o),x2:r+t*Math.sin(o)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],s=await this.stateValues.nThroughPoints,o=await this.stateValues.numericalPrescribedCenter;if((s<=1||null!==o)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),s>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;if(null!==s&&s.stateValues["pointX"+i]){let e=s.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],s=t[1],o=e.numericalThroughPoints[0],l=o[0];return n=(o[1]-s)/(l-i)**2,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return s===c?o==p?(r=-2*n*s,a=n*l+o):(i=!1,n=NaN,r=NaN,a=NaN):(r=(o-p-n*(l-d))/(s-c),a=o-n*l-r*s),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],h=m[0],f=m[1],y=h*h,g=l-y,b=d-y,v=s-h,N=c-h,T=o-f,C=p-f,A=g*N-b*v;if(0===A){let t,u,d,m=!1;s===c?o===p?s===h?o==f?t=1:m=!0:(t=2,u=h,d=f):m=!0:s===h?o===f?(t=2,u=c,d=p):m=!0:c===h&&p===f?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*s,a=n*s*s+o):(n=e.aShadow,r=(o-d-n*(l-u*u))/(s-u),a=o-n*l-r*s)}else n=(T*N-C*v)/A,r=(C*g-T*b)/A,a=o-r*s-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let s=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await s("a"),t=await s("b"),n=await s("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await s("a"),n=await s("b"),r=await s("c"),i=t.numericalThroughPoints[0][0],o=t.numericalThroughPoints[1][0];if(i===o){i=-n/(2*e);let t=r-n*n/(4*e),s=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&s.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:s}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[o,e*o*o+n*o+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await s("a"),r=await s("b"),i=await s("c"),o=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(o===l?o===u?c=1:(c=2,e=3):o===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[l,n*l*l+r*l+i],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{o=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let s=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*s*a,additionalDependencyValues:{c:i+s*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],s=t.x1?.evaluate_to_constant(),o=t.x2?.evaluate_to_constant();if(!Number.isFinite(s)||!Number.isFinite(o))return{};s/=a,o/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(s+u*o-u*c)/e*a,n.x2=(u*(s+u*o)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-o,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-s)/d,1e-14),h=m[0],f=e.f(h*a)/i,y=(s-h)**2+(o-f)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(s-n)**2+(o-r)**2;l0){const t=Math.sqrt(s/108),n=2*Math.sqrt(Math.cbrt(i*i/4+s/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const o=Math.sqrt(-s/108);return[Math.cbrt(-i/2+o)+Math.cbrt(-i/2-o)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let s=t.pointIndMap[e[0]];void 0!==s&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[s]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[s]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),s=e[n].direction;if(0===t[1])if("none"===s||"next"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}o&&("symmetric"===s?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===s||"previous"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length)if("both"===s){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===s?me$3.fromAst(-e):me$3.fromAst(e))}o&&("symmetric"===s?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let s=i.split(",").map((e=>Number(e))),o=s.map((e=>e+1)),l=n[i].direction;if(l)if(0===s[1]){if("none"!==l&&"next"!==l){let s=n[i].controlChild,u=!0;if(s&&1===s.length){s[0].stateValues["vectorX1_"+o[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===s[1]&&"none"!==l&&"previous"!==l){let s,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+o[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+o[2]]&&(c=!1)}s="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(s=s.evaluate_to_constant(),Number.isFinite(s)||(s=NaN),s=me$3.fromAst(s),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:s}):a[i]=s):r.push({setDependency:t[i].controlChild,desiredValue:s,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!s.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),s=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,s],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this),mouseDownOnVector:this.mouseDownOnVector.bind(this)})}static componentType="vector";static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.displayWithAngleBrackets={createComponentOfType:"boolean",createStateVariable:"displayWithAngleBrackets",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros","displayWithAngleBrackets"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let s=t[i].componentAttr;null===s?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=s.stateValues.value.simplify();break;default:let o=e.displacementShadow.tree;Array.isArray(o)&&vectorOperators.includes(o[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:s=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(s=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?s=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.magnitude={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=0,n=!0;for(let r=0;re/i));let s=e.magnitude.evaluate_to_constant();if(!Number.isFinite(s)||s<0)return{success:!1};let o=[];for(let e=0;e({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"},displayWithAngleBrackets:{dependencyType:"stateVariable",variableName:"displayWithAngleBrackets"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");if(t.length>1){t=[e.displayWithAngleBrackets?"altvector":"vector",...t]}else t=1===t.length?t[0]:"_";return{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.slice(1).map((e=>me$3.fromAst(e))):[e.displacementCoords],{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let s=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnVector({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.emphasizeRightAngle={createComponentOfType:"boolean",createStateVariable:"emphasizeRightAngle",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),s=t.stateValues.points[1][1].evaluate_to_constant(),o=Math.atan2(s-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(o)),"0,1":me$3.fromAst(n.x2+Math.sin(o)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=o+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),s=t.stateValues.points[0][1].evaluate_to_constant(),o=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];i=n.stateValues.points[0][0].evaluate_to_constant(),s=n.stateValues.points[0][1].evaluate_to_constant(),o=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),s=r["1,1"].evaluate_to_constant(),o=Math.atan2(a-s,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(o)),r["2,1"]=me$3.fromAst(s+Math.sin(o))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),s=t.stateValues.coeffvar2.evaluate_to_constant(),o=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(o)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*s-i*r;if(Math.abs(l)<1e-14)return Math.abs(o*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===s&&0===o?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(o*r-a*s)/l,c=(a*i-o*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$2=util$1.isObject,isArray$3=util$1.isArray,isRegex=util$1.isRegex,assign$1=util$1.assign,keys$1=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$1({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,s=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const o=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$2(u)||null===u)return i(u);if(isArray$3(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(s=!0,p=!0):i(e,"text")||i(e,"textList")?(o=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(h.push(!1),s=!0,c=!0):i(t,"textInput")?(h.push(!1),o=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(h.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,h.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(t.handGraded&&!m&&(p=!0),!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let f=[],y=[],g=[];if(0===h.filter((e=>!e)).length)f=e;else{if(!h[0]){let t=h.indexOf(!0);-1!==t&&(y=e.slice(0,t),e=e.slice(t),h=h.slice(t))}let t=h.indexOf(!1);-1===t?f=e:(f=e.slice(0,t),g=e.slice(t))}for(;"string"==typeof f[0]&&""===f[0].trim();)f=f.slice(1);let b,v,N=f.length;for(;"string"==typeof f[N-1]&&""===f[N-1].trim();)f=f.slice(0,N-1),N=f.length;if(t.type?(v=t.type,["math","text","boolean"].includes(v)||(console.warn(`Invalid type ${v}`),v="math")):v=s?"math":o?"text":l?"boolean":"math",0===f.length)b=[...y,...g];else{let e;e=f.length>1||n.isInheritedComponentType({inheritedComponentType:f[0].componentType,baseComponentType:"_composite"})&&!f[0].props?.componentType?[{componentType:v,children:f}]:f,b=[...y,{componentType:"award",children:e},...g]}if(p&&!c){b=[{componentType:v+"Input"},...b]}return{success:!0,newChildren:b}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag&&!e.handGraded:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!(e.haveAwardThatRequiresInput||e.handGraded)||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","formula","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):void 0!==e.stateValues.value?(n.push(e.stateValues.value),r.push(t)):e.stateValues.formula instanceof me$3.class?(n.push(e.stateValues.formula),r.push("math")):(n.push(""),r.push("text"))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[s,o]of a.entries())if(e>o||null===o){r.splice(s,0,t.componentName),r=r.slice(0,n),a.splice(s,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit;await this.stateValues.handGraded&&(n=0);let r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],s=await this.stateValues.inputChildrenWithValues;if(1===s.length){let e=s[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let o=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:o}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of o)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:o,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:o,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,s=!1,o=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?s=!0:i(t,"text")||i(t,"textList")?o=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=s?"math":o?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let s=await t.unionFromU,o=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,s=await t.functionSymbols,o=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:s,splitSymbols:o,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let s;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let o=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{s=o(e)}catch(e){s=me$3.fromAst("_")}return s}class Textinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0,fallBackToParentStateVariable:"expanded"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateBoolean:this.updateBoolean.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateSelectedIndices:this.updateSelectedIndices.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s=0,o=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=o+s;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,s+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,s=await e.stateValues.step,o=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:s,type:o,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:s,length:i,exclude:l,type:o,lowercase:await e.stateValues.lowercase}),p=o;"letters"===o&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let s=await e.stateValues.from,o=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(s)}else{let t=!1;"math"===u?s.equals(a.from)&&l.equals(a.step)||(t=!0):s===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,h=0,f=d;if(od&&(m=o-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,h+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,h+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(h=d,f=0),h>0)for(let t=f;t0){let t=[],a=e.attributes.newNamespace?.primitive,o={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(o[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:o,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let h={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(h)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=s,a.length=o,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,o),s.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:o,iterateNumber:r,componentInfoObjects:a,flags:i});s.push(...n.replacements),r=n.iterateNumber}return{replacements:s,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let s=n.lastReplacementParameters,o=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==s.sourcesNames.length)l=!1;else for(let e=0;e1&&(o=!0)}else o=!0;if(o){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(s),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let h=await e.stateValues.minNIterates,f=s.minNIterates,y=0,g=e.replacementsToWithhold;g||(g=0);let b=s.withheldSubstitutionChildNames,v=!1;if(hf){let t=h-f;if(g>0)if(g>=t){y=g-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=g,f+=g,y=0;if(t>0){let t=[];for(let n=f;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),Object.assign(this.actions,{changeValue:this.changeValue})}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:s}){let o=e;if(0===r.length){if(!Number.isFinite(o))return;let e=Math.round((o-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return o>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(o-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}class Pegboard extends GraphicalComponent{static componentType="pegboard";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0,forRenderer:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0,forRenderer:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0,forRenderer:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0,forRenderer:!0},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let s=t({variables:{[i]:e[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={returnDependencies:()=>({graphComponentName:{dependencyType:"attributeTargetComponentNames",attributeName:"baseOnGraph"}}),definition:({dependencyValues:e})=>1===e.graphComponentName?.length?{setValue:{graphComponentName:e.graphComponentName[0].absoluteName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,s={["x"+n]:t[i].x},o=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:s,scales:e.scales});r.constrained&&(s["x"+n]=convertValueToMathExpression(r.variables["x"+n]),o=!0)}r[i]=s["x"+n],a[i]=o}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,s={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:s,scales:t.scales});n.constrained&&(s["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:s["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let s={};for(let e in i.desiredConstraintResults)s[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:s}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:s}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:s}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x1:Math.max(s,Math.min(o,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x2:Math.max(s,Math.min(o,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(!Number.isFinite(s))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)n&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let s=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,s={};for(let e in t)s[e]=findFiniteNumericalValue(t[e]);for(let o of e.nearestPointFunctions){let e=o({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==s.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(s.x1-e.x1,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(s.x2-e.x2,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(s.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,s={},o={};for(let e in r)o[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==o.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((o.x1-e.x1)/t,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((o.x2-e.x2)/n,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(o.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:s}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,s={};for(let[o,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],s=r[1];if(2!==i.stateValues.nDimensions||2!==s.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let o=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=s.stateValues.numericalCoeffvar1,p=s.stateValues.numericalCoeffvar2,d=s.stateValues.numericalCoeff0;if(!(Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=o*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*o-u*c)>1e-14)return{replacements:[]};if(0===o&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}}let h=(d*l-u*p)/m,f=(u*c-d*o)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",h,f]),draggable:!1,fixed:!0}}],g=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:g,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,s=!0;if(i===e.replacements.length){s=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let s=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>s&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let s,o,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===s)return[];if(!s){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=s,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=s,[e]}}let o=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return o.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=s,o}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t} /** * @license * Copyright (c) 2022 Handsoncode. All rights reserved. diff --git a/src/Viewer/renderers/mathInput.jsx b/src/Viewer/renderers/mathInput.jsx index 2a9b170fcb..e997aba3f2 100644 --- a/src/Viewer/renderers/mathInput.jsx +++ b/src/Viewer/renderers/mathInput.jsx @@ -329,7 +329,7 @@ export default function MathInput(props) { latex={rendererValue.current} config={{ autoCommands: - 'alpha beta gamma delta epsilon zeta eta mu nu xi omega rho sigma tau phi chi psi omega iota kappa lambda Gamma Delta Xi Omega Sigma Phi Psi Omega Lambda sqrt pi Pi theta Theta integral infinity', + 'alpha beta gamma delta epsilon zeta eta mu nu xi omega rho sigma tau phi chi psi omega iota kappa lambda Gamma Delta Xi Omega Sigma Phi Psi Omega Lambda sqrt pi Pi theta Theta integral infinity forall exists', autoOperatorNames: 'arg deg det dim exp gcd hom ker lg lim ln log max min' + ' Pr' +