@numero-uno-jpn/rstats 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.ja.md +7 -7
  3. package/README.md +7 -7
  4. package/dist/chunks/{chunk-7PSGKKOP.js → chunk-3QTVXDUM.js} +2 -2
  5. package/dist/chunks/{chunk-A76XBA3D.js → chunk-4ILI2FSB.js} +1 -1
  6. package/dist/chunks/{chunk-RZIWVCHO.js → chunk-5OSQ76OO.js} +2 -2
  7. package/dist/chunks/{chunk-7T74KLE5.js → chunk-5SQFDLNG.js} +2 -2
  8. package/dist/chunks/{chunk-ACE64PMM.js → chunk-5XQZNKHZ.js} +2 -2
  9. package/dist/chunks/chunk-5YMP4WAJ.js +2 -0
  10. package/dist/chunks/{chunk-ZUESNU7W.js → chunk-735NNFAS.js} +2 -2
  11. package/dist/chunks/{chunk-WM33ADZV.js → chunk-7J4HW6VF.js} +2 -2
  12. package/dist/chunks/{chunk-6JRESWVF.js → chunk-BDJPSEA7.js} +2 -2
  13. package/dist/chunks/{chunk-7CPM3M6Q.js → chunk-GEJCBCMP.js} +2 -2
  14. package/dist/chunks/{chunk-SZ357HRC.js → chunk-H4CHJMFU.js} +1 -1
  15. package/dist/chunks/{chunk-Q4JF4QHS.js → chunk-IQOVOHZG.js} +2 -2
  16. package/dist/chunks/chunk-KO6QQPC6.js +2 -0
  17. package/dist/chunks/{chunk-FBDZ6B2G.js → chunk-LY2T6DA6.js} +2 -2
  18. package/dist/chunks/chunk-OLPTFKIZ.js +3 -0
  19. package/dist/chunks/{chunk-YTV3RFCA.js → chunk-SAZAEPZC.js} +1 -1
  20. package/dist/chunks/{chunk-DWNGNTS6.js → chunk-TYFGVCVQ.js} +2 -2
  21. package/dist/chunks/{chunk-XCAMWVNO.js → chunk-UWBYDIOH.js} +1 -1
  22. package/dist/chunks/{chunk-IGSR4GIF.js → chunk-UZHY5DWN.js} +2 -2
  23. package/dist/chunks/{chunk-NTETWLP3.js → chunk-VOIJKNL2.js} +1 -1
  24. package/dist/chunks/{chunk-IBJ7RI44.js → chunk-Z3C3G5XI.js} +2 -2
  25. package/dist/descriptive.js +2 -2
  26. package/dist/distributions/nchisq.js +123 -25
  27. package/dist/distributions/signrank.js +73 -20
  28. package/dist/distributions.js +2 -2
  29. package/dist/linalg.js +2 -2
  30. package/dist/mixed.js +4 -4
  31. package/dist/models/glm.js +4 -2
  32. package/dist/models/glmFamily.js +16 -4
  33. package/dist/models/lmer.d.ts +28 -5
  34. package/dist/models/lmer.js +129 -20
  35. package/dist/models/lmerAnova.d.ts +8 -3
  36. package/dist/models/lmerAnova.js +10 -4
  37. package/dist/models/lmerHypotheses.d.ts +4 -3
  38. package/dist/models/lmerHypotheses.js +9 -7
  39. package/dist/models/lmerTest.d.ts +13 -7
  40. package/dist/models/lmerTest.js +16 -11
  41. package/dist/models/mixedStructure.js +30 -14
  42. package/dist/numerics.js +2 -2
  43. package/dist/rstats.js +13 -13
  44. package/dist/special.js +2 -2
  45. package/dist/tests.js +7 -7
  46. package/package.json +1 -1
  47. package/dist/chunks/chunk-DCGBYO44.js +0 -2
  48. package/dist/chunks/chunk-SD7ML5PE.js +0 -2
  49. package/dist/chunks/chunk-YQLEXH2Y.js +0 -3
@@ -1,2 +1,2 @@
1
- /*! rStats.js 0.14.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
1
+ /*! rStats.js 0.15.1 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
2
  var q=2220446049250313e-31,b0=22250738585072014e-324,z=17976931348623157e292,v0=[.06667134430868814,.1494513491505806,.21908636251598204,.26926671930999635,.29552422471475287],f0=[.9956571630258081,.9739065285171717,.9301574913557082,.8650633666889845,.7808177265864169,.6794095682990244,.5627571346686047,.4333953941292472,.2943928627014602,.14887433898163122,0],I=[.011694638867371874,.032558162307964725,.054755896574351995,.07503967481091996,.0931254545836976,.10938715880229764,.12349197626206584,.13470921731147334,.14277593857706009,.14773910490133849,.1494455540029169];function h0(a,o,i,s,t){let r=Math.abs((a-o)*i);return t!==0&&r!==0&&(r=t*Math.min(1,Math.pow(200*r/t,1.5))),s>b0/(50*q)&&(r=Math.max(q*50*s,r)),r}function g0(a,o,i){let s=.5*(o+i),t=.5*(i-o),r=Math.abs(t),w=new Array(10),u=new Array(10),p=a(s),M=0,c=I[10]*p,b=Math.abs(c);for(let e=0;e<5;e++){let n=2*e+1,l=t*f0[n],h=a(s-l),v=a(s+l);w[n]=h,u[n]=v;let g=h+v;M+=v0[e]*g,c+=I[n]*g,b+=I[n]*(Math.abs(h)+Math.abs(v))}for(let e=0;e<5;e++){let n=2*e,l=t*f0[n],h=a(s-l),v=a(s+l);w[n]=h,u[n]=v;let g=h+v;c+=I[n]*g,b+=I[n]*(Math.abs(h)+Math.abs(v))}let A=c*.5,f=I[10]*Math.abs(p-A);for(let e=0;e<10;e++)f+=I[e]*(Math.abs(w[e]-A)+Math.abs(u[e]-A));return b*=r,f*=r,{result:c*t,abserr:h0(c,M,t,b,f),resabs:b,resasc:f}}var l0=[0,.1294849661688697,0,.27970539148927664,0,.3818300505051189,0,.4179591836734694],x0=[.9914553711208126,.9491079123427585,.8648644233597691,.7415311855993945,.5860872354676911,.4058451513773972,.20778495500789848,0],U=[.022935322010529224,.06309209262997856,.10479001032225019,.14065325971552592,.1690047266392679,.19035057806478542,.20443294007529889,.20948214108472782];function A0(a,o,i,s,t){let r=i>1?1:i,w=.5*(s+t),u=.5*(t-s),p=new Array(7),M=new Array(7),c=h=>{let v=o+r*(1-h)/h,g=a(v);return i===2&&(g+=a(-v)),g},b=c(w)/w/w,A=b*l0[7],f=b*U[7],e=Math.abs(f);for(let h=0;h<7;h++){let v=u*x0[h],g=w-v,W=w+v,m=c(g),x=c(W);m=m/g/g,x=x/W/W,p[h]=m,M[h]=x;let K=m+x;A+=l0[h]*K,f+=U[h]*K,e+=U[h]*(Math.abs(m)+Math.abs(x))}let n=f*.5,l=U[7]*Math.abs(b-n);for(let h=0;h<7;h++)l+=U[h]*(Math.abs(p[h]-n)+Math.abs(M[h]-n));return e*=u,l*=u,{result:f*u,abserr:h0(f,A,u,e,l),resabs:e,resasc:l}}function j0(a){let o=a.epstab,i=a.n;a.nres+=1;let s=z,t=o[a.n];if(a.n<2)return s=Math.max(s,5*q*Math.abs(t)),[t,s];let r=49;o[a.n+2]=o[a.n];let w=Math.trunc(a.n/2);o[a.n]=z;let u=a.n;for(let c=0;c<w;c++){let b=u-1,A=u-2,f=o[u+2],e=o[A],n=o[b],l=f,h=Math.abs(n),v=l-n,g=Math.abs(v),W=Math.max(Math.abs(l),h)*q,m=n-e,x=Math.abs(m),K=Math.max(h,Math.abs(e))*q;if(!(g>W||x>K))return t=f,s=g+x,s=Math.max(s,5*q*Math.abs(t)),[t,s];let k=o[u];o[u]=n;let j=n-k,F=Math.abs(j),_=Math.max(h,Math.abs(k))*q;if(F<=_||g<=W||x<=K){a.n=c+c;break}let L=1/j+1/v-1/m;if(!(Math.abs(L*n)>1e-4)){a.n=c+c;break}f=n+1/L,o[u]=f,u-=2;let X=g+Math.abs(f-l)+x;X>s||(s=X,t=f)}a.n===r&&(a.n=2*Math.trunc(r/2));let p=i%2;for(let c=0;c<=w;c++)o[2*c+p]=o[2*c+2+p];if(a.n!==i){let c=i-a.n;for(let b=0;b<=a.n;b++)o[b]=o[c],c++}let M=a.res3la;return a.nres<4?(M[a.nres-1]=t,s=z):(s=Math.abs(t-M[2])+Math.abs(t-M[1])+Math.abs(t-M[0]),M[0]=M[1],M[1]=M[2],M[2]=t),s=Math.max(s,5*q*Math.abs(t)),[t,s]}function y0(a,o,i,s,t,r){if(o<=2){t[0]=0,t[1]=1;let e=t[r];return[e,s[e],r]}let w=s[i];for(;r>0&&w>s[t[r-1]];)t[r]=t[r-1],r-=1;let u=o>Math.trunc(a/2)+2?a-o+2:o-1,p=s[o-1],M=u-1,c=r+1,b=c,A=!1;if(c<=M)for(b=c;b<=M;b++){if(w>=s[t[b]]){A=!0;break}t[b-1]=t[b]}if(!A)t[M]=i,t[u]=o-1;else{t[b-1]=i;let e=M;for(let n=b;n<=M&&!(p<s[t[e]]);n++)t[e+1]=t[e],e--;p<s[t[e]]?t[e+1]=o-1:t[b]=o-1}let f=t[r];return[f,s[f],r]}function M0(a,o,i,s,t,r,w,u){let p=new Float64Array(r+1),M=new Float64Array(r+1),c=new Float64Array(r+1),b=new Float64Array(r+1),A=new Int32Array(r+1),f=0,e=0,n=0,l=0;if(p[0]=o,M[0]=i,s<=0&&t<Math.max(50*q,5e-29))return{result:0,abserr:0,neval:0,ier:6,last:0};let h=a(o,i);n=h.result,l=h.abserr;let v=h.resabs,g=h.resasc,W=Math.abs(n),m=Math.max(s,t*W);if(e=1,c[0]=n,b[0]=l,A[0]=0,l<=100*q*v&&l>m&&(f=2),r===1&&(f=1),f!==0||l<=m&&l!==g||l===0)return{result:n,abserr:l,neval:u(e),ier:f,last:e};let x={epstab:new Float64Array(52),res3la:new Float64Array(3),n:1,nres:0};x.epstab[0]=n;let K=l,k=0,j=n,F=l;l=z;let _=0,L=0,E=!1,X=!1,B=0,t0=0,R=0,s0=0,C=0,O=0,D=0,e0=0,u0=W>=(1-50*q)*v?1:-1,a0=!1,y=1;for(y=1;y<r;y++){e=y+1;let d=p[k],H=.5*(p[k]+M[k]),J=H,S=M[k],i0=K,T=a(d,H),V=a(J,S),Y=T.result,N=T.abserr,k0=T.resasc,Z=V.result,P=V.abserr,w0=V.resasc,$=Y+Z,Q=N+P;if(F=F+Q-K,j=j+$-c[k],k0!==N&&w0!==P&&(Math.abs(c[k]-$)>1e-5*Math.abs($)||Q<.99*K||(E?R++:t0++),y>9&&Q>K&&s0++),c[k]=Y,c[y]=Z,m=Math.max(s,t*Math.abs(j)),(t0+R>=10||s0>=20)&&(f=2),R>=5&&(B=3),e===r&&(f=1),Math.max(Math.abs(d),Math.abs(S))<=(1+100*q)*(Math.abs(J)+1e3*b0)&&(f=4),P>N?(p[k]=J,p[y]=d,M[y]=H,c[k]=Z,c[y]=Y,b[k]=P,b[y]=N):(p[y]=J,M[k]=H,M[y]=S,b[k]=N,b[y]=P),[k,K,_]=y0(r,e,k,b,A,_),F<=m){a0=!0;break}if(f!==0)break;if(y===1){C=w,O=F,D=m,x.epstab[1]=j;continue}if(X)continue;if(O-=i0,Math.abs(H-d)>C&&(O+=Q),!E){if(Math.abs(M[k]-p[k])>C)continue;E=!0,_=1}if(!(B===3||O<=D)){let p0=e>2+Math.trunc(r/2)?r+3-e:e,o0=!1;for(let c0=_;c0<p0;c0++){if(k=A[_],K=b[k],Math.abs(M[k]-p[k])>C){o0=!0;break}_++}if(o0)continue}x.n+=1,x.epstab[x.n]=j;let[n0,r0]=j0(x);if(L+=1,L>5&&l<.001*F&&(f=5),r0<l&&(L=0,l=r0,n=n0,e0=O,D=Math.max(s,t*Math.abs(n0)),l<=D)||(x.n===0&&(X=!0),f===5))break;k=A[0],K=b[k],_=0,E=!1,C*=.5,O=F}let G;if(a0||l===z?G=115:f+B===0?G=110:(B===3&&(l+=e0),f===0&&(f=3),n!==0&&j!==0?G=105:l>F?G=115:j===0?G=130:G=110),G===105&&(G=l/Math.abs(n)>F/Math.abs(j)?115:110),G===110)u0===-1&&Math.max(Math.abs(n),Math.abs(j))<=v*.01||(.01>n/j||n/j>100||F>Math.abs(j))&&(f=6);else if(G===115){n=0;for(let d=0;d<=y;d++)n+=c[d];l=F}return f>2&&(f-=1),{result:n,abserr:l,neval:u(e),ier:f,last:e}}function m0(a,o,i,s,t,r){return M0((w,u)=>g0(a,w,u),o,i,s,t,r,Math.abs(i-o)*.375,w=>42*w-21)}function K0(a,o,i,s,t,r){let w=i===2?0:o;return M0((u,p)=>A0(a,w,i,u,p),0,1,s,t,r,.375,u=>(30*u-15)*(i===2?2:1))}export{m0 as a,K0 as b};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 0.14.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{c as re}from"./chunk-7PSGKKOP.js";import{e as ne,h as se,j as X,k as I,m as oe}from"./chunk-WM33ADZV.js";import{a as ae,g as ie}from"./chunk-ZUESNU7W.js";import{k as B}from"./chunk-DWNGNTS6.js";import{b as ce,c as S}from"./chunk-RZIWVCHO.js";import{b as Y}from"./chunk-SZ357HRC.js";import{g as D,h as G}from"./chunk-IGSR4GIF.js";import{b as ee,c as te,d as V,f as q,g as C,i as W}from"./chunk-XCAMWVNO.js";function j(e){if(e.kind==="factor")return ce(e);let t=[...new Set(e.values)].sort((s,o)=>s-o),n=[...new Set(t.map(Y))],r=new Map(n.map((s,o)=>[s,o]));return{levels:n,codes:e.values.map(s=>r.get(Y(s)))}}function A(e,t){if(e.kind!=="numeric")throw new TypeError(`'${t}' must be a numeric column`);return e.values}function R(e,t){let n=ae(e),r=ie(n,Object.keys(t));return{terms:r,rhsVariables:r.variables.slice(r.response===0?1:0)}}function fe(e){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");return t<0?void 0:{lhs:e.slice(0,t).trim(),rhs:e.slice(t+1)}}var Ae=/^Pair\s*\(\s*([A-Za-z.][A-Za-z0-9._]*)\s*,\s*([A-Za-z.][A-Za-z0-9._]*)\s*\)$/,F="'formula' missing or incorrect",le=(e,t)=>t.length===0&&e.terms.length===0&&e.intercept;function Ve(e,t,n){let r=fe(e),s=r===void 0?null:Ae.exec(r.lhs);if(s!==null){let{terms:m,rhsVariables:p}=R(`~${r.rhs}`,t);if(!n||!le(m,p))throw new Error(F);let w=S(t,[s[1],s[2]]);return{kind:"paired",x:A(w.variables[0],s[1]),y:A(w.variables[1],s[2])}}let{terms:o,rhsVariables:c}=R(e,t);if(o.response<0)throw new Error(F);let i=o.variables[0];if(n&&le(o,c))return{kind:"one",x:A(S(t,[i]).variables[0],i)};if(c.length!==1||o.terms.length!==1)throw new Error(F);let a=S(t,[i,c[0]],{dropUnusedLevels:!0}),l=A(a.variables[0],i),u=j(a.variables[1]);if(u.levels.length!==2)throw new Error("grouping factor must have exactly 2 levels");return{kind:"two",x:l.filter((m,p)=>u.codes[p]===0),y:l.filter((m,p)=>u.codes[p]===1),levels:[u.levels[0],u.levels[1]]}}function Ie(e,t){let n=Ve(e,t,!1);if(n.kind!=="two")throw new Error(F);return n}function je(e,t){let{terms:n,rhsVariables:r}=R(e,t);if(n.response<0)throw new Error(F);if(r.length!==1)throw new Error("'formula' should be of the form response ~ group");let s=n.variables[0],o=S(t,[s,r[0]],{dropUnusedLevels:!0});return{values:A(o.variables[0],s),group:j(o.variables[1])}}function ze(e,t){let n=t.levels.map(()=>[]);return e.forEach((r,s)=>n[t.codes[s]].push(r)),n}function Ue(e,t){let{terms:n,rhsVariables:r}=R(e,t);if(n.response<0||r.length===0)throw new Error(F);let s=n.variables[0],o=S(t,[s,...r],{dropUnusedLevels:!0}),c=o.variables.slice(1).map(j),i=o.rows.map((a,l)=>{let u=0,m=1;for(let p of c)u+=p.codes[l]*m,m*=p.levels.length;return u});return{values:A(o.variables[0],s),groups:i}}var ue="incorrect specification for 'formula'";function Ze(e,t){let n=fe(e),r=n?.rhs.split("|");if(n===void 0||n.lhs===""||r.length!==2)throw new Error(ue);let s=y=>{let{terms:E,rhsVariables:h}=R(y,t);if(h.length!==1||E.terms.length!==1)throw new Error(ue);return h[0]},{terms:o}=R(`${n.lhs} ~ 1`,t),c=o.variables[0],i=s(`~${r[0]}`),a=s(`~${r[1]}`),l=S(t,[c,i,a],{dropUnusedLevels:!0}),u=A(l.variables[0],c),m=j(l.variables[1]),p=j(l.variables[2]),w=p.levels.map(()=>m.levels.map(()=>NaN)),N=p.levels.map(()=>m.levels.map(()=>0));if(u.forEach((y,E)=>{let h=p.codes[E],g=m.codes[E];N[h][g]++,w[h][g]=y}),N.some(y=>y.some(E=>E!==1)))throw new Error("not an unreplicated complete block design");return w}function me(e,t){let{terms:n,rhsVariables:r}=R(e,t);if(n.response>=0)throw new Error("'formula' missing or invalid");if(r.length!==2)throw new Error("invalid formula");let s=S(t,r);return{x:A(s.variables[0],r[0]),y:A(s.variables[1],r[1])}}function he(e){if(e===void 0)return"two.sided";let n=["two.sided","less","greater"].filter(r=>r.startsWith(e));if(e.length===0||n.length!==1)throw new RangeError(`invalid alternative "${e}" (expected "two.sided", "less" or "greater")`);return n[0]}function pe(e){if(!(Number.isFinite(e)&&e>=0&&e<=1))throw new RangeError("confLevel must be a number between 0 and 1")}function Ge(e){if(!(Number.isFinite(e)&&e>0&&e<1))throw new RangeError("'conf.level' must be a single number between 0 and 1")}var Se=["pearson","kendall","spearman"];function Te(e){if(e===void 0)return"pearson";let t=Se.filter(n=>n.startsWith(e));if(e.length===0||t.length!==1)throw new RangeError(`invalid method "${e}"`);return t[0]}function de(e){if(!(e[0]>0))return[Math.sqrt(e[0]),0];let t=Math.sqrt(e[0]),n=q(e,te(t,t));return ee(t,n[0]/(2*t))}function we(e){let t=ne(e);if(!Number.isFinite(t[0]))return;let n=e.map(o=>q([o,0],t)),r=0;for(let o of n)r=Math.max(r,Math.abs(o[0]));if(r===0)return n;let s=2**-Math.max(-1022,Math.floor(Math.log2(r)));return n.map(o=>[o[0]*s,o[1]*s])}function H(e,t){let n=e.length;if(n<2)return[NaN,0];let r=we(e),s=we(t);if(r===void 0||s===void 0)return[NaN,0];let o=[0,0],c=[0,0],i=[0,0];for(let l=0;l<n;l++)o=V(o,C(r[l],s[l])),c=V(c,C(r[l],r[l])),i=V(i,C(s[l],s[l]));if(c[0]===0||i[0]===0)return[NaN,0];let a=W(o,C(de(c),de(i)));return a[0]>=1?[1,0]:a[0]<=-1?[-1,0]:a}function ge(e,t){let n=C(q([1,0],e),V([1,0],e));return Math.sqrt(t)*e[0]/Math.sqrt(n[0])}function De(e){return Math.abs(e[0])<.5?Math.atanh(e[0]):.5*Math.log(V([1,0],e)[0]/q([1,0],e)[0])}function Ne(e,t,n){return n==="less"?B(e,t,!0,!1):n==="greater"?B(e,t,!1,!1):2*Math.min(B(e,t,!0,!1),B(e,t,!1,!1))}function Re(e,t){return t==="less"?D(e):t==="greater"?D(e,{lowerTail:!1}):2*Math.min(D(e),D(e,{lowerTail:!1}))}function K(e,t){let n=e.length,r=0;for(let u=0;u<n;u++){let m=e[u],p=t[u];for(let w=u+1;w<n;w++){let N=(e[w]>m?1:0)-(e[w]<m?1:0),y=(t[w]>p?1:0)-(t[w]<p?1:0);r+=N*y}}let s=I(e),o=I(t),c=n*(n-1)/2,i=s.reduce((u,m)=>u+m*(m-1)/2,0),a=o.reduce((u,m)=>u+m*(m-1)/2,0),l=n<2||i===c||a===c?NaN:i===0&&a===0?r/c:r/Math.sqrt((c-i)*(c-a));return{s:r,tau:l,ties:s.length>0||o.length>0,tx:s,ty:o}}function be(e,t){let n=e*(e-1)/2;if(t<0)return 0;if(t>=n)return 1;let r=new Float64Array(t+1);r[0]=1;for(let o=2;o<=e;o++){let c=new Float64Array(t+1),i=0;for(let l=0;l<=t;l++)i+=r[l],c[l]=i;let a=new Float64Array(t+1);for(let l=0;l<=t;l++)a[l]=(c[l]-(l>=o?c[l-o]:0))/o;r=a}let s=0;for(let o=t;o>=0;o--)s+=r[o];return Math.min(1,s)}var ve=new Map;function Le(e){let t=ve.get(e);if(t!==void 0)return t;let n=e*(e*e-1)/3,r=1<<e,s=new Array(r);s[0]=new Float64Array(n+1),s[0][0]=1;let o=i=>{let a=0;for(;i;i&=i-1)a++;return a};for(let i=0;i<r;i++){let a=s[i];if(a===void 0)continue;let l=o(i);for(let u=0;u<e;u++){if(i&1<<u)continue;let m=(u-l)**2,p=i|1<<u,w=s[p]??=new Float64Array(n+1);for(let N=0;N+m<=n;N++)a[N]&&(w[N+m]+=a[N])}i!==r-1&&(s[i]=void 0)}let c=s[r-1];return ve.set(e,c),c}var x=[.2274,.2531,.1745,.0758,.1033,.3932,.0879,.0151,.0072,.0831,.0131,46e-5];function ye(e,t,n){let r=t;r%2!==0&&(r+=1);let s=1/e,o=(6*(r-1)*s/(e*e-1)-1)*Math.sqrt(1/s-1),c=o*o,a=o*s*(x[0]+s*(x[1]+x[2]*s)+c*(-x[3]+s*(x[4]+x[5]*s)-c*s*(x[6]+x[7]*s-c*(x[8]-x[9]*s+c*s*(x[10]-x[11]*c)))))/Math.exp(c/2),l=n?D(o)-a:a+D(o,{lowerTail:!1});return Math.min(1,Math.max(0,l))}function Me(e,t,n){let r=e*(e*e-1)/3;if(e<=9){let s=Le(e),o=1;for(let i=2;i<=e;i++)o*=i;let c=0;if(n)for(let i=Math.min(t,r);i>=0;i--)c+=s[i];else for(let i=r;i>=Math.max(t,0);i--)c+=s[i];return c/o}return n?t+1>r?1:t+1<=0?0:ye(e,t+1,!0):t<=0?1:t>r?0:ye(e,t,!1)}function _e(e,t,n={}){if(typeof e=="string"){let r=me(e,t);return _e(r.x,r.y,n)}return Ce(e,t,n)}function Ce(e,t,n){if(e.length!==t.length)throw new TypeError("x and y must have the same length");let r=he(n.alternative),s=Te(n.method),o=n.continuity??!1,[c,i]=oe(Array.from(e),Array.from(t)),a=c.length;if(s==="pearson"){let f=n.confLevel??.95;if(pe(f),a<3)throw new Error("not enough finite observations");let d=H(c,i),k=a-2,b=Number.isNaN(d[0])?NaN:ge(d,k),M={method:"Pearson's product-moment correlation",alternative:r,statistic:b,statisticName:"t",parameter:k,parameterName:"df",pValue:Ne(b,k,r),estimate:d[0],estimateNames:"cor",nullValue:0,nullValueName:"correlation"};if(a>3){let z=De(d),L=1/Math.sqrt(a-3),_=T=>Math.tanh(z+T),$;if(r==="less")$=[-1,_(L*G(f))];else if(r==="greater")$=[_(-L*G(f)),1];else{let T=L*G((1+f)/2);$=[_(-T),_(T)]}M.confInt=$,M.confLevel=f}return M}if(a<2)throw new Error("not enough finite observations");if(s==="kendall"){let f=K(c,i),d={method:"Kendall's rank correlation tau",alternative:r,estimate:f.tau,estimateNames:"tau",nullValue:0,nullValueName:"tau"};if(Number.isNaN(f.tau))return{...d,statistic:NaN,statisticName:"T",pValue:NaN};if((n.exact??a<50)&&!f.ties){let v=a*(a-1)/2,P=(f.s+v)/2,U=be(a,P),Z=be(a,v-P),Ee=r==="less"?U:r==="greater"?Z:Math.min(1,2*Math.min(U,Z));return{...d,statistic:P,statisticName:"T",pValue:Ee}}let b=(v,P)=>P.reduce((U,Z)=>U+v(Z),0),M=v=>v*(v-1),z=v=>v*(v-1)*(v-2),L=v=>v*(v-1)*(2*v+5),_=(a*(a-1)*(2*a+5)-b(L,f.tx)-b(L,f.ty))/18+b(z,f.tx)*b(z,f.ty)/(9*a*(a-1)*(a-2))+b(M,f.tx)*b(M,f.ty)/(2*a*(a-1)),T=(o?Math.sign(f.s)*(Math.abs(f.s)-1):f.s)/Math.sqrt(_);return{...d,statistic:T,statisticName:"z",pValue:Re(T,r)}}let l=X(c),u=X(i),m=H(l,u),p=a*a*a-a,w=p*(1-m[0])/6,N={method:"Spearman's rank correlation rho",alternative:r,statistic:w,statisticName:"S",estimate:m[0],estimateNames:"rho",nullValue:0,nullValueName:"rho"};if(Number.isNaN(m[0]))return{...N,pValue:NaN};let y=I(c).length>0||I(i).length>0;if((n.exact??a<=1290)&&!y&&a<=1290){let f=Math.round(w),d=Me(a,f,!0),k=Me(a,f,!1),b=r==="greater"?d:r==="less"?k:Math.min(1,2*Math.min(d,k));return{...N,pValue:b}}let h=m;if(o){let f=W([6,0],[p,0]);h=W(V(m,f),V([1,0],f)),Math.abs(h[0])>=1&&(h=[Math.sign(h[0]),0])}let g=ge(h,a-2);return{...N,pValue:Ne(g,a-2,r)}}function Fe(e,t){let n=e.length,r=new Array(n);if(t==="first"||t==="last"||t==="random"){let c=t==="random"?re(n):[],i=Array.from({length:n},(a,l)=>l);return i.sort((a,l)=>{let u=e[a]-e[l];return u!==0?u:t==="first"?a-l:t==="last"?l-a:c[a]-c[l]||a-l}),i.forEach((a,l)=>r[a]=l+1),r}let s=Array.from({length:n},(c,i)=>i).sort((c,i)=>e[c]-e[i]||c-i),o=0;for(;o<n;){let c=o;for(;c+1<n&&e[s[c+1]]===e[s[o]];)c++;let i=t==="average"?(o+c+2)/2:t==="min"?o+1:c+1;for(let a=o;a<=c;a++)r[s[a]]=i;o=c+1}return r}function J(e,t={}){let n=t.tiesMethod??"average";if(!["average","first","last","random","max","min"].includes(n))throw new RangeError(`invalid tiesMethod "${n}"`);let r=t.naLast??"last",s=Array.from(e),o=s.filter(m=>!Number.isNaN(m)),c=Fe(o,n),i=s.length-o.length,a=[],l=0,u=0;for(let m of s)Number.isNaN(m)?(u++,a.push(r==="keep"?NaN:r==="last"?o.length+u:u)):a.push(r==="first"?c[l++]+i:c[l++]);return a}var Oe=["pearson","kendall","spearman"],$e=["all.obs","complete.obs","pairwise.complete.obs","everything","na.or.complete"];function xe(e,t,n,r){if(e===void 0)return n;if(t.includes(e))return e;let s=t.filter(o=>o.startsWith(e));if(e.length===0||s.length!==1)throw new RangeError(`invalid '${r}' argument`);return s[0]}function O(e){return e.length>0&&Array.isArray(e[0])}function ke(e){if(!O(e))return[Array.from(e)];let t=e[0].length;return Array.from({length:t},(n,r)=>e.map(s=>s[r]))}function Q(e,t,n,r){let s=xe(n.method,Oe,"pearson","method"),o=xe(n.use,$e,"everything","use");if(t===void 0&&!O(e))throw new TypeError("supply both 'x' and 'y' or a matrix-like 'x'");let c=ke(e),i=t===void 0?c:ke(t),a=c[0]?.length??0;if(i.some(h=>h.length!==a))throw new RangeError("incompatible dimensions");let l=[...c,...i];if(o==="all.obs"&&l.some(h=>h.some(Number.isNaN)))throw new RangeError("missing observations in cov/cor");if(!r&&o==="pairwise.complete.obs"&&s!=="pearson")throw new RangeError("cannot handle 'pairwise.complete.obs'");let u;if((o==="complete.obs"||o==="na.or.complete")&&(u=Array.from({length:a},(h,g)=>l.every(f=>!Number.isNaN(f[g]))),!u.some(Boolean))){if(o==="complete.obs")throw new RangeError("no complete element pairs");return t===void 0||O(e)||O(t)?c.map(()=>i.map(()=>NaN)):NaN}let m=h=>{let g=u===void 0?h:h.filter((f,d)=>u[d]);return s==="spearman"&&o!=="pairwise.complete.obs"?J(g,{naLast:"keep"}):g},p=c.map(m),w=t===void 0?p:i.map(m),N=(h,g)=>{let f=h,d=g;if(o==="pairwise.complete.obs"){let k=h.map((b,M)=>!Number.isNaN(b)&&!Number.isNaN(g[M]));f=h.filter((b,M)=>k[M]),d=g.filter((b,M)=>k[M]),s==="spearman"&&(f=J(f),d=J(d))}else if(f.some(Number.isNaN)||d.some(Number.isNaN))return NaN;return f.length<2?NaN:s==="kendall"?r?K(f,d).tau:2*K(f,d).s:r?H(f,d)[0]:se(f,d)},y=p.map(h=>w.map(g=>N(h,g))),E=u===void 0?a:u.filter(Boolean).length;return r&&t===void 0&&o!=="pairwise.complete.obs"&&E>=2&&y.forEach((h,g)=>h[g]=1),t!==void 0&&!O(e)&&!O(t)?y[0][0]:y}function it(e,t,n={}){return t!==void 0&&!Array.isArray(t)&&!ArrayBuffer.isView(t)?Q(e,void 0,t,!1):Q(e,t,n,!1)}function ct(e,t,n={}){return t!==void 0&&!Array.isArray(t)&&!ArrayBuffer.isView(t)?Q(e,void 0,t,!0):Q(e,t,n,!0)}export{Ve as a,Ie as b,je as c,ze as d,Ue as e,Ze as f,he as g,pe as h,Ge as i,H as j,_e as k,J as l,it as m,ct as n};
1
+ /*! rStats.js 0.15.1 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{c as re}from"./chunk-3QTVXDUM.js";import{e as ne,h as se,j as X,k as I,m as oe}from"./chunk-7J4HW6VF.js";import{a as ae,g as ie}from"./chunk-735NNFAS.js";import{k as B}from"./chunk-TYFGVCVQ.js";import{b as ce,c as S}from"./chunk-5OSQ76OO.js";import{b as Y}from"./chunk-H4CHJMFU.js";import{g as D,h as G}from"./chunk-UZHY5DWN.js";import{b as ee,c as te,d as V,f as q,g as C,i as W}from"./chunk-UWBYDIOH.js";function j(e){if(e.kind==="factor")return ce(e);let t=[...new Set(e.values)].sort((s,o)=>s-o),n=[...new Set(t.map(Y))],r=new Map(n.map((s,o)=>[s,o]));return{levels:n,codes:e.values.map(s=>r.get(Y(s)))}}function A(e,t){if(e.kind!=="numeric")throw new TypeError(`'${t}' must be a numeric column`);return e.values}function R(e,t){let n=ae(e),r=ie(n,Object.keys(t));return{terms:r,rhsVariables:r.variables.slice(r.response===0?1:0)}}function fe(e){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");return t<0?void 0:{lhs:e.slice(0,t).trim(),rhs:e.slice(t+1)}}var Ae=/^Pair\s*\(\s*([A-Za-z.][A-Za-z0-9._]*)\s*,\s*([A-Za-z.][A-Za-z0-9._]*)\s*\)$/,F="'formula' missing or incorrect",le=(e,t)=>t.length===0&&e.terms.length===0&&e.intercept;function Ve(e,t,n){let r=fe(e),s=r===void 0?null:Ae.exec(r.lhs);if(s!==null){let{terms:m,rhsVariables:p}=R(`~${r.rhs}`,t);if(!n||!le(m,p))throw new Error(F);let w=S(t,[s[1],s[2]]);return{kind:"paired",x:A(w.variables[0],s[1]),y:A(w.variables[1],s[2])}}let{terms:o,rhsVariables:c}=R(e,t);if(o.response<0)throw new Error(F);let i=o.variables[0];if(n&&le(o,c))return{kind:"one",x:A(S(t,[i]).variables[0],i)};if(c.length!==1||o.terms.length!==1)throw new Error(F);let a=S(t,[i,c[0]],{dropUnusedLevels:!0}),l=A(a.variables[0],i),u=j(a.variables[1]);if(u.levels.length!==2)throw new Error("grouping factor must have exactly 2 levels");return{kind:"two",x:l.filter((m,p)=>u.codes[p]===0),y:l.filter((m,p)=>u.codes[p]===1),levels:[u.levels[0],u.levels[1]]}}function Ie(e,t){let n=Ve(e,t,!1);if(n.kind!=="two")throw new Error(F);return n}function je(e,t){let{terms:n,rhsVariables:r}=R(e,t);if(n.response<0)throw new Error(F);if(r.length!==1)throw new Error("'formula' should be of the form response ~ group");let s=n.variables[0],o=S(t,[s,r[0]],{dropUnusedLevels:!0});return{values:A(o.variables[0],s),group:j(o.variables[1])}}function ze(e,t){let n=t.levels.map(()=>[]);return e.forEach((r,s)=>n[t.codes[s]].push(r)),n}function Ue(e,t){let{terms:n,rhsVariables:r}=R(e,t);if(n.response<0||r.length===0)throw new Error(F);let s=n.variables[0],o=S(t,[s,...r],{dropUnusedLevels:!0}),c=o.variables.slice(1).map(j),i=o.rows.map((a,l)=>{let u=0,m=1;for(let p of c)u+=p.codes[l]*m,m*=p.levels.length;return u});return{values:A(o.variables[0],s),groups:i}}var ue="incorrect specification for 'formula'";function Ze(e,t){let n=fe(e),r=n?.rhs.split("|");if(n===void 0||n.lhs===""||r.length!==2)throw new Error(ue);let s=y=>{let{terms:E,rhsVariables:h}=R(y,t);if(h.length!==1||E.terms.length!==1)throw new Error(ue);return h[0]},{terms:o}=R(`${n.lhs} ~ 1`,t),c=o.variables[0],i=s(`~${r[0]}`),a=s(`~${r[1]}`),l=S(t,[c,i,a],{dropUnusedLevels:!0}),u=A(l.variables[0],c),m=j(l.variables[1]),p=j(l.variables[2]),w=p.levels.map(()=>m.levels.map(()=>NaN)),N=p.levels.map(()=>m.levels.map(()=>0));if(u.forEach((y,E)=>{let h=p.codes[E],g=m.codes[E];N[h][g]++,w[h][g]=y}),N.some(y=>y.some(E=>E!==1)))throw new Error("not an unreplicated complete block design");return w}function me(e,t){let{terms:n,rhsVariables:r}=R(e,t);if(n.response>=0)throw new Error("'formula' missing or invalid");if(r.length!==2)throw new Error("invalid formula");let s=S(t,r);return{x:A(s.variables[0],r[0]),y:A(s.variables[1],r[1])}}function he(e){if(e===void 0)return"two.sided";let n=["two.sided","less","greater"].filter(r=>r.startsWith(e));if(e.length===0||n.length!==1)throw new RangeError(`invalid alternative "${e}" (expected "two.sided", "less" or "greater")`);return n[0]}function pe(e){if(!(Number.isFinite(e)&&e>=0&&e<=1))throw new RangeError("confLevel must be a number between 0 and 1")}function Ge(e){if(!(Number.isFinite(e)&&e>0&&e<1))throw new RangeError("'conf.level' must be a single number between 0 and 1")}var Se=["pearson","kendall","spearman"];function Te(e){if(e===void 0)return"pearson";let t=Se.filter(n=>n.startsWith(e));if(e.length===0||t.length!==1)throw new RangeError(`invalid method "${e}"`);return t[0]}function de(e){if(!(e[0]>0))return[Math.sqrt(e[0]),0];let t=Math.sqrt(e[0]),n=q(e,te(t,t));return ee(t,n[0]/(2*t))}function we(e){let t=ne(e);if(!Number.isFinite(t[0]))return;let n=e.map(o=>q([o,0],t)),r=0;for(let o of n)r=Math.max(r,Math.abs(o[0]));if(r===0)return n;let s=2**-Math.max(-1022,Math.floor(Math.log2(r)));return n.map(o=>[o[0]*s,o[1]*s])}function H(e,t){let n=e.length;if(n<2)return[NaN,0];let r=we(e),s=we(t);if(r===void 0||s===void 0)return[NaN,0];let o=[0,0],c=[0,0],i=[0,0];for(let l=0;l<n;l++)o=V(o,C(r[l],s[l])),c=V(c,C(r[l],r[l])),i=V(i,C(s[l],s[l]));if(c[0]===0||i[0]===0)return[NaN,0];let a=W(o,C(de(c),de(i)));return a[0]>=1?[1,0]:a[0]<=-1?[-1,0]:a}function ge(e,t){let n=C(q([1,0],e),V([1,0],e));return Math.sqrt(t)*e[0]/Math.sqrt(n[0])}function De(e){return Math.abs(e[0])<.5?Math.atanh(e[0]):.5*Math.log(V([1,0],e)[0]/q([1,0],e)[0])}function Ne(e,t,n){return n==="less"?B(e,t,!0,!1):n==="greater"?B(e,t,!1,!1):2*Math.min(B(e,t,!0,!1),B(e,t,!1,!1))}function Re(e,t){return t==="less"?D(e):t==="greater"?D(e,{lowerTail:!1}):2*Math.min(D(e),D(e,{lowerTail:!1}))}function K(e,t){let n=e.length,r=0;for(let u=0;u<n;u++){let m=e[u],p=t[u];for(let w=u+1;w<n;w++){let N=(e[w]>m?1:0)-(e[w]<m?1:0),y=(t[w]>p?1:0)-(t[w]<p?1:0);r+=N*y}}let s=I(e),o=I(t),c=n*(n-1)/2,i=s.reduce((u,m)=>u+m*(m-1)/2,0),a=o.reduce((u,m)=>u+m*(m-1)/2,0),l=n<2||i===c||a===c?NaN:i===0&&a===0?r/c:r/Math.sqrt((c-i)*(c-a));return{s:r,tau:l,ties:s.length>0||o.length>0,tx:s,ty:o}}function be(e,t){let n=e*(e-1)/2;if(t<0)return 0;if(t>=n)return 1;let r=new Float64Array(t+1);r[0]=1;for(let o=2;o<=e;o++){let c=new Float64Array(t+1),i=0;for(let l=0;l<=t;l++)i+=r[l],c[l]=i;let a=new Float64Array(t+1);for(let l=0;l<=t;l++)a[l]=(c[l]-(l>=o?c[l-o]:0))/o;r=a}let s=0;for(let o=t;o>=0;o--)s+=r[o];return Math.min(1,s)}var ve=new Map;function Le(e){let t=ve.get(e);if(t!==void 0)return t;let n=e*(e*e-1)/3,r=1<<e,s=new Array(r);s[0]=new Float64Array(n+1),s[0][0]=1;let o=i=>{let a=0;for(;i;i&=i-1)a++;return a};for(let i=0;i<r;i++){let a=s[i];if(a===void 0)continue;let l=o(i);for(let u=0;u<e;u++){if(i&1<<u)continue;let m=(u-l)**2,p=i|1<<u,w=s[p]??=new Float64Array(n+1);for(let N=0;N+m<=n;N++)a[N]&&(w[N+m]+=a[N])}i!==r-1&&(s[i]=void 0)}let c=s[r-1];return ve.set(e,c),c}var x=[.2274,.2531,.1745,.0758,.1033,.3932,.0879,.0151,.0072,.0831,.0131,46e-5];function ye(e,t,n){let r=t;r%2!==0&&(r+=1);let s=1/e,o=(6*(r-1)*s/(e*e-1)-1)*Math.sqrt(1/s-1),c=o*o,a=o*s*(x[0]+s*(x[1]+x[2]*s)+c*(-x[3]+s*(x[4]+x[5]*s)-c*s*(x[6]+x[7]*s-c*(x[8]-x[9]*s+c*s*(x[10]-x[11]*c)))))/Math.exp(c/2),l=n?D(o)-a:a+D(o,{lowerTail:!1});return Math.min(1,Math.max(0,l))}function Me(e,t,n){let r=e*(e*e-1)/3;if(e<=9){let s=Le(e),o=1;for(let i=2;i<=e;i++)o*=i;let c=0;if(n)for(let i=Math.min(t,r);i>=0;i--)c+=s[i];else for(let i=r;i>=Math.max(t,0);i--)c+=s[i];return c/o}return n?t+1>r?1:t+1<=0?0:ye(e,t+1,!0):t<=0?1:t>r?0:ye(e,t,!1)}function _e(e,t,n={}){if(typeof e=="string"){let r=me(e,t);return _e(r.x,r.y,n)}return Ce(e,t,n)}function Ce(e,t,n){if(e.length!==t.length)throw new TypeError("x and y must have the same length");let r=he(n.alternative),s=Te(n.method),o=n.continuity??!1,[c,i]=oe(Array.from(e),Array.from(t)),a=c.length;if(s==="pearson"){let f=n.confLevel??.95;if(pe(f),a<3)throw new Error("not enough finite observations");let d=H(c,i),k=a-2,b=Number.isNaN(d[0])?NaN:ge(d,k),M={method:"Pearson's product-moment correlation",alternative:r,statistic:b,statisticName:"t",parameter:k,parameterName:"df",pValue:Ne(b,k,r),estimate:d[0],estimateNames:"cor",nullValue:0,nullValueName:"correlation"};if(a>3){let z=De(d),L=1/Math.sqrt(a-3),_=T=>Math.tanh(z+T),$;if(r==="less")$=[-1,_(L*G(f))];else if(r==="greater")$=[_(-L*G(f)),1];else{let T=L*G((1+f)/2);$=[_(-T),_(T)]}M.confInt=$,M.confLevel=f}return M}if(a<2)throw new Error("not enough finite observations");if(s==="kendall"){let f=K(c,i),d={method:"Kendall's rank correlation tau",alternative:r,estimate:f.tau,estimateNames:"tau",nullValue:0,nullValueName:"tau"};if(Number.isNaN(f.tau))return{...d,statistic:NaN,statisticName:"T",pValue:NaN};if((n.exact??a<50)&&!f.ties){let v=a*(a-1)/2,P=(f.s+v)/2,U=be(a,P),Z=be(a,v-P),Ee=r==="less"?U:r==="greater"?Z:Math.min(1,2*Math.min(U,Z));return{...d,statistic:P,statisticName:"T",pValue:Ee}}let b=(v,P)=>P.reduce((U,Z)=>U+v(Z),0),M=v=>v*(v-1),z=v=>v*(v-1)*(v-2),L=v=>v*(v-1)*(2*v+5),_=(a*(a-1)*(2*a+5)-b(L,f.tx)-b(L,f.ty))/18+b(z,f.tx)*b(z,f.ty)/(9*a*(a-1)*(a-2))+b(M,f.tx)*b(M,f.ty)/(2*a*(a-1)),T=(o?Math.sign(f.s)*(Math.abs(f.s)-1):f.s)/Math.sqrt(_);return{...d,statistic:T,statisticName:"z",pValue:Re(T,r)}}let l=X(c),u=X(i),m=H(l,u),p=a*a*a-a,w=p*(1-m[0])/6,N={method:"Spearman's rank correlation rho",alternative:r,statistic:w,statisticName:"S",estimate:m[0],estimateNames:"rho",nullValue:0,nullValueName:"rho"};if(Number.isNaN(m[0]))return{...N,pValue:NaN};let y=I(c).length>0||I(i).length>0;if((n.exact??a<=1290)&&!y&&a<=1290){let f=Math.round(w),d=Me(a,f,!0),k=Me(a,f,!1),b=r==="greater"?d:r==="less"?k:Math.min(1,2*Math.min(d,k));return{...N,pValue:b}}let h=m;if(o){let f=W([6,0],[p,0]);h=W(V(m,f),V([1,0],f)),Math.abs(h[0])>=1&&(h=[Math.sign(h[0]),0])}let g=ge(h,a-2);return{...N,pValue:Ne(g,a-2,r)}}function Fe(e,t){let n=e.length,r=new Array(n);if(t==="first"||t==="last"||t==="random"){let c=t==="random"?re(n):[],i=Array.from({length:n},(a,l)=>l);return i.sort((a,l)=>{let u=e[a]-e[l];return u!==0?u:t==="first"?a-l:t==="last"?l-a:c[a]-c[l]||a-l}),i.forEach((a,l)=>r[a]=l+1),r}let s=Array.from({length:n},(c,i)=>i).sort((c,i)=>e[c]-e[i]||c-i),o=0;for(;o<n;){let c=o;for(;c+1<n&&e[s[c+1]]===e[s[o]];)c++;let i=t==="average"?(o+c+2)/2:t==="min"?o+1:c+1;for(let a=o;a<=c;a++)r[s[a]]=i;o=c+1}return r}function J(e,t={}){let n=t.tiesMethod??"average";if(!["average","first","last","random","max","min"].includes(n))throw new RangeError(`invalid tiesMethod "${n}"`);let r=t.naLast??"last",s=Array.from(e),o=s.filter(m=>!Number.isNaN(m)),c=Fe(o,n),i=s.length-o.length,a=[],l=0,u=0;for(let m of s)Number.isNaN(m)?(u++,a.push(r==="keep"?NaN:r==="last"?o.length+u:u)):a.push(r==="first"?c[l++]+i:c[l++]);return a}var Oe=["pearson","kendall","spearman"],$e=["all.obs","complete.obs","pairwise.complete.obs","everything","na.or.complete"];function xe(e,t,n,r){if(e===void 0)return n;if(t.includes(e))return e;let s=t.filter(o=>o.startsWith(e));if(e.length===0||s.length!==1)throw new RangeError(`invalid '${r}' argument`);return s[0]}function O(e){return e.length>0&&Array.isArray(e[0])}function ke(e){if(!O(e))return[Array.from(e)];let t=e[0].length;return Array.from({length:t},(n,r)=>e.map(s=>s[r]))}function Q(e,t,n,r){let s=xe(n.method,Oe,"pearson","method"),o=xe(n.use,$e,"everything","use");if(t===void 0&&!O(e))throw new TypeError("supply both 'x' and 'y' or a matrix-like 'x'");let c=ke(e),i=t===void 0?c:ke(t),a=c[0]?.length??0;if(i.some(h=>h.length!==a))throw new RangeError("incompatible dimensions");let l=[...c,...i];if(o==="all.obs"&&l.some(h=>h.some(Number.isNaN)))throw new RangeError("missing observations in cov/cor");if(!r&&o==="pairwise.complete.obs"&&s!=="pearson")throw new RangeError("cannot handle 'pairwise.complete.obs'");let u;if((o==="complete.obs"||o==="na.or.complete")&&(u=Array.from({length:a},(h,g)=>l.every(f=>!Number.isNaN(f[g]))),!u.some(Boolean))){if(o==="complete.obs")throw new RangeError("no complete element pairs");return t===void 0||O(e)||O(t)?c.map(()=>i.map(()=>NaN)):NaN}let m=h=>{let g=u===void 0?h:h.filter((f,d)=>u[d]);return s==="spearman"&&o!=="pairwise.complete.obs"?J(g,{naLast:"keep"}):g},p=c.map(m),w=t===void 0?p:i.map(m),N=(h,g)=>{let f=h,d=g;if(o==="pairwise.complete.obs"){let k=h.map((b,M)=>!Number.isNaN(b)&&!Number.isNaN(g[M]));f=h.filter((b,M)=>k[M]),d=g.filter((b,M)=>k[M]),s==="spearman"&&(f=J(f),d=J(d))}else if(f.some(Number.isNaN)||d.some(Number.isNaN))return NaN;return f.length<2?NaN:s==="kendall"?r?K(f,d).tau:2*K(f,d).s:r?H(f,d)[0]:se(f,d)},y=p.map(h=>w.map(g=>N(h,g))),E=u===void 0?a:u.filter(Boolean).length;return r&&t===void 0&&o!=="pairwise.complete.obs"&&E>=2&&y.forEach((h,g)=>h[g]=1),t!==void 0&&!O(e)&&!O(t)?y[0][0]:y}function it(e,t,n={}){return t!==void 0&&!Array.isArray(t)&&!ArrayBuffer.isView(t)?Q(e,void 0,t,!1):Q(e,t,n,!1)}function ct(e,t,n={}){return t!==void 0&&!Array.isArray(t)&&!ArrayBuffer.isView(t)?Q(e,void 0,t,!0):Q(e,t,n,!0)}export{Ve as a,Ie as b,je as c,ze as d,Ue as e,Ze as f,he as g,pe as h,Ge as i,H as j,_e as k,J as l,it as m,ct as n};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 0.14.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{l as me,m as he,n as pe}from"./chunks/chunk-IBJ7RI44.js";import"./chunks/chunk-7PSGKKOP.js";import{A as Fe,B as je,C as Se,D as Te,E as _e,F as Ie,a as V,b as L,c as z,d as k,e as K,f as ge,g as de,j as ye,k as we,l as Y,m as be,n as Ne,o as Ee,p as Ae,q as Me,r as C,s as F,t as S,u as xe,v as $e,w as ve,x as Oe,y as Re,z as ke}from"./chunks/chunk-FBDZ6B2G.js";import{a as ee,b as Le,c as Ce,d as Pe,e as Ue,f as qe}from"./chunks/chunk-Q4JF4QHS.js";import"./chunks/chunk-A76XBA3D.js";import"./chunks/chunk-WM33ADZV.js";import{a as G,e as I,f as J}from"./chunks/chunk-ZUESNU7W.js";import"./chunks/chunk-DWNGNTS6.js";import{a as H}from"./chunks/chunk-RZIWVCHO.js";import{b as _,c as X}from"./chunks/chunk-SZ357HRC.js";import"./chunks/chunk-IGSR4GIF.js";import"./chunks/chunk-XCAMWVNO.js";var B=4*Number.EPSILON,Ve={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function ze(e,n,t){let r=e.length,o=i=>e[Math.min(Math.max(i,1),r)-1];if(t===7){let i=1+(r-1)*n,h=Math.floor(i),m=o(h),y=o(Math.ceil(i));if(i>h&&y!==m){let g=i-h;return(1-g)*m+g*y}return m}let a,s;if(t<=3){let i=t===3?r*n-.5:r*n;a=Math.floor(i*(1+B)),t===1?s=i>a?1:0:t===2?s=i>a?1:.5:s=i!==a||Math.abs(a%2)===1?1:0}else{let[i,h]=Ve[t],m=i+n*(r+1-i-h);a=Math.floor(m*(1+B)),s=m-a,Math.abs(s)<B&&(s=0)}let l=o(a),f=o(a+1);return s===1?f:s>0&&s<1&&l!==f?(1-s)*l+s*f:l}function P(e,n=[0,.25,.5,.75,1],t={}){let r=t.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let o=Y(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let a=o.sort((i,h)=>i-h),s=typeof n=="number"?[n]:Array.from(n),l=100*Number.EPSILON;if(s.some(i=>i<-l||i>1+l))throw new RangeError("'probs' outside [0,1]");let f=s.map(i=>Number.isNaN(i)||a.length===0?NaN:ze(a,Math.min(Math.max(i,0),1),r));return typeof n=="number"?f[0]:f}function W(e,n={}){let[t,r]=P(e,[.25,.75],n);return r-t}function Be(e){let n=Array.from(e).filter(a=>!Number.isNaN(a)).sort((a,s)=>a-s),t=n.length;if(t===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((t+3)/2)/2;return[1,r,(t+1)/2,t+1-r,t].map(a=>.5*(n[Math.floor(a)-1]+n[Math.ceil(a)-1]))}function We(e,n={}){let t=Array.from(e),r=t.filter(m=>!Number.isNaN(m)),o=n.naRm?r:t,a=n.center??(o.length>r.length?NaN:F(r)),s=n.constant??1.4826,l=n.low??!1,f=n.high??!1,i=o.map(m=>Math.abs(m-a)),h=i.length;if((l||f)&&h%2===0){if(l&&f)throw new RangeError("'low' and 'high' cannot be both TRUE");let m=h/2+(f?1:0),y=i.filter(g=>!Number.isNaN(g)).sort((g,d)=>g-d);if(m===0||y.length<m)throw new RangeError(`'partial' index ${m} outside bounds`);return s*y[m-1]}return s*F(i)}var ne=e=>e===null||typeof e=="number"&&Number.isNaN(e),te=e=>Array.isArray(e)||ArrayBuffer.isView(e);function Ze(e){if(te(e))return{columns:[e],rows:e.length};if(typeof e!="object"||e===null)throw new TypeError("the arguments must be arrays or data frames");let n=Object.values(e),t=n[0]?.length??0;if(n.some(r=>r.length!==t))throw new RangeError("not all arguments have the same length");return{columns:n,rows:t}}function re(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(Ze),t=n[0].rows;if(n.some(o=>o.rows!==t))throw new RangeError("not all arguments have the same length");let r=n.flatMap(o=>o.columns);return Array.from({length:t},(o,a)=>r.every(s=>!ne(s[a])))}function De(e){if(te(e))return Array.from(e).filter(r=>!ne(r));let n=re(e),t={};for(let[r,o]of Object.entries(e)){let a=Array.from(o).filter((s,l)=>n[l]);t[r]=o instanceof Float64Array?Float64Array.from(a):a}return t}function oe(e,n={}){let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5;if(Number.isNaN(r)||Math.abs(r)>=2**31||Math.trunc(r)<0)throw new RangeError("invalid 'n' argument");let o=Math.trunc(r),a=n.minN??Math.floor(r/3);if(Number.isNaN(a)||Math.trunc(a)<0||Math.trunc(a)>o)throw new RangeError("invalid 'min.n' argument");let s=Math.trunc(a),l=n.shrinkSml??.75,f=n.highUBias??1.5,i=n.u5Bias??.5+1.5*f,h=1/0,m=-1/0;for(let A of t)A<h&&(h=A),A>m&&(m=A);let y=m-h,g,d;if(y===0&&m===0)g=1,d=!0;else{g=Math.max(Math.abs(h),Math.abs(m));let O=(1+(i>=1.5*f+.5?1/(1+f):1.5/(1+i)))*Math.max(1,o)*Number.EPSILON;d=y<g*O*3}d?(g>10&&(g=9+g/10),g*=l,s>1&&(g/=s)):(g=o>1?y/o:y,y===1/0&&o>=2&&(g=m/o-h/o));let x=2**-20*Qe;g<x?g=x:g>Number.MAX_VALUE/1.25&&(g=Number.MAX_VALUE/1.25);let b=10**Math.floor(Math.log10(g)),w=[[2*b,f],[5*b,i],[10*b,f]],c=b;for(let[A,O]of w)if(A-g<O*(g-c))c=A;else break;let u=1e-10,p=Math.floor(h/c+u);for(;p*c>h+u*c;)p--;for(;!Number.isFinite(p*c);)p++;let N=Math.ceil(m/c-u);for(;N*c<m-u*c;)N++;for(;!Number.isFinite(N*c);)N--;let E=Math.trunc(.5+N-p);if(E<s){let A=s-E,O=Math.floor(A/2),T=A%2;h===0&&p===0&&m!==0?N+=A:m===0&&N===0&&h!==0?p-=A:p>=0?(N+=O,p-=O+T):(p-=O,N+=O+T),E=s}let $=p*c<h?p*c:h,M=N*c>m?N*c:m;if(E<=0)return[$];let v;if(Number.isFinite(M-$))v=ee($,M,E+1);else{let A=M/E-$/E;v=Array.from({length:E+1},(O,T)=>$+T*A),v[E]=M}let R=M/E-$/E;return v.map(A=>Math.abs(A)<1e-14*R?0:A)}var Qe=22250738585072014e-324;function Ge(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function Je(e,n){let t=e.length,[r,o]=S(e),a=o-r;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let s=3.5*C(e)*t**-.3333333333333333;return s>0?Math.max(1,Math.ceil(a/s)):1}case"fd":case"freedman-diaconis":{let s=e.map(Ge),l=2*W(s);for(let f=1/8;l===0&&f>=1/512;f/=2){let[i,h]=P(s,[f,1-f]);l=(h-i)/(1-2*f)}return l===0&&(l=3.5*C(e)),l>0?Math.ceil(a/l*t**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function Xe(e,n){let t=e.slice(1).map((r,o)=>r-e[o]);return e.length>5?F(t):e.length<=3?n:Math.min(...t.filter(r=>r>0))}function He(e,n={}){let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,a=n.includeLowest??!0,s=n.breaks??"Sturges",l;if(typeof s!="string"&&typeof s!="number"&&s.length>1)l=[...s].sort((w,c)=>w-c);else{a=!0;let w=typeof s=="string"?Je(t,s):typeof s=="number"?s:s[0];if(!Number.isFinite(w)||w<1)throw new RangeError("invalid number of 'breaks'");w=Math.min(w,1e6);let[c,u]=S(t);l=oe([c,u],{n:w,minN:1});for(let p=1;p<l.length;p++)if(!(l[p]-l[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let f=l.length,[i,h]=r>0?S(t):[0,0],m=1e-7*Xe(l,h-i),y=l.map((w,c)=>o?c===0&&a?w-m:w+m:c<f-1?w-m:a?w+m:w-m),g=new Array(Math.max(0,f-1)).fill(0),d=0;for(let w of t){let c=Ke(w,y,o,a);c>=0&&(g[c]++,d++)}if(d<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let x=g.map((w,c)=>w/(r*(l[c+1]-l[c]))),b=g.map((w,c)=>.5*(l[c+1]+l[c]));return{breaks:l,counts:g,density:x,mids:b}}function Ke(e,n,t,r){let o=n.length-1;if(o<1)return-1;if(t){if(e===n[0]&&r)return 0;if(!(e>n[0]&&e<=n[o]))return-1;let l=1,f=o;for(;l<f;){let i=l+f>>1;e<=n[i]?f=i:l=i+1}return l-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let a=0,s=o-1;for(;a<s;){let l=a+s+1>>1;n[l]<=e?a=l:s=l-1}return a}function Ye(e){let n=Array.from(e).filter(r=>!Number.isNaN(r)).sort((r,o)=>r-o),t=n.length;if(t<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let o=0,a=t;for(;o<a;){let s=o+a>>1;n[s]<=r?o=s+1:a=s}return o/t}}var U=e=>e===null||typeof e=="number"&&Number.isNaN(e),en=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?H(e,n):Number(e)-Number(n),nn=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?_(e):e>0?"Inf":"-Inf";function tn(e,n){let t=X(n),r=new Set(t.filter(l=>!U(l)).map(l=>typeof l));if(r.size>1)throw new TypeError(`${e} mixes ${[...r].join(" and ")} labels`);let o=[...r][0];if(o!==void 0&&o!=="number"&&o!=="string"&&o!=="boolean")throw new TypeError(`${e} has labels of an unsupported type`);let a=[...new Set(t.filter(l=>!U(l)))].sort(en),s=new Map(a.map((l,f)=>[l,f]));return{levels:a,codes:t.map(l=>U(l)?-1:s.get(l))}}var j=e=>Array.isArray(e)||e instanceof Float64Array;function ie(e){if(e instanceof Float64Array)return[e];if(!Array.isArray(e))throw new TypeError("the group labels must be an array or an array of arrays");if(e.length>0&&e.every(j))return[...e];if(e.some(j))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function Z(e,n,t){e.forEach((s,l)=>{if(s.length!==t)throw new RangeError(`${n[l]} must have one label per row (${t}), not ${s.length}`)});let r=e.map((s,l)=>tn(n[l],s)),o=r.reduce((s,l)=>s*l.levels.length,1),a=new Array(t);for(let s=0;s<t;s++){let l=0,f=1;for(let i of r){let h=i.codes[s];if(h<0){l=-1;break}l+=h*f,f*=i.levels.length}a[s]=l}return{factors:r,size:o,cells:a}}function D(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function rn(e,n){return e.factors.map(t=>{let r=t.levels.length,o=t.levels[n%r];return n=Math.floor(n/r),o})}var ce=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function on(e,n,t){let r=Array.from(e),o=ie(n),a=Z(o,ce(o.length,"index"),r.length),s=D(a).map(i=>i.length===0?null:{value:t(i.map(h=>r[h]))}),f=s.every(i=>i===null||typeof i.value=="number")?s.map(i=>i===null?NaN:i.value):s.map(i=>i===null?null:i.value);return{dim:a.factors.map(i=>i.levels.length),dimnames:a.factors.map(i=>[...i.levels]),values:f}}function sn(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=o instanceof Float64Array?Float64Array.from(n,a=>o[a]):n.map(a=>o[a]);return t}function ln(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!j(o))throw new TypeError(`column '${r}' must be an array`);if(o.length!==t)throw new RangeError(`the columns of the data frame have different lengths (found for '${r}')`)}return t}function an(e,n,t={}){let r=t.sep??".",o=ie(n),a=!j(e);if(a&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let s=a?ln(e):e.length,l=Z(o,ce(o.length,"f"),s),f=a?[]:Array.from(e),i=new Map;return D(l).forEach((h,m)=>{if(h.length===0&&(t.drop||l.factors.length===1))return;let y=rn(l,m).map(nn).join(r);i.set(y,a?sn(e,h):h.map(g=>f[g]))}),i}function se(e,n){if(n===void 0)throw new Error(`object '${e}' not found`);if(!j(n))throw new TypeError(`column '${e}' must be an array`);return Array.from(n,t=>{if(t===null)return NaN;if(typeof t!="number")throw new TypeError(`column '${e}' to summarise must be numeric`);return t})}function le(e,n){let t=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(t===void 0)throw new Error(`object '${n}' not found`);if(!j(t))throw new TypeError(`column '${n}' must be an array`);return t}function cn(e,n){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");if(t<0)throw new SyntaxError("invalid formula: missing '~'");let r=e.slice(0,t).trim(),{rhs:o}=G(`~ ${e.slice(t+1)}`),a=/^[A-Za-z.][A-Za-z0-9._]*$/,s;if(r!=="."){let i=/^cbind\s*\((.*)\)$/s.exec(r);if(s=i===null?[r]:i[1].split(",").map(h=>h.trim()),s.some(h=>!a.test(h)||h==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}else if(I(o,[]).length<I(o,["."]).length)throw new SyntaxError("invalid formula: '.' cannot be on both sides");let l=s===void 0?[]:n.filter(i=>!s.includes(i)),f=I(o,l);return J(o,()=>0,l),{values:s??n.filter(i=>!f.includes(i)),groups:f}}function ae(e,n,t,r,o,a){let s=r[0]?.length??n[0]?.length??0;e.forEach((h,m)=>{if(n[m].length!==s)throw new RangeError(`variable lengths differ (found for '${h}')`)});let l=Z(r,t,s),f=D(l).map((h,m)=>({cell:m,rows:h.filter(o)})).filter(h=>h.rows.length>0),i={};return t.forEach((h,m)=>{let y=r[m];i[h]=f.map(g=>{let d=y[g.rows[0]];return d===0?0:d})}),e.forEach((h,m)=>{let y=n[m],d=f.map(b=>a(b.rows.map(w=>y[w]))).map(b=>{if(typeof b=="number")return{names:void 0,values:[b]};if(Array.isArray(b))return{names:void 0,values:[...b]};let w=b;return{names:Object.keys(w),values:Object.values(w)}}),x=d[0]?.values.length??1;if(d.some(b=>b.values.length!==x))throw new RangeError("fun must return values of the same length for every group");if(x===1&&d[0]?.names===void 0){i[h]=d.map(b=>b.values[0]);return}for(let b=0;b<x;b++){let w=d[0].names?.[b]??String(b+1);i[`${h}.${w}`]=d.map(c=>c.values[b])}}),i}function un(e,n,t){if(typeof n!="object"||n===null)throw new TypeError("the data must be an object of columns");if(typeof e=="string"){let l=n,{values:f,groups:i}=cn(e,Object.keys(l)),h=d=>Object.prototype.hasOwnProperty.call(l,d),m=f.map(d=>se(d,h(d)?l[d]:void 0)),y=i.map(d=>le(l,d));return ae(f,m,i,y,d=>m.every(x=>!Number.isNaN(x[d]))&&y.every(x=>!U(x[d])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(l=>se(l,e[l])),a=Object.keys(n);if(a.length===0)throw new RangeError("'by' must name at least one grouping column");let s=a.map(l=>le(n,l));return ae(r,o,a,s,()=>!0,t)}var q=e=>typeof e=="string"?[e]:[...e];function fe(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new Error(`Column \`${t}\` doesn't exist.`)}function fn(e,n){if(n instanceof Float64Array)return"double";let t=null;for(let r of n){if(r===null)continue;let o=typeof r=="number"?"double":typeof r=="string"?"character":"logical";if(t!==null&&o!==t)throw new TypeError(`column '${e}' mixes ${t} and ${o} values`);t=o}return t}function mn(e,n){let t=null;for(let r of n){let o=fn(r,e[r]);if(o!==null){if(t===null)t={type:o,column:r};else if(t.type!==o){if(t.type==="character"||o==="character")throw new TypeError(`Can't combine \`${t.column}\` <${t.type}> and \`${r}\` <${o}>.`);o==="double"&&(t={type:o,column:r})}}}return t?.type??null}function hn(e,n,t){let r=new RegExp(`${n}|`).exec("").length-1;if(r!==t)throw new Error(`\`regex\` should define ${t} groups; ${r} found.`);let o=new RegExp(n);return e.map(a=>{let s=o.exec(a);return Array.from({length:t},(l,f)=>s===null?null:s[f+1]??null)})}function pn(e,n,t,r){let o=new RegExp(n,"g"),a=[],s=[],l=e.map((i,h)=>{let m=[],y=0;for(let g of i.matchAll(o))g[0].length!==0&&(m.push(i.slice(y,g.index)),y=g.index+g[0].length);return m.push(i.slice(y)),m.length>t&&a.push(h+1),m.length<t&&s.push(h+1),Array.from({length:t},(g,d)=>m[d]??null)}),f=i=>`${i.length} rows [${i.join(", ")}]`;return a.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${f(a)}.`),s.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${f(s)}.`),l}function gn(e,n,t,r){let{namesSep:o,namesPattern:a}=t;if(n.length===1){if(o!==void 0)throw new Error("`names_sep` can't be used with a length 1 `names_to`.");if(a===void 0)return e.map(l=>[l]);let s=new RegExp(a);return e.map(l=>[s.exec(l)?.[1]??null])}if(o===void 0==(a===void 0))throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");return o!==void 0?pn(e,o,n.length,r):hn(e,a,n.length)}function dn(e,n){let t=V(e),r=Object.keys(e),o=typeof n.cols=="function"?r.filter(n.cols):[...new Set(n.cols)];if(fe(e,o),o.length===0)throw new Error("`cols` must select at least one column.");let a=q(n.namesTo??"name"),s=a.indexOf(".value");if(a.lastIndexOf(".value")!==s)throw new Error('`names_to` may contain ".value" only once');let l=[],f=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),i=o.map(c=>f===null?c:c.replace(f,"")),h=gn(i,a,n,l),m=[],y=[];if(s<0)m.push(...h),y.push({name:n.valuesTo??"value",sources:[...o]});else{let c=new Map,u=new Map;h.forEach((p,N)=>{let E=p.filter((A,O)=>O!==s),$=JSON.stringify(E),M=c.get($);if(M===void 0){M=m.length,c.set($,M),m.push(E);for(let A of y)A.sources.push(null)}let v=p[s]??"NA",R=u.get(v);if(R===void 0&&(R={name:v,sources:m.map(()=>null)},u.set(v,R),y.push(R)),R.sources[M]!==null)throw new Error(`the names give the value column '${v}' twice for one key`);R.sources[M]=o[N]})}let g=y.map(c=>mn(e,c.sources.filter(u=>u!==null))),d=[];if(n.colsVary==="slowest")for(let c=0;c<m.length;c++)for(let u=0;u<t;u++)d.push([u,c]);else for(let c=0;c<t;c++)for(let u=0;u<m.length;u++)d.push([c,u]);let x=(c,u,p)=>{let N=c.sources[p];return N==null?null:e[N][u]};n.valuesDropNa===!0&&(d=d.filter(([c,u])=>y.some(p=>!L(x(p,c,u)))));let b={},w=d.map(([c])=>c);for(let c of r)o.includes(c)||k(b,c,z(e[c],w));if(a.forEach((c,u)=>{if(u===s)return;let p=n.namesTransform?.[c],N=E=>{let $=m[E][u<s||s<0?u:u-1];return $===null||p===void 0?$:p($)};k(b,c,d.map(([,E])=>N(E)))}),y.forEach((c,u)=>{let p=g[u]==="double";if(p&&c.sources.every(N=>N!==null&&e[N]instanceof Float64Array))k(b,c.name,Float64Array.from(d,([N,E])=>x(c,N,E)));else{let N=d.map(([E,$])=>{let M=x(c,E,$);return p&&typeof M=="boolean"?Number(M):M});k(b,c.name,N)}}),n.onWarning!==void 0)for(let c of new Set(l))n.onWarning(c);return b}var yn=e=>L(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function ue(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(a,s)=>{let l=JSON.stringify(e.map(i=>yn(i[s]))),f=t.get(l);return f===void 0&&(f=r.length,t.set(l,f),r.push(s)),f}),firsts:r}}function wn(e){return L(e)?"NA":typeof e=="number"?Number.isFinite(e)?_(e):e>0?"Inf":"-Inf":typeof e=="boolean"?e?"TRUE":"FALSE":e}function Q(e,n,t){if(e!==void 0)return n(e)?e:e[t]}function bn(e,n={}){let t=V(e),r=q(n.namesFrom??"name"),o=q(n.valuesFrom??"value"),a=n.idCols===void 0?Object.keys(e).filter(u=>!r.includes(u)&&!o.includes(u)):q(n.idCols);fe(e,[...a,...r,...o]);let s=n.namesPrefix??"",l=n.namesSep??"_",f=ue(a.map(u=>e[u]),t),i=ue(r.map(u=>e[u]),t),h=i.firsts.map((u,p)=>p);n.namesSort===!0&&h.sort((u,p)=>{for(let N of r){let E=K(e[N][i.firsts[u]],e[N][i.firsts[p]]);if(E!==0)return E}return 0});let m=i.firsts.map(u=>s+r.map(p=>wn(e[p][u])).join(l)),y=i.firsts.length,g=Array.from({length:f.firsts.length*y},()=>[]);for(let u=0;u<t;u++)g[f.codes[u]*y+i.codes[u]].push(u);let d=u=>typeof u=="function",x=u=>typeof u!="object"||u===null,b=(u,p)=>{let N=e[u],E=Q(n.valuesFn,d,u),$=Q(n.valuesFill,x,u)??null,M=f.firsts.map((v,R)=>{let A=g[R*y+p];return A.length===0?$:E!==void 0?E(A.map(O=>N[O])):N[A[0]]});return N instanceof Float64Array&&M.every(v=>v===null||typeof v=="number")?Float64Array.from(M,v=>v===null?NaN:v):M};for(let u of o)if(Q(n.valuesFn,d,u)===void 0&&g.some(p=>p.length>1))throw new Error(`values from '${u}' are not uniquely identified; use valuesFn to summarise them`);let w={};for(let u of a)k(w,u,z(e[u],f.firsts));let c=(u,p)=>o.length===1?m[p]:`${u}${l}${m[p]}`;if(n.namesVary==="slowest")for(let u of h)for(let p of o)k(w,c(p,u),b(p,u));else for(let u of o)for(let p of h)k(w,c(u,p),b(u,p));return w}export{W as IQR,un as aggregate,re as completeCases,pe as cor,he as cov,ve as cummax,Oe as cummin,$e as cumprod,xe as cumsum,Ue as cut,_e as cv,Re as diff,Ye as ecdf,qe as findInterval,Be as fivenum,ye as fromRows,je as geometricMean,He as hist,Fe as kurtosis,We as mad,Ee as mean,Te as meanAD,F as median,ge as merge,Se as modes,De as naOmit,dn as pivotLonger,bn as pivotWider,oe as pretty,Ne as prod,P as quantile,S as range,me as rank,Ie as scale,C as sd,ke as skewness,an as split,de as subset,be as sum,Ce as table,Le as tabulate,on as tapply,we as toRows,Pe as unique,Me as variance,Ae as weightedMean};
1
+ /*! rStats.js 0.15.1 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{l as me,m as he,n as pe}from"./chunks/chunk-Z3C3G5XI.js";import"./chunks/chunk-3QTVXDUM.js";import{A as Fe,B as je,C as Se,D as Te,E as _e,F as Ie,a as V,b as L,c as z,d as k,e as K,f as ge,g as de,j as ye,k as we,l as Y,m as be,n as Ne,o as Ee,p as Ae,q as Me,r as C,s as F,t as S,u as xe,v as $e,w as ve,x as Oe,y as Re,z as ke}from"./chunks/chunk-LY2T6DA6.js";import{a as ee,b as Le,c as Ce,d as Pe,e as Ue,f as qe}from"./chunks/chunk-IQOVOHZG.js";import"./chunks/chunk-4ILI2FSB.js";import"./chunks/chunk-7J4HW6VF.js";import{a as G,e as I,f as J}from"./chunks/chunk-735NNFAS.js";import"./chunks/chunk-TYFGVCVQ.js";import{a as H}from"./chunks/chunk-5OSQ76OO.js";import{b as _,c as X}from"./chunks/chunk-H4CHJMFU.js";import"./chunks/chunk-UZHY5DWN.js";import"./chunks/chunk-UWBYDIOH.js";var B=4*Number.EPSILON,Ve={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function ze(e,n,t){let r=e.length,o=i=>e[Math.min(Math.max(i,1),r)-1];if(t===7){let i=1+(r-1)*n,h=Math.floor(i),m=o(h),y=o(Math.ceil(i));if(i>h&&y!==m){let g=i-h;return(1-g)*m+g*y}return m}let a,s;if(t<=3){let i=t===3?r*n-.5:r*n;a=Math.floor(i*(1+B)),t===1?s=i>a?1:0:t===2?s=i>a?1:.5:s=i!==a||Math.abs(a%2)===1?1:0}else{let[i,h]=Ve[t],m=i+n*(r+1-i-h);a=Math.floor(m*(1+B)),s=m-a,Math.abs(s)<B&&(s=0)}let l=o(a),f=o(a+1);return s===1?f:s>0&&s<1&&l!==f?(1-s)*l+s*f:l}function P(e,n=[0,.25,.5,.75,1],t={}){let r=t.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let o=Y(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let a=o.sort((i,h)=>i-h),s=typeof n=="number"?[n]:Array.from(n),l=100*Number.EPSILON;if(s.some(i=>i<-l||i>1+l))throw new RangeError("'probs' outside [0,1]");let f=s.map(i=>Number.isNaN(i)||a.length===0?NaN:ze(a,Math.min(Math.max(i,0),1),r));return typeof n=="number"?f[0]:f}function W(e,n={}){let[t,r]=P(e,[.25,.75],n);return r-t}function Be(e){let n=Array.from(e).filter(a=>!Number.isNaN(a)).sort((a,s)=>a-s),t=n.length;if(t===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((t+3)/2)/2;return[1,r,(t+1)/2,t+1-r,t].map(a=>.5*(n[Math.floor(a)-1]+n[Math.ceil(a)-1]))}function We(e,n={}){let t=Array.from(e),r=t.filter(m=>!Number.isNaN(m)),o=n.naRm?r:t,a=n.center??(o.length>r.length?NaN:F(r)),s=n.constant??1.4826,l=n.low??!1,f=n.high??!1,i=o.map(m=>Math.abs(m-a)),h=i.length;if((l||f)&&h%2===0){if(l&&f)throw new RangeError("'low' and 'high' cannot be both TRUE");let m=h/2+(f?1:0),y=i.filter(g=>!Number.isNaN(g)).sort((g,d)=>g-d);if(m===0||y.length<m)throw new RangeError(`'partial' index ${m} outside bounds`);return s*y[m-1]}return s*F(i)}var ne=e=>e===null||typeof e=="number"&&Number.isNaN(e),te=e=>Array.isArray(e)||ArrayBuffer.isView(e);function Ze(e){if(te(e))return{columns:[e],rows:e.length};if(typeof e!="object"||e===null)throw new TypeError("the arguments must be arrays or data frames");let n=Object.values(e),t=n[0]?.length??0;if(n.some(r=>r.length!==t))throw new RangeError("not all arguments have the same length");return{columns:n,rows:t}}function re(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(Ze),t=n[0].rows;if(n.some(o=>o.rows!==t))throw new RangeError("not all arguments have the same length");let r=n.flatMap(o=>o.columns);return Array.from({length:t},(o,a)=>r.every(s=>!ne(s[a])))}function De(e){if(te(e))return Array.from(e).filter(r=>!ne(r));let n=re(e),t={};for(let[r,o]of Object.entries(e)){let a=Array.from(o).filter((s,l)=>n[l]);t[r]=o instanceof Float64Array?Float64Array.from(a):a}return t}function oe(e,n={}){let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5;if(Number.isNaN(r)||Math.abs(r)>=2**31||Math.trunc(r)<0)throw new RangeError("invalid 'n' argument");let o=Math.trunc(r),a=n.minN??Math.floor(r/3);if(Number.isNaN(a)||Math.trunc(a)<0||Math.trunc(a)>o)throw new RangeError("invalid 'min.n' argument");let s=Math.trunc(a),l=n.shrinkSml??.75,f=n.highUBias??1.5,i=n.u5Bias??.5+1.5*f,h=1/0,m=-1/0;for(let A of t)A<h&&(h=A),A>m&&(m=A);let y=m-h,g,d;if(y===0&&m===0)g=1,d=!0;else{g=Math.max(Math.abs(h),Math.abs(m));let O=(1+(i>=1.5*f+.5?1/(1+f):1.5/(1+i)))*Math.max(1,o)*Number.EPSILON;d=y<g*O*3}d?(g>10&&(g=9+g/10),g*=l,s>1&&(g/=s)):(g=o>1?y/o:y,y===1/0&&o>=2&&(g=m/o-h/o));let x=2**-20*Qe;g<x?g=x:g>Number.MAX_VALUE/1.25&&(g=Number.MAX_VALUE/1.25);let b=10**Math.floor(Math.log10(g)),w=[[2*b,f],[5*b,i],[10*b,f]],c=b;for(let[A,O]of w)if(A-g<O*(g-c))c=A;else break;let u=1e-10,p=Math.floor(h/c+u);for(;p*c>h+u*c;)p--;for(;!Number.isFinite(p*c);)p++;let N=Math.ceil(m/c-u);for(;N*c<m-u*c;)N++;for(;!Number.isFinite(N*c);)N--;let E=Math.trunc(.5+N-p);if(E<s){let A=s-E,O=Math.floor(A/2),T=A%2;h===0&&p===0&&m!==0?N+=A:m===0&&N===0&&h!==0?p-=A:p>=0?(N+=O,p-=O+T):(p-=O,N+=O+T),E=s}let $=p*c<h?p*c:h,M=N*c>m?N*c:m;if(E<=0)return[$];let v;if(Number.isFinite(M-$))v=ee($,M,E+1);else{let A=M/E-$/E;v=Array.from({length:E+1},(O,T)=>$+T*A),v[E]=M}let R=M/E-$/E;return v.map(A=>Math.abs(A)<1e-14*R?0:A)}var Qe=22250738585072014e-324;function Ge(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function Je(e,n){let t=e.length,[r,o]=S(e),a=o-r;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let s=3.5*C(e)*t**-.3333333333333333;return s>0?Math.max(1,Math.ceil(a/s)):1}case"fd":case"freedman-diaconis":{let s=e.map(Ge),l=2*W(s);for(let f=1/8;l===0&&f>=1/512;f/=2){let[i,h]=P(s,[f,1-f]);l=(h-i)/(1-2*f)}return l===0&&(l=3.5*C(e)),l>0?Math.ceil(a/l*t**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function Xe(e,n){let t=e.slice(1).map((r,o)=>r-e[o]);return e.length>5?F(t):e.length<=3?n:Math.min(...t.filter(r=>r>0))}function He(e,n={}){let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,a=n.includeLowest??!0,s=n.breaks??"Sturges",l;if(typeof s!="string"&&typeof s!="number"&&s.length>1)l=[...s].sort((w,c)=>w-c);else{a=!0;let w=typeof s=="string"?Je(t,s):typeof s=="number"?s:s[0];if(!Number.isFinite(w)||w<1)throw new RangeError("invalid number of 'breaks'");w=Math.min(w,1e6);let[c,u]=S(t);l=oe([c,u],{n:w,minN:1});for(let p=1;p<l.length;p++)if(!(l[p]-l[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let f=l.length,[i,h]=r>0?S(t):[0,0],m=1e-7*Xe(l,h-i),y=l.map((w,c)=>o?c===0&&a?w-m:w+m:c<f-1?w-m:a?w+m:w-m),g=new Array(Math.max(0,f-1)).fill(0),d=0;for(let w of t){let c=Ke(w,y,o,a);c>=0&&(g[c]++,d++)}if(d<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let x=g.map((w,c)=>w/(r*(l[c+1]-l[c]))),b=g.map((w,c)=>.5*(l[c+1]+l[c]));return{breaks:l,counts:g,density:x,mids:b}}function Ke(e,n,t,r){let o=n.length-1;if(o<1)return-1;if(t){if(e===n[0]&&r)return 0;if(!(e>n[0]&&e<=n[o]))return-1;let l=1,f=o;for(;l<f;){let i=l+f>>1;e<=n[i]?f=i:l=i+1}return l-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let a=0,s=o-1;for(;a<s;){let l=a+s+1>>1;n[l]<=e?a=l:s=l-1}return a}function Ye(e){let n=Array.from(e).filter(r=>!Number.isNaN(r)).sort((r,o)=>r-o),t=n.length;if(t<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let o=0,a=t;for(;o<a;){let s=o+a>>1;n[s]<=r?o=s+1:a=s}return o/t}}var U=e=>e===null||typeof e=="number"&&Number.isNaN(e),en=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?H(e,n):Number(e)-Number(n),nn=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?_(e):e>0?"Inf":"-Inf";function tn(e,n){let t=X(n),r=new Set(t.filter(l=>!U(l)).map(l=>typeof l));if(r.size>1)throw new TypeError(`${e} mixes ${[...r].join(" and ")} labels`);let o=[...r][0];if(o!==void 0&&o!=="number"&&o!=="string"&&o!=="boolean")throw new TypeError(`${e} has labels of an unsupported type`);let a=[...new Set(t.filter(l=>!U(l)))].sort(en),s=new Map(a.map((l,f)=>[l,f]));return{levels:a,codes:t.map(l=>U(l)?-1:s.get(l))}}var j=e=>Array.isArray(e)||e instanceof Float64Array;function ie(e){if(e instanceof Float64Array)return[e];if(!Array.isArray(e))throw new TypeError("the group labels must be an array or an array of arrays");if(e.length>0&&e.every(j))return[...e];if(e.some(j))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function Z(e,n,t){e.forEach((s,l)=>{if(s.length!==t)throw new RangeError(`${n[l]} must have one label per row (${t}), not ${s.length}`)});let r=e.map((s,l)=>tn(n[l],s)),o=r.reduce((s,l)=>s*l.levels.length,1),a=new Array(t);for(let s=0;s<t;s++){let l=0,f=1;for(let i of r){let h=i.codes[s];if(h<0){l=-1;break}l+=h*f,f*=i.levels.length}a[s]=l}return{factors:r,size:o,cells:a}}function D(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function rn(e,n){return e.factors.map(t=>{let r=t.levels.length,o=t.levels[n%r];return n=Math.floor(n/r),o})}var ce=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function on(e,n,t){let r=Array.from(e),o=ie(n),a=Z(o,ce(o.length,"index"),r.length),s=D(a).map(i=>i.length===0?null:{value:t(i.map(h=>r[h]))}),f=s.every(i=>i===null||typeof i.value=="number")?s.map(i=>i===null?NaN:i.value):s.map(i=>i===null?null:i.value);return{dim:a.factors.map(i=>i.levels.length),dimnames:a.factors.map(i=>[...i.levels]),values:f}}function sn(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=o instanceof Float64Array?Float64Array.from(n,a=>o[a]):n.map(a=>o[a]);return t}function ln(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!j(o))throw new TypeError(`column '${r}' must be an array`);if(o.length!==t)throw new RangeError(`the columns of the data frame have different lengths (found for '${r}')`)}return t}function an(e,n,t={}){let r=t.sep??".",o=ie(n),a=!j(e);if(a&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let s=a?ln(e):e.length,l=Z(o,ce(o.length,"f"),s),f=a?[]:Array.from(e),i=new Map;return D(l).forEach((h,m)=>{if(h.length===0&&(t.drop||l.factors.length===1))return;let y=rn(l,m).map(nn).join(r);i.set(y,a?sn(e,h):h.map(g=>f[g]))}),i}function se(e,n){if(n===void 0)throw new Error(`object '${e}' not found`);if(!j(n))throw new TypeError(`column '${e}' must be an array`);return Array.from(n,t=>{if(t===null)return NaN;if(typeof t!="number")throw new TypeError(`column '${e}' to summarise must be numeric`);return t})}function le(e,n){let t=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(t===void 0)throw new Error(`object '${n}' not found`);if(!j(t))throw new TypeError(`column '${n}' must be an array`);return t}function cn(e,n){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");if(t<0)throw new SyntaxError("invalid formula: missing '~'");let r=e.slice(0,t).trim(),{rhs:o}=G(`~ ${e.slice(t+1)}`),a=/^[A-Za-z.][A-Za-z0-9._]*$/,s;if(r!=="."){let i=/^cbind\s*\((.*)\)$/s.exec(r);if(s=i===null?[r]:i[1].split(",").map(h=>h.trim()),s.some(h=>!a.test(h)||h==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}else if(I(o,[]).length<I(o,["."]).length)throw new SyntaxError("invalid formula: '.' cannot be on both sides");let l=s===void 0?[]:n.filter(i=>!s.includes(i)),f=I(o,l);return J(o,()=>0,l),{values:s??n.filter(i=>!f.includes(i)),groups:f}}function ae(e,n,t,r,o,a){let s=r[0]?.length??n[0]?.length??0;e.forEach((h,m)=>{if(n[m].length!==s)throw new RangeError(`variable lengths differ (found for '${h}')`)});let l=Z(r,t,s),f=D(l).map((h,m)=>({cell:m,rows:h.filter(o)})).filter(h=>h.rows.length>0),i={};return t.forEach((h,m)=>{let y=r[m];i[h]=f.map(g=>{let d=y[g.rows[0]];return d===0?0:d})}),e.forEach((h,m)=>{let y=n[m],d=f.map(b=>a(b.rows.map(w=>y[w]))).map(b=>{if(typeof b=="number")return{names:void 0,values:[b]};if(Array.isArray(b))return{names:void 0,values:[...b]};let w=b;return{names:Object.keys(w),values:Object.values(w)}}),x=d[0]?.values.length??1;if(d.some(b=>b.values.length!==x))throw new RangeError("fun must return values of the same length for every group");if(x===1&&d[0]?.names===void 0){i[h]=d.map(b=>b.values[0]);return}for(let b=0;b<x;b++){let w=d[0].names?.[b]??String(b+1);i[`${h}.${w}`]=d.map(c=>c.values[b])}}),i}function un(e,n,t){if(typeof n!="object"||n===null)throw new TypeError("the data must be an object of columns");if(typeof e=="string"){let l=n,{values:f,groups:i}=cn(e,Object.keys(l)),h=d=>Object.prototype.hasOwnProperty.call(l,d),m=f.map(d=>se(d,h(d)?l[d]:void 0)),y=i.map(d=>le(l,d));return ae(f,m,i,y,d=>m.every(x=>!Number.isNaN(x[d]))&&y.every(x=>!U(x[d])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(l=>se(l,e[l])),a=Object.keys(n);if(a.length===0)throw new RangeError("'by' must name at least one grouping column");let s=a.map(l=>le(n,l));return ae(r,o,a,s,()=>!0,t)}var q=e=>typeof e=="string"?[e]:[...e];function fe(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new Error(`Column \`${t}\` doesn't exist.`)}function fn(e,n){if(n instanceof Float64Array)return"double";let t=null;for(let r of n){if(r===null)continue;let o=typeof r=="number"?"double":typeof r=="string"?"character":"logical";if(t!==null&&o!==t)throw new TypeError(`column '${e}' mixes ${t} and ${o} values`);t=o}return t}function mn(e,n){let t=null;for(let r of n){let o=fn(r,e[r]);if(o!==null){if(t===null)t={type:o,column:r};else if(t.type!==o){if(t.type==="character"||o==="character")throw new TypeError(`Can't combine \`${t.column}\` <${t.type}> and \`${r}\` <${o}>.`);o==="double"&&(t={type:o,column:r})}}}return t?.type??null}function hn(e,n,t){let r=new RegExp(`${n}|`).exec("").length-1;if(r!==t)throw new Error(`\`regex\` should define ${t} groups; ${r} found.`);let o=new RegExp(n);return e.map(a=>{let s=o.exec(a);return Array.from({length:t},(l,f)=>s===null?null:s[f+1]??null)})}function pn(e,n,t,r){let o=new RegExp(n,"g"),a=[],s=[],l=e.map((i,h)=>{let m=[],y=0;for(let g of i.matchAll(o))g[0].length!==0&&(m.push(i.slice(y,g.index)),y=g.index+g[0].length);return m.push(i.slice(y)),m.length>t&&a.push(h+1),m.length<t&&s.push(h+1),Array.from({length:t},(g,d)=>m[d]??null)}),f=i=>`${i.length} rows [${i.join(", ")}]`;return a.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${f(a)}.`),s.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${f(s)}.`),l}function gn(e,n,t,r){let{namesSep:o,namesPattern:a}=t;if(n.length===1){if(o!==void 0)throw new Error("`names_sep` can't be used with a length 1 `names_to`.");if(a===void 0)return e.map(l=>[l]);let s=new RegExp(a);return e.map(l=>[s.exec(l)?.[1]??null])}if(o===void 0==(a===void 0))throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");return o!==void 0?pn(e,o,n.length,r):hn(e,a,n.length)}function dn(e,n){let t=V(e),r=Object.keys(e),o=typeof n.cols=="function"?r.filter(n.cols):[...new Set(n.cols)];if(fe(e,o),o.length===0)throw new Error("`cols` must select at least one column.");let a=q(n.namesTo??"name"),s=a.indexOf(".value");if(a.lastIndexOf(".value")!==s)throw new Error('`names_to` may contain ".value" only once');let l=[],f=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),i=o.map(c=>f===null?c:c.replace(f,"")),h=gn(i,a,n,l),m=[],y=[];if(s<0)m.push(...h),y.push({name:n.valuesTo??"value",sources:[...o]});else{let c=new Map,u=new Map;h.forEach((p,N)=>{let E=p.filter((A,O)=>O!==s),$=JSON.stringify(E),M=c.get($);if(M===void 0){M=m.length,c.set($,M),m.push(E);for(let A of y)A.sources.push(null)}let v=p[s]??"NA",R=u.get(v);if(R===void 0&&(R={name:v,sources:m.map(()=>null)},u.set(v,R),y.push(R)),R.sources[M]!==null)throw new Error(`the names give the value column '${v}' twice for one key`);R.sources[M]=o[N]})}let g=y.map(c=>mn(e,c.sources.filter(u=>u!==null))),d=[];if(n.colsVary==="slowest")for(let c=0;c<m.length;c++)for(let u=0;u<t;u++)d.push([u,c]);else for(let c=0;c<t;c++)for(let u=0;u<m.length;u++)d.push([c,u]);let x=(c,u,p)=>{let N=c.sources[p];return N==null?null:e[N][u]};n.valuesDropNa===!0&&(d=d.filter(([c,u])=>y.some(p=>!L(x(p,c,u)))));let b={},w=d.map(([c])=>c);for(let c of r)o.includes(c)||k(b,c,z(e[c],w));if(a.forEach((c,u)=>{if(u===s)return;let p=n.namesTransform?.[c],N=E=>{let $=m[E][u<s||s<0?u:u-1];return $===null||p===void 0?$:p($)};k(b,c,d.map(([,E])=>N(E)))}),y.forEach((c,u)=>{let p=g[u]==="double";if(p&&c.sources.every(N=>N!==null&&e[N]instanceof Float64Array))k(b,c.name,Float64Array.from(d,([N,E])=>x(c,N,E)));else{let N=d.map(([E,$])=>{let M=x(c,E,$);return p&&typeof M=="boolean"?Number(M):M});k(b,c.name,N)}}),n.onWarning!==void 0)for(let c of new Set(l))n.onWarning(c);return b}var yn=e=>L(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function ue(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(a,s)=>{let l=JSON.stringify(e.map(i=>yn(i[s]))),f=t.get(l);return f===void 0&&(f=r.length,t.set(l,f),r.push(s)),f}),firsts:r}}function wn(e){return L(e)?"NA":typeof e=="number"?Number.isFinite(e)?_(e):e>0?"Inf":"-Inf":typeof e=="boolean"?e?"TRUE":"FALSE":e}function Q(e,n,t){if(e!==void 0)return n(e)?e:e[t]}function bn(e,n={}){let t=V(e),r=q(n.namesFrom??"name"),o=q(n.valuesFrom??"value"),a=n.idCols===void 0?Object.keys(e).filter(u=>!r.includes(u)&&!o.includes(u)):q(n.idCols);fe(e,[...a,...r,...o]);let s=n.namesPrefix??"",l=n.namesSep??"_",f=ue(a.map(u=>e[u]),t),i=ue(r.map(u=>e[u]),t),h=i.firsts.map((u,p)=>p);n.namesSort===!0&&h.sort((u,p)=>{for(let N of r){let E=K(e[N][i.firsts[u]],e[N][i.firsts[p]]);if(E!==0)return E}return 0});let m=i.firsts.map(u=>s+r.map(p=>wn(e[p][u])).join(l)),y=i.firsts.length,g=Array.from({length:f.firsts.length*y},()=>[]);for(let u=0;u<t;u++)g[f.codes[u]*y+i.codes[u]].push(u);let d=u=>typeof u=="function",x=u=>typeof u!="object"||u===null,b=(u,p)=>{let N=e[u],E=Q(n.valuesFn,d,u),$=Q(n.valuesFill,x,u)??null,M=f.firsts.map((v,R)=>{let A=g[R*y+p];return A.length===0?$:E!==void 0?E(A.map(O=>N[O])):N[A[0]]});return N instanceof Float64Array&&M.every(v=>v===null||typeof v=="number")?Float64Array.from(M,v=>v===null?NaN:v):M};for(let u of o)if(Q(n.valuesFn,d,u)===void 0&&g.some(p=>p.length>1))throw new Error(`values from '${u}' are not uniquely identified; use valuesFn to summarise them`);let w={};for(let u of a)k(w,u,z(e[u],f.firsts));let c=(u,p)=>o.length===1?m[p]:`${u}${l}${m[p]}`;if(n.namesVary==="slowest")for(let u of h)for(let p of o)k(w,c(p,u),b(p,u));else for(let u of o)for(let p of h)k(w,c(u,p),b(u,p));return w}export{W as IQR,un as aggregate,re as completeCases,pe as cor,he as cov,ve as cummax,Oe as cummin,$e as cumprod,xe as cumsum,Ue as cut,_e as cv,Re as diff,Ye as ecdf,qe as findInterval,Be as fivenum,ye as fromRows,je as geometricMean,He as hist,Fe as kurtosis,We as mad,Ee as mean,Te as meanAD,F as median,ge as merge,Se as modes,De as naOmit,dn as pivotLonger,bn as pivotWider,oe as pretty,Ne as prod,P as quantile,S as range,me as rank,Ie as scale,C as sd,ke as skewness,an as split,de as subset,be as sum,Ce as table,Le as tabulate,on as tapply,we as toRows,Pe as unique,Me as variance,Ae as weightedMean};
@@ -9,13 +9,14 @@
9
9
  // Quantiles use Newton's method starting from Patnaik's (1949) approximation (c χ²_ν, c = (k + 2λ)/(k + λ),
10
10
  // ν = (k + λ)^2/(k + 2λ)).
11
11
  // With a huge λ the mixture is slow and inaccurate far from the centre; there a Chernoff bound decides first whether
12
- // the far tail is below the double range (then it is 0 and the near tail 1).
12
+ // the far tail is below the double range (then it is 0 and the near tail 1). For x λ > 4e18 the density comes from the
13
+ // large-argument expansion of the Bessel function and the distribution function from integrating it numerically.
13
14
  import { dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
14
15
  import { invertContinuous } from "../internal/invert.js";
15
16
  import { dpoisLogDD, mixtureCdf, mixtureCdfBoth, mixtureDensity } from "../internal/poissonMixture.js";
16
17
  import { gammaInc } from "../special/igam.js";
17
18
  import { dpoisRaw } from "../special/loader.js";
18
- import { ddAdd, ddDiv, twoSum } from "../special/dd.js";
19
+ import { ddAdd, ddDiv, twoProd, twoSum } from "../special/dd.js";
19
20
  import { digamma } from "../special/psigamma.js";
20
21
  import { dgamma1, qgamma1 } from "./gamma.js";
21
22
  function gammaKernel(a, y) {
@@ -57,13 +58,9 @@ function validParams(df, ncp) {
57
58
  */
58
59
  function pnchisqBoth(x, df, ncp, lower) {
59
60
  const mu = ncp / 2;
60
- if (mu * (x / 2) > 1e18) {
61
- // x λ is very large (far in the right tail): the peak of the series is too far away, so build the tail from the density (besselAsymptotic)
62
- const lq = upperTailAsymptotic(x, df, ncp);
63
- if (lower)
64
- return { lin: -Math.expm1(lq), log: Math.log1p(-Math.exp(lq)) };
65
- return { lin: Math.exp(lq), log: lq };
66
- }
61
+ // x λ is very large: the peak of the series is too far away, so integrate the density (besselAsymptotic)
62
+ if (mu * (x / 2) > 1e18)
63
+ return besselTails(x, df, ncp, lower);
67
64
  // x so small that x/2 underflows to 0 (the smallest subnormal) is approximated by the smallest positive number
68
65
  const kernel = gammaKernel(df / 2, Math.max(x / 2, Number.MIN_VALUE));
69
66
  const own = mixtureCdfBoth(mu, kernel, lower);
@@ -80,15 +77,6 @@ function pnchisqBoth(x, df, ncp, lower) {
80
77
  }
81
78
  return own;
82
79
  }
83
- /**
84
- * log P[X > x] for very large x. Using the log-derivative of the density f, -(log f)' = s(x),
85
- * P[X > x] = f(x)/s(x) (1 + O(x^-3/2)), s(x) = 1/2 - sqrt(λ/x)/2 - (k - 3)/(4x)
86
- * (f in the form of besselAsymptotic. Used for x λ > 1e18, so the correction is negligible)
87
- */
88
- function upperTailAsymptotic(x, df, ncp) {
89
- const s = 0.5 - Math.sqrt(ncp / x) / 2 - (df - 3) / (4 * x);
90
- return besselAsymptotic(x, df, ncp, true) - Math.log(s);
91
- }
92
80
  function pnchisqRaw(x, df, ncp, lower, log) {
93
81
  const v = pnchisqBoth(x, df, ncp, lower);
94
82
  return log ? v.log : v.lin;
@@ -127,6 +115,21 @@ function dnchisqRaw(x, df, ncp, log) {
127
115
  function besselAsymptotic(x, df, ncp, log) {
128
116
  const nu = df / 2 - 1;
129
117
  const z = Math.sqrt(ncp * x);
118
+ const s = besselSeries(nu, z);
119
+ // -(x + λ)/2 + z = -(sqrt(x) - sqrt(λ))^2 / 2, with sqrt(x) - sqrt(λ) written without cancellation (the difference
120
+ // of the rounded roots carries an error of ulp(sqrt(λ))) and its square in double-double, as in besselTails
121
+ const rl = Math.sqrt(ncp);
122
+ const d = (x - ncp) / (Math.sqrt(x) + rl);
123
+ const [p, pe] = twoProd(d, d);
124
+ const hi = -p / 2;
125
+ // (ν/2) log(x/λ) = ν log(sqrt(x)/sqrt(λ))
126
+ const rest = -Math.LN2 - pe / 2 + nu * Math.log1p(d / rl) - 0.5 * Math.log(2 * Math.PI * z) + Math.log(s);
127
+ if (log)
128
+ return hi + rest;
129
+ return hi > -700 ? Math.exp(hi) * Math.exp(rest) : Math.exp(hi + rest);
130
+ }
131
+ /** Σ_m (-1)^m a_m(ν) / z^m of besselAsymptotic */
132
+ function besselSeries(nu, z) {
130
133
  const mu4 = 4 * nu * nu;
131
134
  let term = 1;
132
135
  let s = 1;
@@ -136,10 +139,102 @@ function besselAsymptotic(x, df, ncp, log) {
136
139
  if (Math.abs(term) < 1e-17 * Math.abs(s))
137
140
  break;
138
141
  }
139
- // -(x + λ)/2 + z = -(sqrt(x) - sqrt(λ))^2 / 2
140
- const d = Math.sqrt(x) - Math.sqrt(ncp);
141
- const lv = -Math.LN2 - (d * d) / 2 + (nu / 2) * Math.log(x / ncp) - 0.5 * Math.log(2 * Math.PI * z) + Math.log(s);
142
- return log ? lv : Math.exp(lv);
142
+ return s;
143
+ }
144
+ /** log(sqrt(2 pi)) */
145
+ const LN_SQRT_2PI = 0.918938533204672741780329736406;
146
+ /**
147
+ * Linear value and log of P[X <= x] (lower) / P[X > x] for very large x λ, by integrating the density of
148
+ * besselAsymptotic. In t = sqrt(x) the density is g(t) = f(t²) 2t, with
149
+ * log g(t) = -(t - sqrt(λ))²/2 + (ν + 1/2) log(t / sqrt(λ)) - log sqrt(2 pi) + log S(t sqrt(λ))
150
+ * (S the series of besselSeries, 1 + O(1/(t sqrt(λ)))): close to a unit normal density whatever λ is (for k = 1 it
151
+ * is φ(t - sqrt(λ)), the term φ(t + sqrt(λ)) of the exact density being negligible). log g is concave (its second
152
+ * derivative is -1 - (ν + 1/2)/t² up to O(1/(t sqrt(λ)))), so g falls on both sides of its mode, the root of
153
+ * t² - sqrt(λ) t - (ν + 1/2) = 0. The tail beyond t0 = sqrt(x) away from the mode is the smaller one, at most about
154
+ * 1/2 (g is symmetric up to O(1/sqrt(λ))); it is integrated from t0 outwards and the other tail is 1 - (that).
155
+ * The integrand is g(t)/g(t0), which starts at 1 and decays monotonically, so the integral has full relative accuracy
156
+ * even far in a tail; log g(t0) is added in log space, with (t0 - sqrt(λ))² in double-double since in a deep tail its
157
+ * rounding would otherwise become the relative error of the probability.
158
+ */
159
+ function besselTails(x, df, ncp, lower) {
160
+ const nu = df / 2 - 1;
161
+ const c = nu + 0.5;
162
+ const rl = Math.sqrt(ncp);
163
+ const t0 = Math.sqrt(x);
164
+ // t0 - sqrt(λ) without cancellation
165
+ const d0 = (x - ncp) / (t0 + rl);
166
+ const mode = (rl + Math.sqrt(Math.max(ncp + 4 * c, 0))) / 2;
167
+ const up = t0 >= mode;
168
+ const dir = up ? 1 : -1;
169
+ const ls0 = Math.log(besselSeries(nu, t0 * rl));
170
+ // log(g(t0 + dir u) / g(t0)), written with the offset h so that it has no cancellation near u = 0
171
+ const integrand = (u) => {
172
+ const h = dir * u;
173
+ return Math.exp((-h * (2 * d0 + h)) / 2 + c * Math.log1p(h / t0) + Math.log(besselSeries(nu, (t0 + h) * rl)) - ls0);
174
+ };
175
+ // Rate at which log g falls at distance u from t0 (the derivative of log g, without the O(1/(t sqrt(λ))) part of S)
176
+ const rate = (u) => -dir * (c / (t0 + dir * u) - (d0 + dir * u));
177
+ // Integrate over intervals of doubling width, starting from about the length over which g falls by e^-1. Since log g
178
+ // is concave, the rest beyond u is at most g(u)/rate(u); stop when that is negligible
179
+ const end = up ? Infinity : t0;
180
+ let w = 1 / (1 + Math.abs(rate(0)));
181
+ let a = 0;
182
+ let sum = 0;
183
+ for (let i = 0; i < 200 && a < end; i++) {
184
+ const b = Math.min(a + w, end);
185
+ sum += kronrodAdaptive(integrand, a, b, sum, 0);
186
+ const r = rate(b);
187
+ if (r > 0 && integrand(b) <= 1e-17 * r * sum)
188
+ break;
189
+ a = b;
190
+ w *= 2;
191
+ }
192
+ const [p, pe] = twoProd(d0, d0);
193
+ const hi = -p / 2;
194
+ const rest = -pe / 2 + c * Math.log1p(d0 / rl) - LN_SQRT_2PI + ls0 + Math.log(sum);
195
+ const tail = hi > -700 ? Math.exp(hi) * Math.exp(rest) : Math.exp(hi + rest);
196
+ if (up !== lower)
197
+ return { lin: tail, log: hi + rest };
198
+ return { lin: 1 - tail, log: Math.log1p(-tail) };
199
+ }
200
+ // Gauss-Kronrod 7-15 rule (QUADPACK, public domain; as in src/integrate/quadpack.ts): Kronrod nodes, from the end of
201
+ // [-1, 1] to the centre, their weights, and the Gauss weights of the odd-numbered nodes
202
+ const GK15_X = [
203
+ 0.991455371120812639206854697526329, 0.949107912342758524526189684047851, 0.864864423359769072789712788640926,
204
+ 0.741531185599394439863864773280788, 0.58608723546769113029414483825873, 0.405845151377397166906606412076961,
205
+ 0.207784955007898467600689403773245, 0,
206
+ ];
207
+ const GK15_WK = [
208
+ 0.02293532201052922496373200805897, 0.063092092629978553290700663189204, 0.104790010322250183839876322541518,
209
+ 0.140653259715525918745189590510238, 0.16900472663926790282658342659855, 0.190350578064785409913256402421014,
210
+ 0.204432940075298892414161999234649, 0.209482141084727828012999174891714,
211
+ ];
212
+ const GK15_WG = [
213
+ 0.129484966168869693270611432679082, 0.27970539148927666790146777142378, 0.381830050505118944950369775488975,
214
+ 0.417959183673469387755102040816327,
215
+ ];
216
+ /**
217
+ * Integral of f over [a, b] by the 15-point Kronrod rule, bisecting while it differs from the 7-point Gauss rule by
218
+ * more than 1e-15 of the total (`total`, the integral accumulated so far, or this part's own value). The difference
219
+ * overestimates the error of the Kronrod value by far, so the result is good to about the rounding of the sum
220
+ */
221
+ function kronrodAdaptive(f, a, b, total, depth) {
222
+ const m = (a + b) / 2;
223
+ const h = (b - a) / 2;
224
+ const fc = f(m);
225
+ let k = GK15_WK[7] * fc;
226
+ let g = GK15_WG[3] * fc;
227
+ for (let j = 0; j < 7; j++) {
228
+ const fs = f(m - h * GK15_X[j]) + f(m + h * GK15_X[j]);
229
+ k += GK15_WK[j] * fs;
230
+ if (j % 2 === 1)
231
+ g += GK15_WG[(j - 1) / 2] * fs;
232
+ }
233
+ k *= h;
234
+ g *= h;
235
+ if (Math.abs(k - g) <= 1e-15 * Math.max(Math.abs(k), total) || depth >= 40)
236
+ return k;
237
+ return kronrodAdaptive(f, a, m, total, depth + 1) + kronrodAdaptive(f, m, b, total, depth + 1);
143
238
  }
144
239
  export function dnchisq1(x, df, ncp, log) {
145
240
  if (Number.isNaN(x) || Number.isNaN(df) || Number.isNaN(ncp))
@@ -248,8 +343,9 @@ export function qnchisq1(p, df, ncp, lowerTail, logP) {
248
343
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
249
344
  const cdf = memoCdf(df, ncp);
250
345
  // If the distribution function at the smallest positive number already passes the target, the answer is 0 (includes the point mass for df = 0)
251
- const atMin = pnchisqRaw(Number.MIN_VALUE, df, ncp, lower, true);
252
- if (lower ? atMin >= logTarget : atMin <= logTarget)
346
+ // (the upper tail there is built from the lower one: the series for the upper tail itself takes seconds for λ = 1e12)
347
+ const atMin = pnchisqRaw(Number.MIN_VALUE, df, ncp, true, lower);
348
+ if (lower ? atMin >= logTarget : Math.log1p(-atMin) <= logTarget)
253
349
  return 0;
254
350
  // Patnaik's approximation as the starting value
255
351
  const c = (df + 2 * ncp) / (df + ncp);
@@ -272,7 +368,9 @@ export function qnchisq1(p, df, ncp, lowerTail, logP) {
272
368
  cdf: (x, l) => cdf(x, l).lin,
273
369
  cdfLog: (x, l) => cdf(x, l).log,
274
370
  pdfLog: (x) => dnchisqRaw(x, df, ncp, true),
275
- x0: Math.min(x0, hi),
371
+ // Start just inside the bracket when the first upper end already passes the target: a start at the end itself
372
+ // falls back to bisection towards 0, through x where the series is slow (seconds for λ = 1e12)
373
+ x0: x0 < hi ? x0 : hi * (1 - 2 ** -26),
276
374
  lo: 0,
277
375
  hi,
278
376
  positive: true,
@@ -16,13 +16,23 @@ const SCALE_STEP = -900;
16
16
  /**
17
17
  * Tables are cached per n (so that quantile searches, or alternating calls with different n, do not rebuild them).
18
18
  * When the total number of entries exceeds CACHE_BUDGET, the oldest are evicted (at most 32 MB in two Float64Arrays).
19
+ * The key is n for the main table and -n for the low table of n (tableValue), so both share the budget.
19
20
  */
20
21
  const cache = new Map();
21
22
  const CACHE_BUDGET = 2 ** 21;
22
23
  let cached = 0;
23
24
  /** Maximum table length (computations needing more throw RangeError; about 512 MB in two Float64Arrays) */
24
25
  const MAX_LEN = 2 ** 25;
25
- /** Build the table of counts for s = 0..J (J at most the end of the lower half, floor(n(n+1)/4)) */
26
+ /**
27
+ * Build the table of counts for s = 0..J (J at most the end of the lower half, floor(n(n+1)/4)).
28
+ *
29
+ * Rescaling by 2^-900 makes the low entries subnormal or 0: each loses up to 2^-1075 (in units of the new scale).
30
+ * What an entry s' holds after element k reaches the final w[s] through the elements k+1..kmax, as many times as
31
+ * there are subsets of them summing to s - s', so the loss reaches w[s] at most 2^(kmax - k) times over. A count at
32
+ * s therefore keeps relative accuracy 2^-60 if c_n(s) >= 2^(S - 1075 + kmax - k + 60) for every rescaling (to scale
33
+ * S after element k); that bound is minTrusted. Being below the smallest normal number is not enough: for n = 2000
34
+ * the entries around s = 95000 lost digits (relative 1e-7) through the entries below them that were lost.
35
+ */
26
36
  function buildTable(n, J) {
27
37
  if (J + 1 > MAX_LEN) {
28
38
  throw new RangeError(`signrank: n = ${n} needs too large a table (${J + 1} entries)`);
@@ -30,6 +40,8 @@ function buildTable(n, J) {
30
40
  const w = new Float64Array(J + 1);
31
41
  w[0] = 1;
32
42
  let scale = 0;
43
+ // log2 of the smallest trusted true count (see above)
44
+ let trustLog2 = -Infinity;
33
45
  // Elements k > J do not contribute to sums s <= J
34
46
  const kmax = Math.min(n, J);
35
47
  for (let k = 1; k <= kmax; k++) {
@@ -42,6 +54,7 @@ function buildTable(n, J) {
42
54
  for (let s = 0; s <= J; s++)
43
55
  w[s] *= f;
44
56
  scale -= SCALE_STEP;
57
+ trustLog2 = Math.max(trustLog2, scale - 1015 + kmax - k);
45
58
  }
46
59
  }
47
60
  // Cumulative sum (with Kahan compensation)
@@ -55,35 +68,60 @@ function buildTable(n, J) {
55
68
  hi = t;
56
69
  cum[s] = hi;
57
70
  }
58
- return { n, len: J + 1, count: w, cum, scale };
71
+ return { n, len: J + 1, count: w, cum, scale, minTrusted: 2 ** (trustLog2 - scale) };
59
72
  }
60
- /** Return a table for n usable for s <= J */
61
- function table(n, J) {
62
- const old = cache.get(n);
73
+ /** Return a table for n usable for s <= J (with low, the low table of n; see lowValue) */
74
+ function table(n, J, low = false) {
75
+ const key = low ? -n : n;
76
+ const old = cache.get(key);
63
77
  if (old !== undefined && old.len > J) {
64
78
  // Move to the end as most recently used
65
- cache.delete(n);
66
- cache.set(n, old);
79
+ cache.delete(key);
80
+ cache.set(key, old);
67
81
  return old;
68
82
  }
69
83
  const half = Math.floor((n * (n + 1)) / 4);
70
84
  // Growing a little at a time would cause repeated rebuilds, so double the size
71
85
  const want = Math.min(half, Math.max(J, old === undefined ? 0 : 2 * old.len));
72
- const t = buildTable(n, want);
86
+ return store(key, buildTable(n, want), old);
87
+ }
88
+ /** Put t in the cache under key (replacing old) and evict the oldest tables beyond the budget */
89
+ function store(key, t, old) {
73
90
  if (old !== undefined) {
74
- cache.delete(n);
91
+ cache.delete(key);
75
92
  cached -= old.len;
76
93
  }
77
- cache.set(n, t);
94
+ cache.set(key, t);
78
95
  cached += t.len;
79
- for (const [key, v] of cache) {
80
- if (cached <= CACHE_BUDGET || key === n)
96
+ for (const [k, v] of cache) {
97
+ if (cached <= CACHE_BUDGET || k === key)
81
98
  break;
82
- cache.delete(key);
99
+ cache.delete(k);
83
100
  cached -= v.len;
84
101
  }
85
102
  return t;
86
103
  }
104
+ /**
105
+ * The value at s of the count (cum false) or cumulative count (cum true) for n, with the table it is scaled by.
106
+ * A table built far beyond s has been rescaled for its large entries, and its low entries have lost digits (c_n(0) = 1
107
+ * becomes 2^-1800 for n = 2000 and underflows), so a value the bound of buildTable does not cover is read from the
108
+ * low table of n instead, built only as far as needed. A table built up to J = s is exact at s: s is its largest
109
+ * entry, and rescaling keeps the largest entry at least 1 (every count c_n(s) for 0 <= s <= n(n+1)/2 is at least 1).
110
+ */
111
+ function tableValue(n, s, cum) {
112
+ const trusted = (t, v) => s === t.len - 1 || v >= (cum ? (s + 1) * t.minTrusted : t.minTrusted);
113
+ let t = table(n, s);
114
+ let v = (cum ? t.cum : t.count)[s];
115
+ if (trusted(t, v))
116
+ return [v, t];
117
+ t = table(n, s, true);
118
+ v = (cum ? t.cum : t.count)[s];
119
+ if (trusted(t, v))
120
+ return [v, t];
121
+ // The low table (grown by doubling) was rescaled too far for s: rebuild it exactly up to s
122
+ t = store(-n, buildTable(n, s), cache.get(-n));
123
+ return [(cum ? t.cum : t.count)[s], t];
124
+ }
87
125
  /** Convert the table value v (scale 2^-scale) to the probability v 2^(scale - n) (underflow only at the final step) */
88
126
  function toProb(v, t, log) {
89
127
  const e = t.scale - t.n;
@@ -92,7 +130,22 @@ function toProb(v, t, log) {
92
130
  if (!log)
93
131
  return p;
94
132
  // log(v) + e log 2 loses digits since both terms are large, so use log(p) if the probability is a normal number
95
- return p >= 1e-300 ? Math.log(p) : Math.log(v) + e * Math.LN2;
133
+ if (p >= 1e-300)
134
+ return Math.log(p);
135
+ // Otherwise split v into its significand m in [1, 2) and exponent, so that the result does not depend on the
136
+ // scale of the table (the same count read from tables of different scale gives the same bits)
137
+ let k = Math.floor(Math.log2(v));
138
+ const k1 = Math.trunc(k / 2);
139
+ let m = v * 2 ** -k1 * 2 ** -(k - k1);
140
+ if (m >= 2) {
141
+ m /= 2;
142
+ k++;
143
+ }
144
+ else if (m < 1) {
145
+ m *= 2;
146
+ k--;
147
+ }
148
+ return Math.log(m) + (k + e) * Math.LN2;
96
149
  }
97
150
  /** Check and round n. NaN if invalid */
98
151
  function signrankN(n) {
@@ -114,8 +167,8 @@ export function dsignrank1(x, n, log) {
114
167
  if (x < 0 || x > total)
115
168
  return d0(log);
116
169
  const s = Math.min(x, total - x);
117
- const t = table(n, s);
118
- return toProb(t.count[s], t, log);
170
+ const [v, t] = tableValue(n, s, false);
171
+ return toProb(v, t, log);
119
172
  }
120
173
  /** P[V <= x] (lower) / P[V > x] (0 <= x < total, x an integer) */
121
174
  function psignrankRaw(x, n, lowerTail, logP) {
@@ -127,11 +180,11 @@ function psignrankRaw(x, n, lowerTail, logP) {
127
180
  const direct = lowerTail ? lowerIdx : upperIdx;
128
181
  const other = lowerTail ? upperIdx : lowerIdx;
129
182
  if (direct <= other) {
130
- const t = table(n, direct);
131
- return toProb(t.cum[direct], t, logP);
183
+ const [c, t] = tableValue(n, direct, true);
184
+ return toProb(c, t, logP);
132
185
  }
133
- const t = table(n, other);
134
- const v = toProb(t.cum[other], t, false);
186
+ const [c, t] = tableValue(n, other, true);
187
+ const v = toProb(c, t, false);
135
188
  return logP ? Math.log1p(-v) : 1 - v;
136
189
  }
137
190
  export function psignrank1(q, n, lowerTail, logP) {