@numero-uno-jpn/rstats 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.ja.md +17 -8
  3. package/README.md +17 -8
  4. package/dist/chunks/{chunk-CQNVEA22.js → chunk-6JRESWVF.js} +2 -2
  5. package/dist/chunks/chunk-7CPM3M6Q.js +2 -0
  6. package/dist/chunks/chunk-7PSGKKOP.js +2 -0
  7. package/dist/chunks/{chunk-4AQNVF3Z.js → chunk-7T74KLE5.js} +2 -2
  8. package/dist/chunks/{chunk-F44XUHWI.js → chunk-A76XBA3D.js} +1 -1
  9. package/dist/chunks/{chunk-VG67L3JA.js → chunk-ACE64PMM.js} +2 -2
  10. package/dist/chunks/chunk-DCGBYO44.js +2 -0
  11. package/dist/chunks/chunk-DWNGNTS6.js +2 -0
  12. package/dist/chunks/{chunk-SVWU5T7C.js → chunk-FBDZ6B2G.js} +2 -2
  13. package/dist/chunks/chunk-IBJ7RI44.js +2 -0
  14. package/dist/chunks/{chunk-4GNJEYXR.js → chunk-IGSR4GIF.js} +2 -2
  15. package/dist/chunks/{chunk-BJHBYEEU.js → chunk-NTETWLP3.js} +1 -1
  16. package/dist/chunks/{chunk-2IAT6MT2.js → chunk-Q4JF4QHS.js} +2 -2
  17. package/dist/chunks/{chunk-JGFUZKLJ.js → chunk-RZIWVCHO.js} +2 -2
  18. package/dist/chunks/chunk-SD7ML5PE.js +2 -0
  19. package/dist/chunks/{chunk-3AKA4KEL.js → chunk-SZ357HRC.js} +1 -1
  20. package/dist/chunks/{chunk-SLSDFIW2.js → chunk-WM33ADZV.js} +2 -2
  21. package/dist/chunks/{chunk-MEMYFTYS.js → chunk-XCAMWVNO.js} +1 -1
  22. package/dist/chunks/chunk-YQLEXH2Y.js +3 -0
  23. package/dist/chunks/chunk-YTV3RFCA.js +2 -0
  24. package/dist/chunks/{chunk-BSOUJPDF.js → chunk-ZUESNU7W.js} +2 -2
  25. package/dist/descriptive.js +2 -2
  26. package/dist/distributions.js +2 -2
  27. package/dist/entries/mixed.d.ts +3 -1
  28. package/dist/entries/mixed.js +4 -1
  29. package/dist/internal/fround.d.ts +12 -0
  30. package/dist/internal/fround.js +89 -0
  31. package/dist/linalg.js +2 -2
  32. package/dist/mixed.js +4 -3
  33. package/dist/models/lmer.d.ts +37 -4
  34. package/dist/models/lmer.js +18 -1
  35. package/dist/models/lmerAnova.d.ts +138 -0
  36. package/dist/models/lmerAnova.js +134 -0
  37. package/dist/models/lmerHypotheses.d.ts +105 -0
  38. package/dist/models/lmerHypotheses.js +303 -0
  39. package/dist/models/lmerTest.d.ts +233 -0
  40. package/dist/models/lmerTest.js +306 -0
  41. package/dist/models/mixedDerivatives.d.ts +27 -0
  42. package/dist/models/mixedDerivatives.js +342 -0
  43. package/dist/models/mixedDeviance.d.ts +112 -0
  44. package/dist/models/mixedDeviance.js +216 -86
  45. package/dist/models/mixedStructure.d.ts +5 -3
  46. package/dist/models/modelMatrix.d.ts +10 -3
  47. package/dist/models/modelMatrix.js +23 -2
  48. package/dist/numerics.js +2 -2
  49. package/dist/rstats.js +13 -13
  50. package/dist/special.js +2 -2
  51. package/dist/tests.js +11 -12
  52. package/llms.txt +6 -1
  53. package/package.json +1 -1
  54. package/dist/chunks/chunk-22SXZNR6.js +0 -2
  55. package/dist/chunks/chunk-AGRKZXLG.js +0 -2
  56. package/dist/chunks/chunk-N3FV6H3C.js +0 -2
  57. package/dist/chunks/chunk-NRV3BH7I.js +0 -2
  58. package/dist/chunks/chunk-RTWLZPPG.js +0 -2
  59. package/dist/chunks/chunk-VWGJYRE6.js +0 -2
package/dist/mixed.js CHANGED
@@ -1,3 +1,4 @@
1
- /*! rStats.js 0.13.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{a as lt}from"./chunks/chunk-RTWLZPPG.js";import{h as bt,u as At,w as xt}from"./chunks/chunk-VWGJYRE6.js";import{a as gt,c as dt,d as ct,f as wt,g as at}from"./chunks/chunk-BSOUJPDF.js";import{b as vt}from"./chunks/chunk-JGFUZKLJ.js";import{b as st}from"./chunks/chunk-3AKA4KEL.js";var Mt=1,kt=new WeakMap;function Ct(r){let n=kt.get(r);if(n!==void 0)return n;let s=r.y.length,l=r.xColNames.length,o=r.q,i=r.terms.length,t=r.terms.reduce((f,M)=>f+M.nLevels,0),e=new Int32Array(t+1),m=new Int32Array(t),b=[],p=[],j=0;r.terms.forEach((f,M)=>{let P=f.columns.length;b.push(j),p.push(P);for(let N=0;N<f.nLevels;N++,j++)e[j]=f.zOffset+N*P,m[j]=M}),e[t]=o;let _=r.terms.map((f,M)=>{let P=p[M],N=new Int32Array(P*P).fill(-1);for(let{row:Y,col:Z,theta:J}of r.lambda)Z>=f.zOffset&&Z<f.zOffset+P&&(N[Y-f.zOffset+(Z-f.zOffset)*P]=J);return N}),k=r.terms.map(f=>r.groups[f.group].codes),u=new Int32Array(s+1);for(let f=0;f<s;f++){let M=0;for(let P of r.terms)for(let N of P.matrix[f])N!==0&&M++;u[f+1]=u[f]+M}let I=u,C=I[s],$=new Int32Array(C),y=new Float64Array(C);{let f=0;for(let M=0;M<s;M++)r.terms.forEach((P,N)=>{let Y=P.zOffset+k[N][M]*p[N];P.matrix[M].forEach((Z,J)=>{Z!==0&&($[f]=Y+J,y[f++]=Z)})})}let A=new Map,x=[],z=[],D=(f,M)=>{let P=M*t+f,N=A.get(P);return N===void 0&&(N=x.length,A.set(P,N),x.push(f),z.push(M)),N};for(let f=0;f<t;f++)D(f,f);let S=new Int32Array(i),G=i*(i+1)/2,H=new Int32Array(s*G);for(let f=0;f<s;f++){for(let M=0;M<i;M++)S[M]=b[M]+k[M][f];for(let M=0;M<i;M++)for(let P=0;P<=M;P++)H[f*G+M*(M+1)/2+P]=D(S[M],S[P])}let U=x.length,g=Array.from({length:U},(f,M)=>M).sort((f,M)=>z[f]-z[M]||x[f]-x[M]),T=new Int32Array(U);g.forEach((f,M)=>T[f]=M);let E=new Int32Array(t+1),V=new Int32Array(U),L=new Int32Array(U+1);g.forEach((f,M)=>{V[M]=x[f],E[z[f]+1]++;let P=p[m[x[f]]]*p[m[z[f]]];L[M+1]=L[M]+P});for(let f=0;f<t;f++)E[f+1]+=E[f];let B=new Float64Array(L[U]),K=new Float64Array(o*l),X=new Float64Array(o),c=new Float64Array(l);for(let f=0;f<s;f++){let M=r.x[f],P=r.y[f];for(let N=0;N<i;N++){let Y=r.terms[N].matrix[f],Z=p[N];for(let J=0;J<=N;J++){let Nt=r.terms[J].matrix[f],jt=p[J],Lt=T[H[f*G+N*(N+1)/2+J]],qt=L[Lt];for(let ot=0;ot<jt;ot++){let pt=Nt[ot];if(pt!==0)for(let rt=0;rt<Z;rt++)B[qt+rt+ot*Z]+=Y[rt]*pt}}}for(let N=I[f];N<I[f+1];N++){let Y=$[N],Z=y[N];for(let J=0;J<l;J++)K[Y+J*o]+=Z*M[J];X[Y]+=Z*P}for(let N=0;N<l;N++)c[N]+=M[N]*P}let a=new Array(t),O=Array.from({length:t},()=>[]),h=new Int32Array(t).fill(-1);for(let f=0;f<t;f++){let M=[],P=Y=>{Y!==f&&h[Y]!==f&&(h[Y]=f,M.push(Y))};for(let Y=E[f]+1;Y<E[f+1];Y++)P(V[Y]);for(let Y of O[f])for(let Z of a[Y])P(Z);let N=Int32Array.from(M).sort();a[f]=N,N.length>0&&O[N[0]].push(f)}let v=new Int32Array(U);{let f=new Int32Array(t);for(let M=0;M<t;M++){let P=0;for(let N of a[M])f[N]=P,P+=e[N+1]-e[N];for(let N=E[M]+1;N<E[M+1];N++)v[N]=f[V[N]]}}let F=new Int32Array(o+1);for(let f=0;f<t;f++){let M=0;for(let P of a[f])M+=e[P+1]-e[P];for(let P=e[f];P<e[f+1];P++)F[P+1]=F[P]+(e[f+1]-P)+M}let R=new Int32Array(F[o]),w=new Int32Array(o+1);for(let f=0;f<t;f++)for(let M=e[f];M<e[f+1];M++){let P=F[M];for(let N=M;N<e[f+1];N++)R[P++]=N;for(let N of a[f])for(let Y=e[N];Y<e[N+1];Y++)R[P++]=Y}for(let f=0;f<o;f++)for(let M=F[f]+1;M<F[f+1];M++)w[R[M]+1]++;for(let f=0;f<o;f++)w[f+1]+=w[f];let d=w.slice(),q=w.slice(0,o),W=new Int32Array(d[o]),tt=new Int32Array(d[o]);for(let f=0;f<o;f++)for(let M=F[f]+1;M<F[f+1];M++){let P=q[R[M]]++;W[P]=f,tt[P]=M}let et={n:s,p:l,q:o,nGroups:t,groupStart:e,groupTerm:m,termNc:p,termTheta:_,blockStart:E,blockRow:V,blockValueStart:L,zz:B,zx:K,zy:X,xy:c,rowStart:I,rowCols:$,rowValues:y,colStart:F,colRows:R,rowListStart:d,rowListCol:W,rowListPos:tt,blockPatternOffset:v};return kt.set(r,et),et}function _t(r,n){return r.termTheta.map(s=>Float64Array.from(s,l=>l<0?0:n[l]))}function ft(r,n,s){let l=new Float64Array(r.q);for(let o=0;o<r.nGroups;o++){let i=r.groupTerm[o],t=r.termNc[i],e=n[i],m=r.groupStart[o];for(let b=0;b<t;b++){let p=s[m+b];if(p!==0)for(let j=b;j<t;j++)l[m+j]+=e[j+b*t]*p}}return l}function nt(r,n,s,l=1){let o=r.q,i=new Float64Array(o*l);for(let t=0;t<r.nGroups;t++){let e=r.groupTerm[t],m=r.termNc[e],b=n[e],p=r.groupStart[t];for(let j=0;j<l;j++){let _=p+j*o;for(let k=0;k<m;k++){let u=0;for(let I=k;I<m;I++)u+=b[I+k*m]*s[_+I];i[_+k]=u}}}return i}function Vt(r,n){let s=new Float64Array(r.zz.length),l=new Float64Array(64);for(let o=0;o<r.nGroups;o++){let i=r.groupTerm[o],t=r.termNc[i],e=n[i];for(let m=r.blockStart[o];m<r.blockStart[o+1];m++){let b=r.groupTerm[r.blockRow[m]],p=r.termNc[b],j=n[b],_=r.blockValueStart[m];if(p===1&&t===1)s[_]=j[0]*r.zz[_]*e[0];else{let k=l.length>=p*t?l:new Float64Array(p*t);for(let u=0;u<t;u++)for(let I=0;I<p;I++){let C=0;for(let $=u;$<t;$++)C+=r.zz[_+I+$*p]*e[$+u*t];k[I+u*p]=C}for(let u=0;u<t;u++)for(let I=0;I<p;I++){let C=0;for(let $=I;$<p;$++)C+=j[$+I*p]*k[$+u*p];s[_+I+u*p]=C}}if(m===r.blockStart[o])for(let k=0;k<t;k++)s[_+k+k*t]+=1}}return s}function Pt(r,n){let{q:s,colStart:l,colRows:o,rowListStart:i,rowListCol:t,rowListPos:e}=r,m=new Float64Array(o.length),b=new Float64Array(s);for(let p=0;p<r.nGroups;p++){let j=r.termNc[r.groupTerm[p]],_=r.groupStart[p];for(let k=0;k<j;k++){let u=_+k;for(let y=r.blockStart[p];y<r.blockStart[p+1];y++){let A=r.blockRow[y],x=r.termNc[r.groupTerm[A]],z=r.blockValueStart[y]+k*x,D=r.groupStart[A];for(let S=A===p?k:0;S<x;S++)b[D+S]=n[z+S]}for(let y=i[u];y<i[u+1];y++){let A=t[y],x=e[y],z=m[x];if(z===0)continue;let D=l[A+1];for(let S=x;S<D;S++)b[o[S]]-=m[S]*z}let I=b[u];if(!(I>0))throw new Error("the penalised least-squares matrix is not positive definite");let C=Math.sqrt(I),$=l[u];m[$]=C,b[u]=0;for(let y=$+1;y<l[u+1];y++){let A=o[y];m[y]=b[A]/C,b[A]=0}}}return m}function it(r,n,s,l=0){let{q:o,colStart:i,colRows:t}=r;for(let e=0;e<o;e++){let m=i[e],b=s[l+e]/=n[m];if(b!==0)for(let p=m+1;p<i[e+1];p++)s[l+t[p]]-=n[p]*b}}function mt(r,n,s,l=0){let{q:o,colStart:i,colRows:t}=r;for(let e=o-1;e>=0;e--){let m=i[e],b=s[l+e];for(let p=m+1;p<i[e+1];p++)b-=n[p]*s[l+t[p]];s[l+e]=b/n[m]}}function Dt(r,n,s){for(let l=0;l<n;l++){let o=l*n,i=s[l];for(let t=0;t<l;t++)i-=r[t+o]*s[t];s[l]=i/r[l+o]}}function Gt(r,n,s){for(let l=n-1;l>=0;l--){let o=s[l]/=r[l+l*n],i=l*n;for(let t=0;t<l;t++)s[t]-=r[t+i]*o}}function $t(r,n){let s=r.slice();for(let l=0;l<n;l++)for(let o=l+1;o<n;o++)s[o+l*n]=0;xt({nrow:n,ncol:n,data:s});for(let l=0;l<n;l++)for(let o=l+1;o<n;o++)s[o+l*n]=s[l+o*n];return s}function ut(r,n,s,l={}){if(n.length!==r.theta.length)throw new RangeError(`theta must have length ${r.theta.length}, not ${n.length}`);if(n.some(a=>!Number.isFinite(a)))throw new RangeError("theta must be finite");let o=Ct(r),{n:i,p:t,q:e}=o,m=_t(o,n),b=Pt(o,Vt(o,m)),p=a=>{let O=new Float64Array(i);for(let h=0;h<i;h++){let v=0;for(let F=o.rowStart[h];F<o.rowStart[h+1];F++)v+=o.rowValues[F]*a[o.rowCols[F]];O[h]=v}return O},j=a=>{let O=new Float64Array(e);for(let h=0;h<i;h++){let v=a[h];for(let F=o.rowStart[h];F<o.rowStart[h+1];F++)O[o.rowCols[F]]+=o.rowValues[F]*v}return O},_=a=>{it(o,b,a),mt(o,b,a)},k=nt(o,m,o.zx,t);for(let a=0;a<t;a++)it(o,b,k,a*e);let u=[],I=[];for(let a=0;a<t;a++){let O=k.slice(a*e,(a+1)*e);mt(o,b,O);let h=Float64Array.from(r.x,R=>R[a]),v=()=>{let R=p(ft(o,m,O));return h.map((w,d)=>w-R[d])},F=v();for(let R=0;R<Mt;R++){let w=nt(o,m,j(F));for(let d=0;d<e;d++)w[d]-=O[d];_(w);for(let d=0;d<e;d++)O[d]+=w[d];F=v()}u.push(F),I.push(O)}let C=new Float64Array(t*t);for(let a=0;a<t;a++)for(let O=a;O<t;O++){let h=0,v=u[a],F=u[O];for(let d=0;d<i;d++)h+=v[d]*F[d];let R=I[a],w=I[O];for(let d=0;d<e;d++)h+=R[d]*w[d];C[a+O*t]=h,C[O+a*t]=h}let $={nrow:t,ncol:t,data:C};if(t>0&&At($)>0)throw new Error("the fixed-effects matrix of the penalised least squares is not positive definite");let y=(a,O)=>{it(o,b,a);for(let h=0;h<t;h++){let v=O[h];for(let F=0;F<e;F++)v-=k[F+h*e]*a[F];O[h]=v}Dt(C,t,O),Gt(C,t,O);for(let h=0;h<t;h++){let v=O[h];for(let F=0;F<e;F++)a[F]-=k[F+h*e]*v}mt(o,b,a)},A=(a,O)=>{let h=p(O),v=new Float64Array(i);for(let F=0;F<i;F++){let R=r.x[F],w=h[F];for(let d=0;d<t;d++)w+=R[d]*a[d];v[F]=r.y[F]-w}return v},x=nt(o,m,o.zy),z=Float64Array.from(o.xy);y(x,z);let D=ft(o,m,x),S=A(z,D);for(let a=0;a<Mt;a++){let O=nt(o,m,j(S));for(let v=0;v<e;v++)O[v]-=x[v];let h=new Float64Array(t);for(let v=0;v<i;v++){let F=r.x[v],R=S[v];for(let w=0;w<t;w++)h[w]+=F[w]*R}y(O,h);for(let v=0;v<e;v++)x[v]+=O[v];for(let v=0;v<t;v++)z[v]+=h[v];D=ft(o,m,x),S=A(z,D)}let G=Array.from(z),H=Array.from(x),U=Array.from(D),g=0;for(let a of S)g+=a*a;let T=0;for(let a of H)T+=a*a;let E=g+T,V=0;for(let a=0;a<e;a++)V+=Math.log(b[o.colStart[a]]);V*=2;let L=0;for(let a=0;a<t;a++)L+=Math.log(C[a+a*t]);L*=2;let B=s?i-t:i,X={deviance:(s?V+L:V)+B*(1+Math.log(2*Math.PI*E/B)),beta:G,u:H,b:U,rss:g,ussq:T,prss:E,logDetL:V,logDetRX:L},c=l.gradient===!0||l.rxInverse===!0?$t(C,t):void 0;return l.rxInverse===!0&&(X.rxInverse=Array.from({length:t},(a,O)=>Array.from({length:t},(h,v)=>c[O+v*t]))),l.gradient===!0&&(X.gradient=Bt(r,o,m,b,n,s,{res:S,uv:x,prss:E,ws:I,xResiduals:u,sInverse:c})),X}function Ut(r,n){let{q:s,colStart:l,colRows:o}=r,i=new Float64Array(n.length),t=new Int32Array(s).fill(-1),e=new Float64Array(s),m=new Float64Array(s);for(let b=s-1;b>=0;b--){let p=l[b],j=l[b+1];for(let u=p+1;u<j;u++){let I=o[u];t[I]=b,e[I]=n[u],m[I]=0}for(let u=p+1;u<j;u++){let I=o[u],C=n[u],$=l[I],y=i[$]*C;for(let A=$+1;A<l[I+1];A++){let x=o[A];if(t[x]!==b)continue;let z=i[A];m[x]+=z*C,y+=z*e[x]}m[I]+=y}let _=n[p],k=1/_;for(let u=p+1;u<j;u++){let I=-m[o[u]]/_;i[u]=I,k-=n[u]*I}i[p]=k/_}return i}function Bt(r,n,s,l,o,i,{res:t,uv:e,prss:m,ws:b,xResiduals:p,sInverse:j}){let{n:_,p:k,q:u,colStart:I,zz:C}=n,$=Ut(n,l),y=n.termNc.map(g=>new Float64Array(g*g)),A=new Float64Array(16),x=new Float64Array(16);for(let g=0;g<n.nGroups;g++){let T=n.groupTerm[g],E=n.termNc[T],V=s[T],L=n.groupStart[g];for(let B=n.blockStart[g];B<n.blockStart[g+1];B++){let K=n.blockRow[B],X=n.groupTerm[K],c=n.termNc[X],a=s[X],O=n.blockValueStart[B];if(E===1&&c===1){let R=K===g?I[L]:I[L]+1+n.blockPatternOffset[B],w=$[R]*C[O];y[T][0]+=w*a[0],K!==g&&(y[X][0]+=w*V[0]);continue}let h=c*E;A.length<h&&(A=new Float64Array(h),x=new Float64Array(Math.max(h,c*c,E*E)));for(let R=0;R<E;R++){let w=I[L+R];if(K===g)for(let d=R;d<c;d++){let q=$[w+d-R];A[d+R*c]=q,A[R+d*c]=q}else{let d=w+(E-R)+n.blockPatternOffset[B];for(let q=0;q<c;q++)A[q+R*c]=$[d+q]}}for(let R=0;R<E;R++)for(let w=0;w<c;w++){let d=0;for(let q=w;q<c;q++)d+=a[q+w*c]*C[O+q+R*c];x[w+R*c]=d}let v=y[T];for(let R=0;R<E;R++)for(let w=0;w<E;w++){let d=0;for(let q=0;q<c;q++)d+=A[q+R*c]*x[q+w*c];v[R+w*E]+=d}if(K===g)continue;for(let R=0;R<c;R++)for(let w=0;w<E;w++){let d=0;for(let q=w;q<E;q++)d+=V[q+w*E]*C[O+R+q*c];x[w+R*E]=d}let F=y[X];for(let R=0;R<c;R++)for(let w=0;w<c;w++){let d=0;for(let q=0;q<E;q++)d+=A[R+q*c]*x[q+w*E];F[R+w*c]+=d}}}let z=new Array(o.length).fill(0);n.termTheta.forEach((g,T)=>{let E=n.termNc[T];for(let V=0;V<E;V++)for(let L=V;L<E;L++)z[g[L+V*E]]+=2*y[T][V+L*E]});let D=new Float64Array(u);for(let g=0;g<_;g++){let T=t[g];for(let E=n.rowStart[g];E<n.rowStart[g+1];E++)D[n.rowCols[E]]+=n.rowValues[E]*T}let S,G;if(i&&k>0){S=new Float64Array(u*k);for(let g=0;g<k;g++)for(let T=0;T<k;T++){let E=j[T+g*k],V=b[T];for(let L=0;L<u;L++)S[L+g*u]+=V[L]*E}G=new Float64Array(k*u);for(let g=0;g<_;g++)for(let T=n.rowStart[g];T<n.rowStart[g+1];T++){let E=n.rowCols[T],V=n.rowValues[T];for(let L=0;L<k;L++)G[L+E*k]+=p[L][g]*V}}let U=2*(i?_-k:_)/m;for(let{row:g,col:T,theta:E}of r.lambda){let V=0;if(S!==void 0&&G!==void 0)for(let L=0;L<k;L++)V+=S[T+L*u]*G[L+g*k];z[E]-=2*V+U*D[g]*e[T]}return z}function Xt(r){let n=[],s=e=>{e.type==="var"?n.includes(e.name)||n.push(e.name):e.type==="binary"?(s(e.left),e.op!=="^"&&s(e.right)):(e.type==="unary"||e.type==="paren"||e.type==="Error")&&s(e.arg)};s(r);let{terms:l}=wt(r,e=>n.indexOf(e),[]);if(l.length===0)throw new SyntaxError(`invalid formula: no grouping factor in '${ct(r)}'`);let o=l.map((e,m)=>[e,m]).sort((e,m)=>e[0].length-m[0].length||e[1]-m[1]).map(([e])=>e.map(m=>n[m])),i=!1,t=e=>{e.type==="binary"?(e.op==="/"&&(i=!0),t(e.left),t(e.right)):(e.type==="unary"||e.type==="paren"||e.type==="Error")&&t(e.arg)};return t(r),i&&(o=o.map(e=>[...e].reverse()).reverse()),o}function Ht(r){if(r.kind==="factor")return vt(r);let n=[...new Set(r.values)].sort((o,i)=>o-i),s=[],l=new Map;for(let o of n){let i=st(o);l.has(i)||(l.set(i,s.length),s.push(i))}return{levels:s,codes:r.values.map(o=>l.get(st(o)))}}function yt(r,n,s={}){let l=gt(r,!1,!0);if(l.response===void 0)throw new TypeError("the formula has no response");let{fixed:o,bars:i}=dt(l.rhs);if(typeof n!="object"||n===null)throw new TypeError("data must be an object of columns");let t={...s.levels===void 0?{}:{levels:s.levels},dropUnusedLevels:!0},e=o??{type:"num",value:1,text:"1"},m=s.contrasts===void 0?{}:{contrasts:s.contrasts,contrastVariables:at({response:l.response,rhs:e},Object.keys(n)).variables},b=lt(l,n,{...t,...m},e),{frame:p}=b,j=p.rows.length;if(j===0)throw new RangeError("0 (non-NA) cases");if(i.length===0)throw new Error("No random effects terms specified in formula");let _=b.terms.variables,k=[];for(let c of i){let a=[c.lhs];if(c.double){let h=at(l,Object.keys(n),c.lhs);a=h.intercept?[{type:"num",value:1,text:"1"}]:[];for(let v of h.terms){let F=v.map(R=>({type:"var",name:_[R]})).reduce((R,w)=>({type:"binary",op:":",left:R,right:w}));a.push({type:"binary",op:"+",left:{type:"num",value:0,text:"0"},right:F})}}let O=Xt(c.group);for(let h of a)for(let v of O)k.push({lhs:h,groupVariables:v})}let u=new Map,I=c=>{let a=c.join(":"),O=u.get(a);if(O!==void 0)return O;let h=c.map(F=>Ht(p.variables[_.indexOf(F)])),v;if(h.length===1)v=h[0];else{let F=new Map;for(let d=0;d<j;d++){let q=h.map(W=>W.codes[d]);F.set(q.join(","),q)}let R=[...F.values()].sort((d,q)=>{for(let W=0;W<d.length;W++)if(d[W]!==q[W])return d[W]-q[W];return 0}),w=new Map(R.map((d,q)=>[d.join(","),q]));v={levels:R.map(d=>d.map((q,W)=>h[W].levels[q]).join(":")),codes:Array.from({length:j},(d,q)=>w.get(h.map(W=>W.codes[q]).join(",")))}}return u.set(a,v),v},C=k.map(c=>({...c,name:c.groupVariables.join(":"),factor:I(c.groupVariables)})),$=C;C.some((c,a)=>a>0&&c.factor.levels.length>C[a-1].factor.levels.length)&&($=C.map((c,a)=>[c,a]).sort((c,a)=>c[0].factor.levels.length-a[0].factor.levels.length||c[1]-a[1]).map(([c])=>c).reverse());let y=[],A=[],x=0,z=0;for(let c of $){let a=y.findIndex(F=>F.name===c.name);a<0&&(a=y.length,y.push({name:c.name,levels:c.factor.levels,codes:c.factor.codes}));let O=lt(l,n,t,c.lhs),h=O.colNames.length,v=c.factor.levels.length;A.push({label:`${ct(c.lhs)} | ${c.name}`,group:a,columns:O.colNames,matrix:O.x,nLevels:v,zOffset:x,thetaOffset:z}),x+=v*h,z+=h*(h+1)/2}if(y.some(c=>c.levels.length<2))throw new RangeError("grouping factors must have > 1 sampled level");let D=y.filter(c=>c.levels.length>=j).map(c=>c.name);if(D.length>0)throw new RangeError(`number of levels of each grouping factor must be < number of observations (problems: ${D.join(", ")})`);for(let c of A){let a=c.nLevels*c.columns.length;if(j<=a)throw new RangeError(`number of observations (=${j}) <= number of random effects (=${a}) for term (${c.label}); the random-effects parameters and the residual variance (or scale parameter) are probably unidentifiable`)}let S=[],G=[],H=[],U=[],g=[];for(let c of A){let{levels:a,codes:O}=y[c.group],h=c.columns.length,v=Array.from({length:a.length*h},()=>({rows:[],values:[]}));for(let w=0;w<j;w++){let d=c.matrix[w],q=O[w]*h;for(let W=0;W<h;W++){let tt=d[W];if(tt===0)continue;let et=v[q+W];et.rows.push(w),et.values.push(tt)}}for(let w=0;w<a.length;w++)for(let d=0;d<h;d++)S.push(v[w*h+d]),G.push(a[w]);let F=Array.from({length:h},()=>new Array(h).fill(-1)),R=c.thetaOffset;for(let w=0;w<h;w++)for(let d=w;d<h;d++)F[d][w]=R++,H.push(d===w?1:0),U.push(d===w?0:-1/0);for(let w=0;w<c.nLevels;w++){let d=c.zOffset+w*h;for(let q=0;q<h;q++)for(let W=q;W<h;W++)g.push({row:d+W,col:d+q,theta:F[W][q]})}}let T=[],E=b.x,V=b.colNames;if(V.length>0){let c=bt(E),a=new Set(c.pivot.slice(c.rank));if(a.size>0){let O=V.map((h,v)=>v).filter(h=>!a.has(h));E=E.map(h=>O.map(v=>h[v])),V=O.map(h=>V[h]),T.push(`fixed-effect model matrix is rank deficient so dropping ${a.size} ${a.size===1?"column / coefficient":"columns / coefficients"}`)}}let L=[...b.warnings],B=[];for(let c=0;c<V.length;c++){let a=E.map(v=>v[c]);if(a.every(v=>v===0||v===1))continue;let O=a.reduce((v,F)=>v+F,0)/j,h=Math.sqrt(a.reduce((v,F)=>v+(F-O)**2,0)/(j-1));B.push(h)}let K=Math.log(1e3);return B.some((c,a)=>Math.abs(Math.log(c))>K||B.some((O,h)=>h!==a&&Math.abs(Math.log(c/O))>K))&&L.push(`Some predictor variables are on very different scales: consider rescaling.
3
- You may also use (g)lmerControl(autoscale = TRUE) to improve numerical stability.`),{rows:p.rows,y:b.y,xColNames:V,x:E,terms:A,groups:y,q:S.length,z:S,zColLevels:G,theta:H,lower:U,lambda:g,messages:T,warnings:L}}var St=.25,Wt=1e-4,Yt=1e-6,Et=1e-6,It=1e-4,Kt=.001,Ot=1e-13,Ft=1e-10,Zt=1e-9,Jt=500,Tt=.75,Rt="lmer: the minimisation of the criterion over theta did not converge";function zt(r){let n=r.length,s=r.map(o=>o.slice()),l=s.map((o,i)=>s.map((t,e)=>i===e?1:0));for(let o=0;o<100;o++){let i=0,t=0;for(let e=0;e<n;e++)for(let m=0;m<n;m++)t+=s[e][m]**2,e!==m&&(i+=s[e][m]**2);if(i<=1e-32*t)break;for(let e=0;e<n-1;e++)for(let m=e+1;m<n;m++){let b=s[e][m];if(b===0)continue;let p=(s[m][m]-s[e][e])/(2*b),j=Math.sign(p||1)/(Math.abs(p)+Math.sqrt(1+p*p)),_=1/Math.sqrt(1+j*j),k=j*_;for(let u=0;u<n;u++){let I=s[u][e],C=s[u][m];s[u][e]=_*I-k*C,s[u][m]=k*I+_*C}for(let u=0;u<n;u++){let I=s[e][u],C=s[m][u];s[e][u]=_*I-k*C,s[m][u]=k*I+_*C}for(let u=0;u<n;u++){let I=l[u][e],C=l[u][m];l[u][e]=_*I-k*C,l[u][m]=k*I+_*C}}}return{values:s.map((o,i)=>o[i]),vectors:s.map((o,i)=>l.map(t=>t[i]))}}var ht=r=>Math.sqrt(r.reduce((n,s)=>n+s*s,0)),Q=(r,n)=>r.reduce((s,l,o)=>s+l*n[o],0);function Qt(r,n,s,l,o){let i=r.length,{values:t,vectors:e}=n,m=e.map(A=>Q(A,r)),b=A=>{let x=new Array(i).fill(0);return A.forEach((z,D)=>e[D].forEach((S,G)=>x[G]+=z*S)),x},p=Math.min(...t);if(p>-l&&t.every((A,x)=>A>l||Math.abs(m[x])<=o)){let A=b(t.map((x,z)=>x>l?-m[z]/x:0));if(ht(A)<=s)return{step:A,newton:!0}}let j=Math.max(0,-p),_=A=>Math.sqrt(t.reduce((x,z,D)=>x+(m[D]/(z+A))**2,0)),k=Math.max(l,1e-12*Math.max(...t.map(Math.abs),1));if(_(j+k)>=s){let A=j+k,x=j+ht(r)/s+Math.max(...t.map(Math.abs))+k;for(let z=0;z<200&&x-A>1e-15*x;z++){let D=(A+x)/2;_(D)>s?A=D:x=D}return{step:b(t.map((z,D)=>-m[D]/(z+x))),newton:!1}}let u=t.map(A=>A+j<=k),I=b(t.map((A,x)=>u[x]?0:-m[x]/(A+j))),C=t.indexOf(p),$=Math.sqrt(Math.max(0,s*s-Q(I,I))),y=-Math.sign(m[C])||1;return{step:I.map((A,x)=>A+y*$*e[C][x]),newton:!1}}function te(r){let n=[];for(let s of r.terms){let l=s.columns.length,o=s.thetaOffset;for(let i=0;i<l;i++){let t=[];for(let e=i;e<l;e++)t.push(o++);n.push(t)}}return n}var ee=(r,n,s)=>{let l=ut(r,n,s,{gradient:!0});return{f:l.deviance,g:l.gradient}};function oe(r,n,s){let l=r.lower.map(y=>y===0),o=y=>s(r,y,n),i=r.theta.slice(),{f:t,g:e}=o(i),m=new Set,b=new Set,p=()=>Math.max(1,...i.map(Math.abs)),j=()=>Zt*Math.max(1,Math.abs(t)),_=St*p(),k=1/0,u,I=y=>{let A=Yt*p(),x=y.map(z=>{let D=Math.max(Wt*Math.abs(i[z]),A),S=i.slice();S[z]=i[z]+D;let G=i.slice();G[z]=i[z]-D;let H=o(S).g,U=o(G).g;return y.map(g=>(H[g]-U[g])/(2*D))});return y.map((z,D)=>y.map((S,G)=>(x[D][G]+x[G][D])/2))},C=y=>{let A=u===void 0||u.free.length!==y.length||u.free.some((c,a)=>c!==y[a]),x=A?I(y):u.h;u=void 0;let z=zt(x),D=Et*Math.max(...z.values.map(Math.abs)),S=y.map(c=>e[c]),{step:G,newton:H}=Qt(S,z,_,D,j()),U=i.slice();y.forEach((c,a)=>U[c]=i[c]+G[a]);let g=Math.max(...G.map(Math.abs))/p(),T=o(U);if(!Number.isFinite(T.f))throw new Error(Rt);let E=-(Q(S,G)+Q(G,x.map(c=>Q(c,G)))/2),V=Math.abs(t-T.f)>1e-10*Math.abs(t)?t-T.f:-(Q(S,G)+Q(y.map(c=>T.g[c]),G))/2,L=E>0?V/E:V>=0?1:-1;(L>.1||g<=Ft)&&(i=U,t=T.f,e=T.g);let B=ht(G);if(L<.25?_=Math.max(B/4,Ot*p()):L>.75&&B>=.99*_&&(_*=2),!H)return k=1/0,!1;let X=y.every(c=>Math.abs(e[c])<=j())&&(g<=Ot||A&&g<=Ft&&g>=.5*k);return L>Tt&&L<1/Tt&&g<.5*k&&(u={free:y,h:x}),k=g,X},$=()=>{if(m.size===0)return!1;let y=i.map((H,U)=>U),A=zt(I(y)),x=Et*Math.max(...A.values.map(Math.abs)),z=A.values.indexOf(Math.min(...A.values));if(!(A.values[z]<-x))return!1;let D=A.vectors[z],S=y.filter((H,U)=>m.has(H)&&Math.abs(D[U])>1e-8);if(S.length===0)return!1;for(let H of S)m.delete(H),b.add(H);let G=Kt*p();return y.forEach((H,U)=>i[H]=i[H]+G*D[U]),{f:t,g:e}=o(i),!0};for(let y=0;y<Jt;y++){let A=i.map((S,G)=>G).filter(S=>!m.has(S));if(A.length>0&&!C(A))continue;let x=A.filter(S=>l[S]&&!b.has(S)&&Math.abs(i[S])<It*p());if(x.length>0){for(let S of x)i[S]=0,m.add(S);({f:t,g:e}=o(i)),k=1/0,u=void 0;continue}let z=1e-12*Math.max(1,Math.abs(t)),D=[...m].filter(S=>Math.abs(e[S])>z);if(D.length>0)for(let S of D)m.delete(S),b.add(S);else if(!$()){for(let S of te(r))if(i[S[0]]<0)for(let G of S)i[G]=-i[G];return i.map(S=>S===0?0:S)}_=Math.max(_,St*It*p()),k=1/0,u=void 0}throw new Error(Rt)}function re(r,n,s={}){return ne(r,n,s,ee)}function ne(r,n,s,l){let o=s.REML??!0,i={};s.contrasts!==void 0&&(i.contrasts=s.contrasts),s.levels!==void 0&&(i.levels=s.levels);let t=yt(r,n,i),e=oe(t,o,l),m=ut(t,e,o,{rxInverse:!0}),b=t.y.length,p=t.xColNames.length,j=2*Math.PI,_=m.logDetL+b*(1+Math.log(j*m.prss/b)),k=m.logDetL+m.logDetRX+(b-p)*(1+Math.log(j*m.prss/(b-p))),u=m.prss/(o?b-p:b),I=Math.sqrt(u),C=m.rxInverse.map(g=>g.map(T=>u*T)),$=C.map((g,T)=>Math.sqrt(g[T])),y=m.beta.map((g,T)=>g/$[T]),A=t.terms.map(g=>{let T=g.columns.length,E=Array.from({length:T},()=>new Array(T).fill(0)),V=g.thetaOffset;for(let X=0;X<T;X++)for(let c=X;c<T;c++)E[c][X]=e[V++];let L=E.map(X=>E.map(c=>u*X.reduce((a,O,h)=>a+O*c[h],0))),B=L.map((X,c)=>Math.sqrt(X[c])),K=L.map((X,c)=>X.map((a,O)=>c===O?1:a/(B[c]*B[O])));return{group:t.groups[g.group].name,columns:[...g.columns],sd:B,corr:K}}),x=t.groups.map((g,T)=>{let E=t.terms.filter(V=>V.group===T);return{group:g.name,levels:[...g.levels],columns:E.flatMap(V=>V.columns),values:g.levels.map((V,L)=>E.flatMap(B=>{let K=B.columns.length;return B.columns.map((X,c)=>m.b[B.zOffset+L*K+c])}))}}),z=t.x.map(g=>g.reduce((T,E,V)=>T+E*m.beta[V],0));t.z.forEach((g,T)=>{let E=m.b[T];E!==0&&g.rows.forEach((V,L)=>z[V]+=g.values[L]*E)});let D=t.y.map((g,T)=>g-z[T]),S=-(o?k:_)/2,G=p+e.length+1,H=e.some((g,T)=>t.lower[T]===0&&g<1e-4),U=[...t.messages];return H&&U.push("boundary (singular) fit: see help('isSingular')"),{formula:r,REML:o,nObs:b,rows:[...t.rows],theta:e,fixefNames:[...t.xColNames],fixef:m.beta,coefTable:{estimate:[...m.beta],stdError:$,tValue:y},vcov:C,sigma:I,varCorr:A,ranef:x,fitted:z,residuals:D,logLik:S,df:G,AIC:-2*S+2*G,BIC:-2*S+Math.log(b)*G,deviance:_,REMLcrit:k,singular:H,messages:U,warnings:[...t.warnings]}}export{re as lmer};
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{a as bt,c as At}from"./chunks/chunk-YQLEXH2Y.js";import{c as ce,s as le}from"./chunks/chunk-SD7ML5PE.js";import{b as zt}from"./chunks/chunk-7CPM3M6Q.js";import{A as he,C as ge,E as Bt,h as vt,l as pe}from"./chunks/chunk-YTV3RFCA.js";import{a as Rt,c as jt,d as Wt,f as me,g as xt}from"./chunks/chunk-ZUESNU7W.js";import{k as fe,l as ie}from"./chunks/chunk-DWNGNTS6.js";import{b as ue}from"./chunks/chunk-RZIWVCHO.js";import{b as Ut}from"./chunks/chunk-SZ357HRC.js";import"./chunks/chunk-6JRESWVF.js";import"./chunks/chunk-IGSR4GIF.js";import"./chunks/chunk-XCAMWVNO.js";var de=1,we=new WeakMap;function Ue(t){let r=we.get(t);if(r!==void 0)return r;let e=t.y.length,n=t.xColNames.length,o=t.q,s=t.terms.length,a=t.terms.reduce((b,R)=>b+R.nLevels,0),c=new Int32Array(a+1),l=new Int32Array(a),h=[],m=[],w=0;t.terms.forEach((b,R)=>{let V=b.columns.length;h.push(w),m.push(V);for(let L=0;L<b.nLevels;L++,w++)c[w]=b.zOffset+L*V,l[w]=R}),c[a]=o;let N=t.terms.map((b,R)=>{let V=m[R],L=new Int32Array(V*V).fill(-1);for(let{row:M,col:q,theta:j}of t.lambda)q>=b.zOffset&&q<b.zOffset+V&&(L[M-b.zOffset+(q-b.zOffset)*V]=j);return L}),u=t.terms.map(b=>t.groups[b.group].codes),f=new Int32Array(e+1);for(let b=0;b<e;b++){let R=0;for(let V of t.terms)for(let L of V.matrix[b])L!==0&&R++;f[b+1]=f[b]+R}let i=f,p=i[e],S=new Int32Array(p),A=new Float64Array(p);{let b=0;for(let R=0;R<e;R++)t.terms.forEach((V,L)=>{let M=V.zOffset+u[L][R]*m[L];V.matrix[R].forEach((q,j)=>{q!==0&&(S[b]=M+j,A[b++]=q)})})}let x=new Map,E=[],I=[],g=(b,R)=>{let V=R*a+b,L=x.get(V);return L===void 0&&(L=E.length,x.set(V,L),E.push(b),I.push(R)),L};for(let b=0;b<a;b++)g(b,b);let d=new Int32Array(s),v=s*(s+1)/2,y=new Int32Array(e*v);for(let b=0;b<e;b++){for(let R=0;R<s;R++)d[R]=h[R]+u[R][b];for(let R=0;R<s;R++)for(let V=0;V<=R;V++)y[b*v+R*(R+1)/2+V]=g(d[R],d[V])}let k=E.length,C=Array.from({length:k},(b,R)=>R).sort((b,R)=>I[b]-I[R]||E[b]-E[R]),F=new Int32Array(k);C.forEach((b,R)=>F[b]=R);let O=new Int32Array(a+1),P=new Int32Array(k),B=new Int32Array(k+1);C.forEach((b,R)=>{P[R]=E[b],O[I[b]+1]++;let V=m[l[E[b]]]*m[l[I[b]]];B[R+1]=B[R]+V});for(let b=0;b<a;b++)O[b+1]+=O[b];let X=new Float64Array(B[k]),ot=new Float64Array(o*n),st=new Float64Array(o),T=new Float64Array(n);for(let b=0;b<e;b++){let R=t.x[b],V=t.y[b];for(let L=0;L<s;L++){let M=t.terms[L].matrix[b],q=m[L];for(let j=0;j<=L;j++){let H=t.terms[j].matrix[b],J=m[j],D=F[y[b*v+L*(L+1)/2+j]],et=B[D];for(let at=0;at<J;at++){let Tt=H[at];if(Tt!==0)for(let mt=0;mt<q;mt++)X[et+mt+at*q]+=M[mt]*Tt}}}for(let L=i[b];L<i[b+1];L++){let M=S[L],q=A[L];for(let j=0;j<n;j++)ot[M+j*o]+=q*R[j];st[M]+=q*V}for(let L=0;L<n;L++)T[L]+=R[L]*V}let z=new Array(a),Q=Array.from({length:a},()=>[]),_=new Int32Array(a).fill(-1);for(let b=0;b<a;b++){let R=[],V=M=>{M!==b&&_[M]!==b&&(_[M]=b,R.push(M))};for(let M=O[b]+1;M<O[b+1];M++)V(P[M]);for(let M of Q[b])for(let q of z[M])V(q);let L=Int32Array.from(R).sort();z[b]=L,L.length>0&&Q[L[0]].push(b)}let G=new Int32Array(k);{let b=new Int32Array(a);for(let R=0;R<a;R++){let V=0;for(let L of z[R])b[L]=V,V+=c[L+1]-c[L];for(let L=O[R]+1;L<O[R+1];L++)G[L]=b[P[L]]}}let Y=new Int32Array(o+1);for(let b=0;b<a;b++){let R=0;for(let V of z[b])R+=c[V+1]-c[V];for(let V=c[b];V<c[b+1];V++)Y[V+1]=Y[V]+(c[b+1]-V)+R}let rt=new Int32Array(Y[o]),W=new Int32Array(o+1);for(let b=0;b<a;b++)for(let R=c[b];R<c[b+1];R++){let V=Y[R];for(let L=R;L<c[b+1];L++)rt[V++]=L;for(let L of z[b])for(let M=c[L];M<c[L+1];M++)rt[V++]=M}for(let b=0;b<o;b++)for(let R=Y[b]+1;R<Y[b+1];R++)W[rt[R]+1]++;for(let b=0;b<o;b++)W[b+1]+=W[b];let U=W.slice(),tt=W.slice(0,o),Z=new Int32Array(U[o]),ft=new Int32Array(U[o]);for(let b=0;b<o;b++)for(let R=Y[b]+1;R<Y[b+1];R++){let V=tt[rt[R]]++;Z[V]=b,ft[V]=R}let it={n:e,p:n,q:o,nGroups:a,groupStart:c,groupTerm:l,termNc:m,termTheta:N,blockStart:O,blockRow:P,blockValueStart:B,zz:X,zx:ot,zy:st,xy:T,rowStart:i,rowCols:S,rowValues:A,colStart:Y,colRows:rt,rowListStart:U,rowListCol:Z,rowListPos:ft,blockPatternOffset:G};return we.set(t,it),it}function We(t,r){return t.termTheta.map(e=>Float64Array.from(e,n=>n<0?0:r[n]))}function ht(t,r,e){let n=new Float64Array(t.q);for(let o=0;o<t.nGroups;o++){let s=t.groupTerm[o],a=t.termNc[s],c=r[s],l=t.groupStart[o];for(let h=0;h<a;h++){let m=e[l+h];if(m!==0)for(let w=h;w<a;w++)n[l+w]+=c[w+h*a]*m}}return n}function pt(t,r,e,n=1){let o=t.q,s=new Float64Array(o*n);for(let a=0;a<t.nGroups;a++){let c=t.groupTerm[a],l=t.termNc[c],h=r[c],m=t.groupStart[a];for(let w=0;w<n;w++){let N=m+w*o;for(let u=0;u<l;u++){let f=0;for(let i=u;i<l;i++)f+=h[i+u*l]*e[N+i];s[N+u]=f}}}return s}function Be(t,r){let e=new Float64Array(t.zz.length),n=new Float64Array(64);for(let o=0;o<t.nGroups;o++){let s=t.groupTerm[o],a=t.termNc[s],c=r[s];for(let l=t.blockStart[o];l<t.blockStart[o+1];l++){let h=t.groupTerm[t.blockRow[l]],m=t.termNc[h],w=r[h],N=t.blockValueStart[l];if(m===1&&a===1)e[N]=w[0]*t.zz[N]*c[0];else{let u=n.length>=m*a?n:new Float64Array(m*a);for(let f=0;f<a;f++)for(let i=0;i<m;i++){let p=0;for(let S=f;S<a;S++)p+=t.zz[N+i+S*m]*c[S+f*a];u[i+f*m]=p}for(let f=0;f<a;f++)for(let i=0;i<m;i++){let p=0;for(let S=i;S<m;S++)p+=w[S+i*m]*u[S+f*m];e[N+i+f*m]=p}}if(l===t.blockStart[o])for(let u=0;u<a;u++)e[N+u+u*a]+=1}}return e}function He(t,r){let{q:e,colStart:n,colRows:o,rowListStart:s,rowListCol:a,rowListPos:c}=t,l=new Float64Array(o.length),h=new Float64Array(e);for(let m=0;m<t.nGroups;m++){let w=t.termNc[t.groupTerm[m]],N=t.groupStart[m];for(let u=0;u<w;u++){let f=N+u;for(let A=t.blockStart[m];A<t.blockStart[m+1];A++){let x=t.blockRow[A],E=t.termNc[t.groupTerm[x]],I=t.blockValueStart[A]+u*E,g=t.groupStart[x];for(let d=x===m?u:0;d<E;d++)h[g+d]=r[I+d]}for(let A=s[f];A<s[f+1];A++){let x=a[A],E=c[A],I=l[E];if(I===0)continue;let g=n[x+1];for(let d=E;d<g;d++)h[o[d]]-=l[d]*I}let i=h[f];if(!(i>0))throw new Error("the penalised least-squares matrix is not positive definite");let p=Math.sqrt(i),S=n[f];l[S]=p,h[f]=0;for(let A=S+1;A<n[f+1];A++){let x=o[A];l[A]=h[x]/p,h[x]=0}}}return l}function Nt(t,r,e,n=0){let{q:o,colStart:s,colRows:a}=t;for(let c=0;c<o;c++){let l=s[c],h=e[n+c]/=r[l];if(h!==0)for(let m=l+1;m<s[c+1];m++)e[n+a[m]]-=r[m]*h}}function Et(t,r,e,n=0){let{q:o,colStart:s,colRows:a}=t;for(let c=o-1;c>=0;c--){let l=s[c],h=e[n+c];for(let m=l+1;m<s[c+1];m++)h-=r[m]*e[n+a[m]];e[n+c]=h/r[l]}}function Xe(t,r,e){for(let n=0;n<r;n++){let o=n*r,s=e[n];for(let a=0;a<n;a++)s-=t[a+o]*e[a];e[n]=s/t[n+o]}}function Ye(t,r,e){for(let n=r-1;n>=0;n--){let o=e[n]/=t[n+n*r],s=n*r;for(let a=0;a<n;a++)e[a]-=t[a+s]*o}}function Ht(t,r){let e=t.slice();for(let n=0;n<r;n++)for(let o=n+1;o<r;o++)e[o+n*r]=0;ge({nrow:r,ncol:r,data:e});for(let n=0;n<r;n++)for(let o=n+1;o<r;o++)e[o+n*r]=e[n+o*r];return e}function Xt(t,r,e,n={}){let o=Yt(t,r),{sys:s,t:a,l:c,rx:l,ws:h,xResiduals:m,res:w,uv:N}=o,{n:u,p:f,q:i}=s,p=Array.from(o.beta),S=Array.from(N),A=Array.from(o.b),x=0;for(let F of w)x+=F*F;let E=0;for(let F of S)E+=F*F;let I=x+E,g=0;for(let F=0;F<i;F++)g+=Math.log(c[s.colStart[F]]);g*=2;let d=0;for(let F=0;F<f;F++)d+=Math.log(l[F+F*f]);d*=2;let v=e?u-f:u,k={deviance:(e?g+d:g)+v*(1+Math.log(2*Math.PI*I/v)),beta:p,u:S,b:A,rss:x,ussq:E,prss:I,logDetL:g,logDetRX:d},C=n.gradient===!0||n.rxInverse===!0?Ht(l,f):void 0;return n.rxInverse===!0&&(k.rxInverse=Array.from({length:f},(F,O)=>Array.from({length:f},(P,B)=>C[O+B*f]))),n.gradient===!0&&(k.gradient=Ze(t,s,a,c,r,e,{res:w,uv:N,prss:I,ws:h,xResiduals:m,sInverse:C})),k}function Yt(t,r){if(r.length!==t.theta.length)throw new RangeError(`theta must have length ${t.theta.length}, not ${r.length}`);if(r.some(g=>!Number.isFinite(g)))throw new RangeError("theta must be finite");let e=Ue(t),{n,p:o,q:s}=e,a=We(e,r),c=He(e,Be(e,a)),l=g=>{let d=new Float64Array(n);for(let v=0;v<n;v++){let y=0;for(let k=e.rowStart[v];k<e.rowStart[v+1];k++)y+=e.rowValues[k]*g[e.rowCols[k]];d[v]=y}return d},h=g=>{let d=new Float64Array(s);for(let v=0;v<n;v++){let y=g[v];for(let k=e.rowStart[v];k<e.rowStart[v+1];k++)d[e.rowCols[k]]+=e.rowValues[k]*y}return d},m=g=>{Nt(e,c,g),Et(e,c,g)},w=pt(e,a,e.zx,o);for(let g=0;g<o;g++)Nt(e,c,w,g*s);let N=[],u=[];for(let g=0;g<o;g++){let d=w.slice(g*s,(g+1)*s);Et(e,c,d);let v=Float64Array.from(t.x,C=>C[g]),y=()=>{let C=l(ht(e,a,d));return v.map((F,O)=>F-C[O])},k=y();for(let C=0;C<de;C++){let F=pt(e,a,h(k));for(let O=0;O<s;O++)F[O]-=d[O];m(F);for(let O=0;O<s;O++)d[O]+=F[O];k=y()}N.push(k),u.push(d)}let f=new Float64Array(o*o);for(let g=0;g<o;g++)for(let d=g;d<o;d++){let v=0,y=N[g],k=N[d];for(let O=0;O<n;O++)v+=y[O]*k[O];let C=u[g],F=u[d];for(let O=0;O<s;O++)v+=C[O]*F[O];f[g+d*o]=v,f[d+g*o]=v}let i={nrow:o,ncol:o,data:f};if(o>0&&he(i)>0)throw new Error("the fixed-effects matrix of the penalised least squares is not positive definite");let p=(g,d)=>{Nt(e,c,g);for(let v=0;v<o;v++){let y=d[v];for(let k=0;k<s;k++)y-=w[k+v*s]*g[k];d[v]=y}Xe(f,o,d),Ye(f,o,d);for(let v=0;v<o;v++){let y=d[v];for(let k=0;k<s;k++)g[k]-=w[k+v*s]*y}Et(e,c,g)},S=(g,d)=>{let v=l(d),y=new Float64Array(n);for(let k=0;k<n;k++){let C=t.x[k],F=v[k];for(let O=0;O<o;O++)F+=C[O]*g[O];y[k]=t.y[k]-F}return y},A=pt(e,a,e.zy),x=Float64Array.from(e.xy);p(A,x);let E=ht(e,a,A),I=S(x,E);for(let g=0;g<de;g++){let d=pt(e,a,h(I));for(let y=0;y<s;y++)d[y]-=A[y];let v=new Float64Array(o);for(let y=0;y<n;y++){let k=t.x[y],C=I[y];for(let F=0;F<o;F++)v[F]+=k[F]*C}p(d,v);for(let y=0;y<s;y++)A[y]+=d[y];for(let y=0;y<o;y++)x[y]+=v[y];E=ht(e,a,A),I=S(x,E)}return{sys:e,t:a,l:c,cx:w,rx:f,ws:u,xResiduals:N,res:I,uv:A,beta:x,b:E,solveNormal:p}}function Zt(t,r){let{q:e,colStart:n,colRows:o}=t,s=new Float64Array(r.length),a=new Int32Array(e).fill(-1),c=new Float64Array(e),l=new Float64Array(e);for(let h=e-1;h>=0;h--){let m=n[h],w=n[h+1];for(let f=m+1;f<w;f++){let i=o[f];a[i]=h,c[i]=r[f],l[i]=0}for(let f=m+1;f<w;f++){let i=o[f],p=r[f],S=n[i],A=s[S]*p;for(let x=S+1;x<n[i+1];x++){let E=o[x];if(a[E]!==h)continue;let I=s[x];l[E]+=I*p,A+=I*c[E]}l[i]+=A}let N=r[m],u=1/N;for(let f=m+1;f<w;f++){let i=-l[o[f]]/N;s[f]=i,u-=r[f]*i}s[m]=u/N}return s}function ve(t,r,e){let{q:n,colStart:o,colRows:s,rowListStart:a,rowListCol:c,rowListPos:l}=t,h=new Float64Array(r.length),m=new Float64Array(n);for(let w=0;w<t.nGroups;w++){let N=t.termNc[t.groupTerm[w]],u=t.groupStart[w];for(let f=0;f<N;f++){let i=u+f;for(let x=t.blockStart[w];x<t.blockStart[w+1];x++){let E=t.blockRow[x],I=t.termNc[t.groupTerm[E]],g=t.blockValueStart[x]+f*I,d=t.groupStart[E];for(let v=E===w?f:0;v<I;v++)m[d+v]=e[g+v]}for(let x=a[i];x<a[i+1];x++){let E=c[x],I=l[x],g=r[I],d=h[I];if(g===0&&d===0)continue;let v=o[E+1];for(let y=I;y<v;y++)m[s[y]]-=h[y]*g+r[y]*d}let p=o[i],S=r[p],A=m[i]/(2*S);h[p]=A,m[i]=0;for(let x=p+1;x<o[i+1];x++){let E=s[x];h[x]=(m[E]-r[x]*A)/S,m[E]=0}}}return h}function be(t,r,e,n){let{q:o,colStart:s,colRows:a}=t,c=new Float64Array(r.length),l=new Int32Array(o).fill(-1),h=new Float64Array(o),m=new Float64Array(o),w=new Float64Array(o),N=new Float64Array(o);for(let u=o-1;u>=0;u--){let f=s[u],i=s[u+1];for(let E=f+1;E<i;E++){let I=a[E];l[I]=u,h[I]=r[E],m[I]=e[E],w[I]=0,N[I]=0}for(let E=f+1;E<i;E++){let I=a[E],g=r[E],d=e[E],v=s[I],y=n[v]*g,k=c[v]*g+n[v]*d;for(let C=v+1;C<s[I+1];C++){let F=a[C];if(l[F]!==u)continue;let O=n[C],P=c[C];w[F]+=O*g,N[F]+=P*g+O*d,y+=O*h[F],k+=P*h[F]+O*m[F]}w[I]+=y,N[I]+=k}let p=r[f],S=e[f],A=1/p,x=-S/(p*p);for(let E=f+1;E<i;E++){let I=a[E],g=n[E],d=-N[I]/p+w[I]*S/(p*p);c[E]=d,A-=r[E]*g,x-=e[E]*g+r[E]*d}c[f]=x/p-A*S/(p*p)}return c}function Ze(t,r,e,n,o,s,{res:a,uv:c,prss:l,ws:h,xResiduals:m,sInverse:w}){let{n:N,p:u,q:f}=r,i=Mt(r,Zt(r,n),e),p=new Array(o.length).fill(0);r.termTheta.forEach((g,d)=>{let v=r.termNc[d];for(let y=0;y<v;y++)for(let k=y;k<v;k++)p[g[k+y*v]]+=2*i[d][y+k*v]});let S=new Float64Array(f);for(let g=0;g<N;g++){let d=a[g];for(let v=r.rowStart[g];v<r.rowStart[g+1];v++)S[r.rowCols[v]]+=r.rowValues[v]*d}let A,x;if(s&&u>0){A=new Float64Array(f*u);for(let g=0;g<u;g++)for(let d=0;d<u;d++){let v=w[d+g*u],y=h[d];for(let k=0;k<f;k++)A[k+g*f]+=y[k]*v}x=new Float64Array(u*f);for(let g=0;g<N;g++)for(let d=r.rowStart[g];d<r.rowStart[g+1];d++){let v=r.rowCols[d],y=r.rowValues[d];for(let k=0;k<u;k++)x[k+v*u]+=m[k][g]*y}}let I=2*(s?N-u:N)/l;for(let{row:g,col:d,theta:v}of t.lambda){let y=0;if(A!==void 0&&x!==void 0)for(let k=0;k<u;k++)y+=A[d+k*f]*x[k+g*u];p[v]-=2*y+I*S[g]*c[d]}return p}function Mt(t,r,e){let{colStart:n,zz:o}=t,s=t.termNc.map(l=>new Float64Array(l*l)),a=new Float64Array(16),c=new Float64Array(16);for(let l=0;l<t.nGroups;l++){let h=t.groupTerm[l],m=t.termNc[h],w=e[h],N=t.groupStart[l];for(let u=t.blockStart[l];u<t.blockStart[l+1];u++){let f=t.blockRow[u],i=t.groupTerm[f],p=t.termNc[i],S=e[i],A=t.blockValueStart[u];if(m===1&&p===1){let g=f===l?n[N]:n[N]+1+t.blockPatternOffset[u],d=r[g]*o[A];s[h][0]+=d*S[0],f!==l&&(s[i][0]+=d*w[0]);continue}let x=p*m;a.length<x&&(a=new Float64Array(x),c=new Float64Array(Math.max(x,p*p,m*m)));for(let g=0;g<m;g++){let d=n[N+g];if(f===l)for(let v=g;v<p;v++){let y=r[d+v-g];a[v+g*p]=y,a[g+v*p]=y}else{let v=d+(m-g)+t.blockPatternOffset[u];for(let y=0;y<p;y++)a[y+g*p]=r[v+y]}}for(let g=0;g<m;g++)for(let d=0;d<p;d++){let v=0;for(let y=d;y<p;y++)v+=S[y+d*p]*o[A+y+g*p];c[d+g*p]=v}let E=s[h];for(let g=0;g<m;g++)for(let d=0;d<m;d++){let v=0;for(let y=0;y<p;y++)v+=a[y+g*p]*c[y+d*p];E[g+d*m]+=v}if(f===l)continue;for(let g=0;g<p;g++)for(let d=0;d<m;d++){let v=0;for(let y=d;y<m;y++)v+=w[y+d*m]*o[A+g+y*p];c[d+g*m]=v}let I=s[i];for(let g=0;g<p;g++)for(let d=0;d<p;d++){let v=0;for(let y=0;y<m;y++)v+=a[g+y*p]*c[y+d*m];I[g+d*p]+=v}}}return s}function Je(t){let r=[],e=c=>{c.type==="var"?r.includes(c.name)||r.push(c.name):c.type==="binary"?(e(c.left),c.op!=="^"&&e(c.right)):(c.type==="unary"||c.type==="paren"||c.type==="Error")&&e(c.arg)};e(t);let{terms:n}=me(t,c=>r.indexOf(c),[]);if(n.length===0)throw new SyntaxError(`invalid formula: no grouping factor in '${Wt(t)}'`);let o=n.map((c,l)=>[c,l]).sort((c,l)=>c[0].length-l[0].length||c[1]-l[1]).map(([c])=>c.map(l=>r[l])),s=!1,a=c=>{c.type==="binary"?(c.op==="/"&&(s=!0),a(c.left),a(c.right)):(c.type==="unary"||c.type==="paren"||c.type==="Error")&&a(c.arg)};return a(t),s&&(o=o.map(c=>[...c].reverse()).reverse()),o}function Ke(t){if(t.kind==="factor")return ue(t);let r=[...new Set(t.values)].sort((o,s)=>o-s),e=[],n=new Map;for(let o of r){let s=Ut(o);n.has(s)||(n.set(s,e.length),e.push(s))}return{levels:e,codes:t.values.map(o=>n.get(Ut(o)))}}function ye(t,r,e={}){let n=Rt(t,!1,!0);if(n.response===void 0)throw new TypeError("the formula has no response");let{fixed:o,bars:s}=jt(n.rhs);if(typeof r!="object"||r===null)throw new TypeError("data must be an object of columns");let a={...e.levels===void 0?{}:{levels:e.levels},dropUnusedLevels:!0},c=o??{type:"num",value:1,text:"1"},l=e.contrasts===void 0?{}:{contrasts:e.contrasts,contrastVariables:xt({response:n.response,rhs:c},Object.keys(r)).variables},h=bt(n,r,{...a,...l},c),{frame:m}=h,w=m.rows.length;if(w===0)throw new RangeError("0 (non-NA) cases");if(s.length===0)throw new Error("No random effects terms specified in formula");let N=h.terms.variables,u=[];for(let T of s){let z=[T.lhs];if(T.double){let _=xt(n,Object.keys(r),T.lhs);z=_.intercept?[{type:"num",value:1,text:"1"}]:[];for(let G of _.terms){let Y=G.map(rt=>({type:"var",name:N[rt]})).reduce((rt,W)=>({type:"binary",op:":",left:rt,right:W}));z.push({type:"binary",op:"+",left:{type:"num",value:0,text:"0"},right:Y})}}let Q=Je(T.group);for(let _ of z)for(let G of Q)u.push({lhs:_,groupVariables:G})}let f=new Map,i=T=>{let z=T.join(":"),Q=f.get(z);if(Q!==void 0)return Q;let _=T.map(Y=>Ke(m.variables[N.indexOf(Y)])),G;if(_.length===1)G=_[0];else{let Y=new Map;for(let U=0;U<w;U++){let tt=_.map(Z=>Z.codes[U]);Y.set(tt.join(","),tt)}let rt=[...Y.values()].sort((U,tt)=>{for(let Z=0;Z<U.length;Z++)if(U[Z]!==tt[Z])return U[Z]-tt[Z];return 0}),W=new Map(rt.map((U,tt)=>[U.join(","),tt]));G={levels:rt.map(U=>U.map((tt,Z)=>_[Z].levels[tt]).join(":")),codes:Array.from({length:w},(U,tt)=>W.get(_.map(Z=>Z.codes[tt]).join(",")))}}return f.set(z,G),G},p=u.map(T=>({...T,name:T.groupVariables.join(":"),factor:i(T.groupVariables)})),S=p;p.some((T,z)=>z>0&&T.factor.levels.length>p[z-1].factor.levels.length)&&(S=p.map((T,z)=>[T,z]).sort((T,z)=>T[0].factor.levels.length-z[0].factor.levels.length||T[1]-z[1]).map(([T])=>T).reverse());let A=[],x=[],E=0,I=0;for(let T of S){let z=A.findIndex(Y=>Y.name===T.name);z<0&&(z=A.length,A.push({name:T.name,levels:T.factor.levels,codes:T.factor.codes}));let Q=bt(n,r,a,T.lhs),_=Q.colNames.length,G=T.factor.levels.length;x.push({label:`${Wt(T.lhs)} | ${T.name}`,group:z,columns:Q.colNames,matrix:Q.x,nLevels:G,zOffset:E,thetaOffset:I}),E+=G*_,I+=_*(_+1)/2}if(A.some(T=>T.levels.length<2))throw new RangeError("grouping factors must have > 1 sampled level");let g=A.filter(T=>T.levels.length>=w).map(T=>T.name);if(g.length>0)throw new RangeError(`number of levels of each grouping factor must be < number of observations (problems: ${g.join(", ")})`);for(let T of x){let z=T.nLevels*T.columns.length;if(w<=z)throw new RangeError(`number of observations (=${w}) <= number of random effects (=${z}) for term (${T.label}); the random-effects parameters and the residual variance (or scale parameter) are probably unidentifiable`)}let d=[],v=[],y=[],k=[],C=[];for(let T of x){let{levels:z,codes:Q}=A[T.group],_=T.columns.length,G=Array.from({length:z.length*_},()=>({rows:[],values:[]}));for(let W=0;W<w;W++){let U=T.matrix[W],tt=Q[W]*_;for(let Z=0;Z<_;Z++){let ft=U[Z];if(ft===0)continue;let it=G[tt+Z];it.rows.push(W),it.values.push(ft)}}for(let W=0;W<z.length;W++)for(let U=0;U<_;U++)d.push(G[W*_+U]),v.push(z[W]);let Y=Array.from({length:_},()=>new Array(_).fill(-1)),rt=T.thetaOffset;for(let W=0;W<_;W++)for(let U=W;U<_;U++)Y[U][W]=rt++,y.push(U===W?1:0),k.push(U===W?0:-1/0);for(let W=0;W<T.nLevels;W++){let U=T.zOffset+W*_;for(let tt=0;tt<_;tt++)for(let Z=tt;Z<_;Z++)C.push({row:U+Z,col:U+tt,theta:Y[Z][tt]})}}let F=[],O=h.x,P=h.colNames;if(P.length>0){let T=vt(O),z=new Set(T.pivot.slice(T.rank));if(z.size>0){let Q=P.map((_,G)=>G).filter(_=>!z.has(_));O=O.map(_=>Q.map(G=>_[G])),P=Q.map(_=>P[_]),F.push(`fixed-effect model matrix is rank deficient so dropping ${z.size} ${z.size===1?"column / coefficient":"columns / coefficients"}`)}}let B=[...h.warnings],X=[];for(let T=0;T<P.length;T++){let z=O.map(G=>G[T]);if(z.every(G=>G===0||G===1))continue;let Q=z.reduce((G,Y)=>G+Y,0)/w,_=Math.sqrt(z.reduce((G,Y)=>G+(Y-Q)**2,0)/(w-1));X.push(_)}let ot=Math.log(1e3);return X.some((T,z)=>Math.abs(Math.log(T))>ot||X.some((Q,_)=>_!==z&&Math.abs(Math.log(T/Q))>ot))&&B.push(`Some predictor variables are on very different scales: consider rescaling.
3
+ You may also use (g)lmerControl(autoscale = TRUE) to improve numerical stability.`),{rows:m.rows,y:h.y,xColNames:P,x:O,terms:x,groups:A,q:d.length,z:d,zColLevels:v,theta:y,lower:k,lambda:C,messages:F,warnings:B}}var xe=.25,Qe=1e-4,to=1e-6,Ae=1e-6,Ne=1e-4,eo=.001,Ee=1e-13,Me=1e-10,oo=1e-9,ro=500,Se=.75,ke="lmer: the minimisation of the criterion over theta did not converge";function Ie(t){let r=t.length,e=t.map(o=>o.slice()),n=e.map((o,s)=>e.map((a,c)=>s===c?1:0));for(let o=0;o<100;o++){let s=0,a=0;for(let c=0;c<r;c++)for(let l=0;l<r;l++)a+=e[c][l]**2,c!==l&&(s+=e[c][l]**2);if(s<=1e-32*a)break;for(let c=0;c<r-1;c++)for(let l=c+1;l<r;l++){let h=e[c][l];if(h===0)continue;let m=(e[l][l]-e[c][c])/(2*h),w=Math.sign(m||1)/(Math.abs(m)+Math.sqrt(1+m*m)),N=1/Math.sqrt(1+w*w),u=w*N;for(let f=0;f<r;f++){let i=e[f][c],p=e[f][l];e[f][c]=N*i-u*p,e[f][l]=u*i+N*p}for(let f=0;f<r;f++){let i=e[c][f],p=e[l][f];e[c][f]=N*i-u*p,e[l][f]=u*i+N*p}for(let f=0;f<r;f++){let i=n[f][c],p=n[f][l];n[f][c]=N*i-u*p,n[f][l]=u*i+N*p}}}return{values:e.map((o,s)=>o[s]),vectors:e.map((o,s)=>n.map(a=>a[s]))}}var Jt=t=>Math.sqrt(t.reduce((r,e)=>r+e*e,0)),gt=(t,r)=>t.reduce((e,n,o)=>e+n*r[o],0);function no(t,r,e,n,o){let s=t.length,{values:a,vectors:c}=r,l=c.map(x=>gt(x,t)),h=x=>{let E=new Array(s).fill(0);return x.forEach((I,g)=>c[g].forEach((d,v)=>E[v]+=I*d)),E},m=Math.min(...a);if(m>-n&&a.every((x,E)=>x>n||Math.abs(l[E])<=o)){let x=h(a.map((E,I)=>E>n?-l[I]/E:0));if(Jt(x)<=e)return{step:x,newton:!0}}let w=Math.max(0,-m),N=x=>Math.sqrt(a.reduce((E,I,g)=>E+(l[g]/(I+x))**2,0)),u=Math.max(n,1e-12*Math.max(...a.map(Math.abs),1));if(N(w+u)>=e){let x=w+u,E=w+Jt(t)/e+Math.max(...a.map(Math.abs))+u;for(let I=0;I<200&&E-x>1e-15*E;I++){let g=(x+E)/2;N(g)>e?x=g:E=g}return{step:h(a.map((I,g)=>-l[g]/(I+E))),newton:!1}}let f=a.map(x=>x+w<=u),i=h(a.map((x,E)=>f[E]?0:-l[E]/(x+w))),p=a.indexOf(m),S=Math.sqrt(Math.max(0,e*e-gt(i,i))),A=-Math.sign(l[p])||1;return{step:i.map((x,E)=>x+A*S*c[p][E]),newton:!1}}function so(t){let r=[];for(let e of t.terms){let n=e.columns.length,o=e.thetaOffset;for(let s=0;s<n;s++){let a=[];for(let c=s;c<n;c++)a.push(o++);r.push(a)}}return r}var ao=(t,r,e)=>{let n=Xt(t,r,e,{gradient:!0});return{f:n.deviance,g:n.gradient}};function co(t,r,e){let n=t.lower.map(A=>A===0),o=A=>e(t,A,r),s=t.theta.slice(),{f:a,g:c}=o(s),l=new Set,h=new Set,m=()=>Math.max(1,...s.map(Math.abs)),w=()=>oo*Math.max(1,Math.abs(a)),N=xe*m(),u=1/0,f,i=A=>{let x=to*m(),E=A.map(I=>{let g=Math.max(Qe*Math.abs(s[I]),x),d=s.slice();d[I]=s[I]+g;let v=s.slice();v[I]=s[I]-g;let y=o(d).g,k=o(v).g;return A.map(C=>(y[C]-k[C])/(2*g))});return A.map((I,g)=>A.map((d,v)=>(E[g][v]+E[v][g])/2))},p=A=>{let x=f===void 0||f.free.length!==A.length||f.free.some((T,z)=>T!==A[z]),E=x?i(A):f.h;f=void 0;let I=Ie(E),g=Ae*Math.max(...I.values.map(Math.abs)),d=A.map(T=>c[T]),{step:v,newton:y}=no(d,I,N,g,w()),k=s.slice();A.forEach((T,z)=>k[T]=s[T]+v[z]);let C=Math.max(...v.map(Math.abs))/m(),F=o(k);if(!Number.isFinite(F.f))throw new Error(ke);let O=-(gt(d,v)+gt(v,E.map(T=>gt(T,v)))/2),P=Math.abs(a-F.f)>1e-10*Math.abs(a)?a-F.f:-(gt(d,v)+gt(A.map(T=>F.g[T]),v))/2,B=O>0?P/O:P>=0?1:-1;(B>.1||C<=Me)&&(s=k,a=F.f,c=F.g);let X=Jt(v);if(B<.25?N=Math.max(X/4,Ee*m()):B>.75&&X>=.99*N&&(N*=2),!y)return u=1/0,!1;let st=A.every(T=>Math.abs(c[T])<=w())&&(C<=Ee||x&&C<=Me&&C>=.5*u);return B>Se&&B<1/Se&&C<.5*u&&(f={free:A,h:E}),u=C,st},S=()=>{if(l.size===0)return!1;let A=s.map((y,k)=>k),x=Ie(i(A)),E=Ae*Math.max(...x.values.map(Math.abs)),I=x.values.indexOf(Math.min(...x.values));if(!(x.values[I]<-E))return!1;let g=x.vectors[I],d=A.filter((y,k)=>l.has(y)&&Math.abs(g[k])>1e-8);if(d.length===0)return!1;for(let y of d)l.delete(y),h.add(y);let v=eo*m();return A.forEach((y,k)=>s[y]=s[y]+v*g[k]),{f:a,g:c}=o(s),!0};for(let A=0;A<ro;A++){let x=s.map((d,v)=>v).filter(d=>!l.has(d));if(x.length>0&&!p(x))continue;let E=x.filter(d=>n[d]&&!h.has(d)&&Math.abs(s[d])<Ne*m());if(E.length>0){for(let d of E)s[d]=0,l.add(d);({f:a,g:c}=o(s)),u=1/0,f=void 0;continue}let I=1e-12*Math.max(1,Math.abs(a)),g=[...l].filter(d=>Math.abs(c[d])>I);if(g.length>0)for(let d of g)l.delete(d),h.add(d);else if(!S()){for(let d of so(t))if(s[d[0]]<0)for(let v of d)s[v]=-s[v];return s.map(d=>d===0?0:d)}N=Math.max(N,xe*Ne*m()),u=1/0,f=void 0}throw new Error(ke)}function lo(t,r,e={}){return Kt(t,r,e,ao)}var Te=new WeakMap;function dt(t){let r=typeof t=="object"&&t!==null?Te.get(t):void 0;if(r===void 0)throw new TypeError("fit must be a result returned by lmer (not a copy of one)");return r}function Kt(t,r,e,n){let o=e.REML??!0,s={};e.contrasts!==void 0&&(s.contrasts=e.contrasts),e.levels!==void 0&&(s.levels=e.levels);let a=ye(t,r,s),c=co(a,o,n),l=Xt(a,c,o,{rxInverse:!0}),h=a.y.length,m=a.xColNames.length,w=2*Math.PI,N=l.logDetL+h*(1+Math.log(w*l.prss/h)),u=l.logDetL+l.logDetRX+(h-m)*(1+Math.log(w*l.prss/(h-m))),f=l.prss/(o?h-m:h),i=Math.sqrt(f),p=l.rxInverse.map(F=>F.map(O=>f*O)),S=p.map((F,O)=>Math.sqrt(F[O])),A=l.beta.map((F,O)=>F/S[O]),x=a.terms.map(F=>{let O=F.columns.length,P=Array.from({length:O},()=>new Array(O).fill(0)),B=F.thetaOffset;for(let T=0;T<O;T++)for(let z=T;z<O;z++)P[z][T]=c[B++];let X=P.map(T=>P.map(z=>f*T.reduce((Q,_,G)=>Q+_*z[G],0))),ot=X.map((T,z)=>Math.sqrt(T[z])),st=X.map((T,z)=>T.map((Q,_)=>z===_?1:Q/(ot[z]*ot[_])));return{group:a.groups[F.group].name,columns:[...F.columns],sd:ot,corr:st}}),E=a.groups.map((F,O)=>{let P=a.terms.filter(B=>B.group===O);return{group:F.name,levels:[...F.levels],columns:P.flatMap(B=>B.columns),values:F.levels.map((B,X)=>P.flatMap(ot=>{let st=ot.columns.length;return ot.columns.map((T,z)=>l.b[ot.zOffset+X*st+z])}))}}),I=a.x.map(F=>F.reduce((O,P,B)=>O+P*l.beta[B],0));a.z.forEach((F,O)=>{let P=l.b[O];P!==0&&F.rows.forEach((B,X)=>I[B]+=F.values[X]*P)});let g=a.y.map((F,O)=>F-I[O]),d=-(o?u:N)/2,v=m+c.length+1,y=c.some((F,O)=>a.lower[O]===0&&F<1e-4),k=[...a.messages];y&&k.push("boundary (singular) fit: see help('isSingular')");let C={formula:t,REML:o,nObs:h,rows:[...a.rows],theta:c,fixefNames:[...a.xColNames],fixef:l.beta,coefTable:{estimate:[...l.beta],stdError:S,tValue:A},vcov:p,sigma:i,varCorr:x,ranef:E,fitted:I,residuals:g,logLik:d,df:v,AIC:-2*d+2*v,BIC:-2*d+Math.log(h)*v,deviance:N,REMLcrit:u,singular:y,messages:k,warnings:[...a.warnings]};return Te.set(C,{structure:a,data:r,options:{...e},reml:o,criterion:n,theta:[...c]}),C}function Fe(t,r,e){let n=new Float64Array(t.zz.length),o=new Float64Array(64);for(let s=0;s<t.nGroups;s++){let a=t.groupTerm[s],c=t.termNc[a],l=e[a];for(let h=t.blockStart[s];h<t.blockStart[s+1];h++){let m=t.groupTerm[t.blockRow[h]],w=t.termNc[m],N=r[m],u=t.blockValueStart[h];o.length<w*c&&(o=new Float64Array(w*c));for(let f=0;f<c;f++)for(let i=0;i<w;i++){let p=0;for(let S=0;S<c;S++)p+=t.zz[u+i+S*w]*l[S+f*c];o[i+f*w]=p}for(let f=0;f<c;f++)for(let i=0;i<w;i++){let p=0;for(let S=0;S<w;S++)p+=N[S+i*w]*o[S+f*w];n[u+i+f*w]=p}}}return n}function St(t,r,e){let n=new Float64Array(e*e);for(let o=0;o<e;o++)for(let s=0;s<e;s++){let a=r[s+o*e];if(a!==0)for(let c=0;c<e;c++)n[c+o*e]+=t[c+s*e]*a}return n}var Qt=(t,r)=>{let e=0;for(let n=0;n<r;n++)e+=t[n+n*r];return e},te=(t,r)=>Array.from({length:r},(e,n)=>Array.from({length:r},(o,s)=>t[n+s*r]));function Oe(t,r,e){let n=Yt(t,r),{sys:o,t:s,l:a,rx:c,ws:l,xResiduals:h,res:m,uv:w}=n,{n:N,p:u,q:f}=o,i=r.length,p=i+1,S=M=>{let q=new Float64Array(N);for(let j=0;j<N;j++){let H=0;for(let J=o.rowStart[j];J<o.rowStart[j+1];J++)H+=o.rowValues[J]*M[o.rowCols[J]];q[j]=H}return q},A=M=>{let q=new Float64Array(f);for(let j=0;j<N;j++){let H=M[j];if(H!==0)for(let J=o.rowStart[j];J<o.rowStart[j+1];J++)q[o.rowCols[J]]+=o.rowValues[J]*H}return q},x=M=>{let q=new Float64Array(u);for(let j=0;j<N;j++){let H=t.x[j],J=M[j];for(let D=0;D<u;D++)q[D]+=H[D]*J}return q},E=M=>{let q=new Float64Array(N);for(let j=0;j<N;j++){let H=t.x[j],J=0;for(let D=0;D<u;D++)J+=H[D]*M[D];q[j]=J}return q},I=M=>{Nt(o,a,M),Et(o,a,M)},g=Array.from({length:i},()=>[]),d=Array.from({length:i},()=>[]);for(let{row:M,col:q,theta:j}of t.lambda)g[j].push(M),d[j].push(q);let v=(M,q)=>{let j=new Float64Array(f),H=g[M],J=d[M];for(let D=0;D<H.length;D++)j[H[D]]+=q[J[D]];return j},y=(M,q)=>{let j=new Float64Array(f),H=g[M],J=d[M];for(let D=0;D<H.length;D++)j[J[D]]+=q[H[D]];return j},k=(M,q,j)=>{let H=g[M],J=d[M],D=0;for(let et=0;et<H.length;et++)D+=q[H[et]]*j[J[et]];return D},C=(M,q,j,H,J)=>{for(let D=0;D<u;D++)for(let et=0;et<u;et++){let at=J*k(M,q[D],j[et]);H[D+et*u]+=at,H[et+D*u]+=at}},F=0;for(let M of m)F+=M*M;let O=0;for(let M of w)O+=M*M;let P=F+O,B=e?N-u:N,X=P/B,ot=Math.sqrt(X),st=0;for(let M=0;M<f;M++)st+=Math.log(a[o.colStart[M]]);st*=2;let T=0;for(let M=0;M<u;M++)T+=Math.log(c[M+M*u]);T*=2;let Q=(e?st+T:st)+P/X+B*Math.log(2*Math.PI*X),_=Ht(c,u),G=Zt(o,a),Y=A(m),rt=h.map(A),W=Mt(o,G,s),U=new Array(i).fill(0),tt=(M,q,j)=>{o.termTheta.forEach((H,J)=>{let D=o.termNc[J];for(let et=0;et<D;et++)for(let at=et;at<D;at++)q[H[at+et*D]]+=j*M[J][et+at*D]})};tt(W,U,2);let Z=Array.from({length:i},(M,q)=>-2*k(q,Y,w)),ft=Array.from({length:i},(M,q)=>{let j=new Float64Array(u*u);return C(q,rt,l,j,-1),j});if(e)for(let M=0;M<i;M++)U[M]+=Qt(St(_,ft[M],u),u);let it=ft.map(M=>St(_,M,u)),b=Array.from({length:p},()=>new Array(p).fill(0));for(let M=0;M<i;M++){let q=o.termTheta.map($=>Float64Array.from($,ut=>ut===M?1:0)),j=Fe(o,q,s),H=Fe(o,s,q);for(let $=0;$<j.length;$++)j[$]+=H[$];let J=ve(o,a,j),D=be(o,a,J,G),et=new Array(i).fill(0),at=Mt(o,D,s),Tt=Mt(o,G,q);if(tt(at,et,2),tt(Tt,et,2),e&&u>0){let $=[],ut=[];for(let nt=0;nt<u;nt++){let lt=y(M,rt[nt]),K=pt(o,s,A(S(v(M,l[nt]))));for(let ct=0;ct<f;ct++)lt[ct]-=K[ct];I(lt),$.push(lt);let ae=v(M,l[nt]),Ge=ht(o,s,lt);for(let ct=0;ct<f;ct++)ae[ct]+=Ge[ct];let Gt=S(ae);for(let ct=0;ct<N;ct++)Gt[ct]=-Gt[ct];ut.push(A(Gt))}for(let nt=0;nt<i;nt++){let lt=new Float64Array(u*u);C(nt,ut,l,lt,-1),C(nt,rt,$,lt,-1),et[nt]+=Qt(St(_,lt,u),u)-Qt(St(it[nt],it[M],u),u)}}let mt=S(v(M,w)),$t=y(M,Y),De=pt(o,s,A(mt));for(let $=0;$<f;$++)$t[$]-=De[$];let Ft=x(mt);for(let $=0;$<u;$++)Ft[$]=-Ft[$];let wt=$t.slice(),Ot=Ft.slice();n.solveNormal(wt,Ot);{let $=S(ht(o,s,wt)),ut=E(Ot);for(let K=0;K<N;K++)$[K]+=ut[K];let nt=pt(o,s,A($)),lt=x($);for(let K=0;K<f;K++)nt[K]=$t[K]-nt[K]-wt[K];for(let K=0;K<u;K++)lt[K]=Ft[K]-lt[K];n.solveNormal(nt,lt);for(let K=0;K<f;K++)wt[K]+=nt[K];for(let K=0;K<u;K++)Ot[K]+=lt[K]}let Pt=S(ht(o,s,wt)),$e=E(Ot);for(let $=0;$<N;$++)Pt[$]=-(mt[$]+Pt[$]+$e[$]);let Pe=A(Pt);for(let $=0;$<i;$++){let ut=-2*(k($,Pe,w)+k($,Y,wt));b[$][M]=et[$]+ut/X}}for(let M=0;M<i;M++){for(let j=M+1;j<i;j++){let H=(b[M][j]+b[j][M])/2;b[M][j]=H,b[j][M]=H}let q=-2*Z[M]/(X*ot);b[M][i]=q,b[i][M]=q}b[i][i]=6*P/(X*X)-2*B/X;let R=[...U.map((M,q)=>M+Z[q]/X),-2*P/(X*ot)+2*B/ot],V=te(_.map(M=>X*M),u),L=[...ft.map((M,q)=>te(St(it[q],_,u).map(j=>-X*j),u)),te(_.map(M=>2*ot*M),u)];return{varpar:[...r,ot],deviance:Q,gradient:R,phiGradient:U,prssGradient:Z,prss:P,hessian:b,beta:Array.from(n.beta),vcov:V,jacobian:L}}var ee=1e-8,fo=Math.sqrt(Number.EPSILON),io=1e-8,Re=new WeakMap;function je(t){if(!Number.isFinite(t))return Number.isNaN(t)?"nan":t>0?"inf":"-inf";let[r,e]=t.toExponential(1).split("e"),n=Number(e);return`${r}e${n<0?"-":"+"}${String(Math.abs(n)).padStart(2,"0")}`}function mo(t){let r=[],e=t.filter(s=>s<-ee),n=t.filter(s=>Math.abs(s)<ee),o=s=>s===1?"eigenvalue":"eigenvalues";return e.length>0&&r.push(`Model failed to converge with ${e.length} negative ${o(e.length)}: ${e.map(je).join(" ")}`),n.length>0&&r.push(`Model may not have converged with ${n.length} ${o(n.length)} close to zero: ${n.map(je).join(" ")}`),r}function It(t){let r=Re.get(t);if(r!==void 0)return r;let e=dt(t),n=uo(e.structure,e.theta,e.reml);return Re.set(t,n),n}function uo(t,r,e){let n=Oe(t,r,e),o=n.varpar.length,s=Bt(n.hessian,{symmetric:!0}),a=s.values,c=s.vectors,l=Array.from({length:o},()=>new Array(o).fill(0));return a.forEach((h,m)=>{if(h>ee)for(let w=0;w<o;w++){let N=2*c[w][m]/h;for(let u=0;u<o;u++)l[w][u]+=N*c[u][m]}}),{varpar:n.varpar,hessian:n.hessian,hessianEigenvalues:a,vcovVarpar:l,beta:n.beta,sigma:n.varpar[o-1],vcov:n.vcov,jacobian:n.jacobian,warnings:mo(a)}}var kt=(t,r)=>{let e=0;for(let n=0;n<t.length;n++){let o=t[n];if(o===0)continue;let s=r[n];for(let a=0;a<t.length;a++)e+=o*s[a]*t[a]}return e},_t=(t,r)=>t.reduce((e,n,o)=>e+n*r[o],0);function qt(t,r,e,n=t.beta){if(r.some(Number.isNaN)||Number.isNaN(e))return{estimate:NaN,stdError:NaN,df:NaN,tValue:NaN,pValue:NaN};let o=_t(r,n),s=kt(r,t.vcov),a=Math.sqrt(s),c=t.jacobian.map(w=>kt(r,w)),l=2*s*s/kt(c,t.vcovVarpar),h=(o-e)/a,m=2*fe(Math.abs(h),l,!1,!1);return{estimate:o,stdError:a,df:l,tValue:h,pValue:m}}function Lt(t,r,e,n){let o=t.sigma*t.sigma;return{sumSq:r*o*e,meanSq:r*o,numDF:e,denDF:n,F:r,pValue:le(r,e,n,!1,!1)}}function po(t){if(t.length===1)return t[0];if(t.every((e,n)=>n===0||Math.abs(e-t[n-1])<io))return t.reduce((e,n)=>e+n,0)/t.length;if(t.some(e=>e<=2))return 2;let r=t.reduce((e,n)=>e+n/(n-2),0);return 2*r/(r-t.length)}function ho(t,r,e,n){return oe(It(t),r,e,n)}function oe(t,r,e,n){let o=r.length;if(o===0)return;let s=e??new Array(o).fill(0);if(o===1){let p=qt(t,r[0],s[0]);return Lt(t,p.tValue*p.tValue,1,p.df)}if(r.some(p=>p.some(Number.isNaN))||s.some(Number.isNaN))return Lt(t,NaN,NaN,NaN);let a=r.map(p=>t.vcov.map((S,A)=>p.reduce((x,E,I)=>x+E*t.vcov[I][A],0))),c=Bt(a.map(p=>r.map(S=>_t(p,S))),{symmetric:!0}),l=c.values,h=Math.max(fo*l[0],0),m=0;for(;m<o&&l[m]>h;)m++;if(m===0)return;m<o&&s.some(p=>p!==0)&&n.add("Contrast is rank deficient and test may be affected");let w=t.beta;if(s.some(p=>p!==0)){let p=zt(r.map(S=>[...S]));w=t.beta.map((S,A)=>S-_t(p[A],s))}let N=t.beta.length,u=Array.from({length:m},(p,S)=>Array.from({length:N},(A,x)=>r.reduce((E,I,g)=>E+c.vectors[g][S]*I[x],0)));if(m===1){let p=qt(t,u[0],0,w);return Lt(t,p.tValue*p.tValue,1,p.df)}let f=0,i=[];return u.forEach((p,S)=>{f+=_t(p,w)**2/l[S];let A=t.jacobian.map(x=>kt(p,x));i.push(2*l[S]*l[S]/kt(A,t.vcovVarpar))}),Lt(t,f/m,m,po(i))}function go(t,r={}){let e=r.ddf??"Satterthwaite";if(e!=="Satterthwaite"&&e!=="lme4")throw new RangeError(`ddf must be "Satterthwaite" or "lme4", not ${JSON.stringify(e)}`);let o=[...dt(t).structure.xColNames];if(e==="lme4"){let{estimate:l,stdError:h,tValue:m}=t.coefTable;return{ddf:e,names:o,estimate:[...l],stdError:[...h],tValue:[...m],messages:[],warnings:[]}}let s=It(t),a=o.length,c=o.map((l,h)=>qt(s,Array.from({length:a},(m,w)=>w===h?1:0),0));return{ddf:e,names:o,estimate:c.map(l=>l.estimate),stdError:c.map(l=>l.stdError),df:c.map(l=>l.df),tValue:c.map(l=>l.tValue),pValue:c.map(l=>l.pValue),messages:[],warnings:[...s.warnings]}}function wo(t,r){if(!Array.isArray(t))throw new TypeError("L must be an array of numbers or an array of rows");let e=t.length>0&&Array.isArray(t[0])?t.map(n=>[...n]):[[...t]];for(let n of e){if(!Array.isArray(n)||n.some(o=>typeof o!="number"))throw new TypeError("L must be an array of numbers or an array of rows");if(n.length!==r)throw new TypeError(`each contrast must have ${r} values (one per fixed effect), not ${n.length}`)}return e}function vo(t,r,e={}){let o=dt(t).structure.xColNames.length,s=wo(r,o),a=e.joint??!0,c=e.confint??!0,l=e.level??.95;if(typeof l!="number"||!(l>=0&&l<=1))throw new RangeError("level must be a number between 0 and 1");let h=e.rhs??0,m=typeof h=="number"?new Array(s.length).fill(h):[...h];if(m.length!==s.length||m.some(i=>typeof i!="number"))throw new TypeError(`rhs must be a number or have one value per contrast (${s.length})`);let w=new At,N=It(t);if(N.warnings.forEach(i=>w.add(i)),a){let i=o===0?void 0:ho(t,s,m,w),p=S=>i===void 0?[]:[i[S]];return{joint:!0,sumSq:p("sumSq"),meanSq:p("meanSq"),numDF:p("numDF"),denDF:p("denDF"),F:p("F"),pValue:p("pValue"),messages:[],warnings:w.list}}let u=o===0?[]:s.map((i,p)=>qt(N,i,m[p])),f={joint:!1,estimate:u.map(i=>i.estimate),stdError:u.map(i=>i.stdError),df:u.map(i=>i.df),tValue:u.map(i=>i.tValue),pValue:u.map(i=>i.pValue),messages:[],warnings:w.list};if(c){let i=u.map(p=>ie((1-l)/2,p.df,!1,!1));f.lower=u.map((p,S)=>p.estimate-p.stdError*i[S]),f.upper=u.map((p,S)=>p.estimate+p.stdError*i[S])}return f}var bo=Math.log10(2);function yo(t){let r=new DataView(new ArrayBuffer(8));r.setFloat64(0,t);let e=r.getUint16(0)>>4&2047;if(e>0)return e-1023;let n=r.getUint32(0)&1048575,o=r.getUint32(4);return(n!==0?32+(31-Math.clz32(n)):31-Math.clz32(o))-1074}function Vt(t){let r=1;for(let e=0;e<t;e++)r*=10;return r}function xo(t){let r=Math.floor(t),e=t-r,n=e<.5?r:e>.5?r+1:r%2===0?r:r+1;return n===0?t<0?-0:0:n}function Ao(t,r=0){if(Number.isNaN(t)||Number.isNaN(r))return NaN;if(!Number.isFinite(t)||t===0||r>323)return t;if(r<-308)return 0;if(r===0)return xo(t);let e=Math.floor(r+.5),n=Math.abs(t);if(bo*(.5+yo(n))+e>15)return t;let s,a,c;if(e<=308){let w=e>=0?Vt(e):1/Vt(-e),N=n*w;c=Math.floor(N),s=c/w,a=Math.ceil(N)/w}else{let w=Vt(308),N=Vt(e-308),u=n*w*N;c=Math.floor(u),s=c/w/N,a=Math.ceil(u)/w/N}let l=a-n,h=n-s,m=l<h||l===h&&c%2===1?a:s;return t<0?-m:m}function Ct(t,r=7){let e=0;for(let o of t)for(let s of o)Math.abs(s)>e&&(e=Math.abs(s));let n=e>0?Math.max(0,r-Math.log10(e)):r;return t.map(o=>o.map(s=>Ao(s,n)))}var ne={type:"num",value:1,text:"1"};function Le(t,r,e={}){let n=Rt(t,!1,!0);if(n.response===void 0)throw new TypeError("the formula has no response");if(typeof r!="object"||r===null)throw new TypeError("data must be an object of columns");let{fixed:o}=jt(n.rhs),s=o??ne,a=e.contrasts===void 0?{}:{contrasts:e.contrasts,contrastVariables:xt({response:n.response,rhs:s},Object.keys(r)).variables},c=bt(n,r,{...e.levels===void 0?{}:{levels:e.levels},dropUnusedLevels:!0,...a},s),{terms:l,frame:h}=c,m=c.colNames.map((f,i)=>i);if(m.length>0){let f=vt(c.x),i=new Set(f.pivot.slice(f.rank));m=m.filter(p=>!i.has(p))}let w=new Set(l.terms.flat()),N=l.variables.map((f,i)=>({name:f,v:i})).filter(({v:f})=>w.has(f)),u={};for(let{name:f,v:i}of N)h.variables[i].kind==="factor"&&(u[f]=e.contrasts?.[f]??"contr.treatment");return{x:c.x.map(f=>m.map(i=>f[i])),colNames:m.map(f=>c.colNames[f]),assign:m.map(f=>c.assign[f]),intercept:l.intercept,terms:l.terms.map((f,i)=>({label:l.termLabels[i],variables:f.map(p=>l.variables[p])})),variables:N.map(({name:f,v:i})=>({name:f,frame:h.variables[i]})),contrasts:u}}var se=(t,r=t[0]?.length??0)=>Array.from({length:r},(e,n)=>t.map(o=>o[n]));function re(t,r,e=r[0]?.length??0){return t.map(n=>{let o=new Array(e).fill(0);return n.forEach((s,a)=>{let c=r[a];for(let l=0;l<e;l++)o[l]+=s*c[l]}),o})}function _e(t,r){let e=Array.from({length:r},()=>new Array(r).fill(0));for(let n=0;n<r;n++)for(let o=n;o<r;o++){let s=0;for(let a of t)s+=a[n]*a[o];e[n][o]=s,e[o][n]=s}return e}var Dt=(t,r)=>t.map(e=>r.map(n=>e[n])),ze=1e-6;function qe(t){let r=t.length,e=Array.from({length:r},(o,s)=>Array.from({length:r},(a,c)=>s===c?1:0)),n=Array.from({length:r},()=>new Array(r).fill(0));for(let o=0;o<r;o++){for(let a=0;a<r;a++){let c=t[o][a];for(let l=0;l<o;l++)c-=e[o][l]*n[l][a];n[o][a]=c}let s=n[o][o];for(let a=o+1;a<r;a++){if(Math.abs(s)<ze){e[a][o]=0;continue}let c=t[a][o];for(let l=0;l<o;l++)c-=e[a][l]*n[l][o];e[a][o]=c/s}}for(let o of[e,n])for(let s of o)s.forEach((a,c)=>{Math.abs(a)<ze&&(s[c]=0)});return{L:e,U:n}}function Ve(t){let r=new Set(t.variables.filter(n=>n.frame.kind==="numeric").map(n=>n.name)),e=n=>n.variables.filter(o=>r.has(o)).sort().join("\0");return t.terms.map(n=>t.terms.map((o,s)=>({b:o,k:s})).filter(({b:o})=>n.variables.every(s=>o.variables.includes(s))&&o.variables.length>n.variables.length&&e(n)===e(o)).map(({k:o})=>o))}var yt=(t,r)=>t.flatMap((e,n)=>e===r+1?[n]:[]);function No(t,r,e,n,o){return{term:t,rows:e.map(s=>n[s]),columns:[...o],values:e.map(s=>[...r[s]])}}function Eo(t){let r=t.colNames.length;if(r===0||r===1&&t.intercept)return[];let e=r===1?[[1]]:se(qe(_e(t.x,r)).L,r);return t.terms.map((n,o)=>No(n.label,e,yt(t.assign,o),t.colNames,t.colNames))}function Mo(t){let r=t.colNames.length,e=Ve(t);return t.terms.map((n,o)=>{let s=yt(t.assign,o);if(e[o].length===0){let u=s.map(f=>Array.from({length:r},(i,p)=>f===p?1:0));return{term:n.label,rows:s.map(f=>t.colNames[f]),columns:[...t.colNames],values:u}}let a=[o,...e[o]].flatMap(u=>yt(t.assign,u)),c=new Set(a),l=[...t.colNames.map((u,f)=>f).filter(u=>!c.has(u)),...a],h=se(qe(_e(Dt(t.x,l),r)).L,r),m=new Set(s),w=l.flatMap((u,f)=>m.has(u)?[f]:[]),N=w.map(u=>{let f=new Array(r).fill(0);return l.forEach((i,p)=>f[i]=h[u][p]),f});return{term:n.label,rows:w.map(u=>t.colNames[l[u]]),columns:[...t.colNames],values:N}})}function So(t){let r=t.x.length,e=new Map(t.variables.map(l=>[l.name,l.frame])),n=[],o=[];t.intercept&&(n.push(new Array(r).fill(1)),o.push("(Intercept)"));let s=l=>{let h=e.get(l);return h.kind==="numeric"?[{name:l,values:h.values}]:h.levels.map((m,w)=>({name:l+m,values:h.codes.map(N=>N===w?1:0)}))};for(let l of t.terms){let h=s(l.variables[0]);for(let m of l.variables.slice(1)){let w=[];for(let N of s(m))for(let u of h)w.push({name:`${u.name}:${N.name}`,values:u.values.map((f,i)=>f*N.values[i])});h=w}for(let m of h)n.push(m.values),o.push(m.name)}let a=o.filter((l,h)=>n[h].every(m=>m===0)),c=a.length>0?[`Missing cells for: ${a.join(", ")}.
4
+ Interpret type III hypotheses with care.`]:[];return{x:Array.from({length:r},(l,h)=>n.map(m=>m[h])),colNames:o,messages:c}}function ko(t){let r={},e={};for(let{name:h,frame:m}of t.variables)m.kind==="numeric"?r[h]=m.values:(r[h]=m.codes.map(w=>m.levels[w]),e[h]=m.levels);let n=h=>h.reduce((m,w)=>m===void 0?w:{type:"binary",op:"+",left:m,right:w},void 0),o=h=>({type:"var",name:h}),s={response:void 0,rhs:n(t.variables.map(h=>o(h.name)))??ne},a=t.terms.map(h=>h.variables.map(o).reduce((m,w)=>({type:"binary",op:":",left:m,right:w}))),c=bt(s,r,{levels:e,intercept:t.intercept},n(a)??ne),l=c.colNames.map((h,m)=>m);if(l.length>0){let h=vt(c.x);h.rank<l.length&&(l=h.pivot.slice(0,h.rank))}return{x:Dt(c.x,l),colNames:l.map(h=>c.colNames[h]),assign:l.map(h=>c.assign[h])}}var Io=1e-8;function To(t){let r=Object.values(t.contrasts).every(u=>u==="contr.treatment"),e=r?{x:t.x,colNames:t.colNames,assign:t.assign}:ko(t),n=e.colNames.length,o=So(t),s=zt(e.x),a=Ct(se(re(s,o.x,o.colNames.length),o.colNames.length)),c=Ve(t),l=t.terms.map((u,f)=>({k:f,order:u.variables.length})).sort((u,f)=>f.order-u.order||u.k-f.k);for(let{k:u}of l){if(c[u].length===0)continue;let f=yt(e.assign,u);if(f.length===0)continue;let i=c[u].flatMap(A=>yt(e.assign,A)),p=Dt(a,f);i.length>0&&(p=pe(vt(Dt(a,i)),p));let S=Ct(p);a.forEach((A,x)=>f.forEach((E,I)=>A[E]=S[x][I]))}let h=new Map(o.colNames.map((u,f)=>[u,f])),m=e.colNames.map(u=>{let f=h.get(u);if(f===void 0)throw new Error(`lmerHypotheses: the column '${u}' of the model matrix is not a column of the full-dummy matrix`);return a[f]}),w=r?void 0:Ct(re(s,t.x,t.colNames.length));return{hypotheses:t.terms.map((u,f)=>{let i=yt(e.assign,f).filter(S=>m.reduce((A,x)=>A+Math.abs(x[S]),0)>Io),p=i.map(S=>m.map(A=>A[S]));return{term:u.label,rows:i.map(S=>e.colNames[S]),columns:[...t.colNames],values:w===void 0?p:re(p,w,t.colNames.length)}}),messages:o.messages}}function Ce(t,r="III"){return t.colNames.length<=1||t.terms.length<=1||r==="I"?{hypotheses:Eo(t),messages:[]}:r==="II"?{hypotheses:Mo(t),messages:[]}:To(t)}var Fo={I:"I",II:"II",III:"III",1:"I",2:"II",3:"III"};function Oo(t,r){let{structure:e,data:n,options:o}=dt(t),s={};o.contrasts!==void 0&&(s.contrasts=o.contrasts),o.levels!==void 0&&(s.levels=o.levels);let a=Le(t.formula,n,s);if(a.colNames.length!==e.xColNames.length||a.colNames.some((c,l)=>c!==e.xColNames[l]))throw new Error("lmerAnova: the columns of the hypotheses differ from the fit's fixed effects");return a.terms.length===0?{hypotheses:{hypotheses:[],messages:[]},termLabels:[]}:{hypotheses:Ce(a,r),termLabels:a.terms.map(c=>c.label)}}function Ro(t,{hypotheses:r},e,n){let o=[],s=[];for(let a of r){let c=a.values.length===0?void 0:oe(t,a.values,void 0,n);c!==void 0&&(o.push(a.term),s.push(c))}for(let a of e)o.includes(a)||(o.push(a),s.push({sumSq:NaN,meanSq:NaN,numDF:NaN,denDF:NaN,F:NaN,pValue:NaN}));return{terms:o,rows:s}}function jo(t,r){let e=Fo[String(r.type??"III")];if(e===void 0)throw new RangeError(`type must be "I", "II" or "III", not ${JSON.stringify(r.type)}`);let{hypotheses:n,termLabels:o}=Oo(t,e),s=It(t),a=new At;s.warnings.forEach(m=>a.add(m));let{terms:c,rows:l}=Ro(s,n,o,a),h=m=>l.map(w=>w[m]);return{type:e,terms:c,sumSq:h("sumSq"),meanSq:h("meanSq"),numDF:h("numDF"),denDF:h("denDF"),F:h("F"),pValue:h("pValue"),messages:[...n.messages],warnings:a.list}}function zo(t,r){if(t.length<2)throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");let e=t.map(dt);if(t.some(i=>i.nObs!==t[0].nObs))throw new Error("models were not all fitted to the same size of dataset");if(e.some(i=>i.data!==e[0].data))throw new Error("all models must be fit to the same data object");let n=new At,o=[],s=t.map((i,p)=>`MODEL${p+1}`);if(r.names!==void 0){if(r.names.length!==t.length||r.names.some(i=>typeof i!="string"))throw new TypeError(`names must be ${t.length} strings, one per fit`);new Set(r.names).size===r.names.length?s=[...r.names]:n.add("failed to find model names, assigning generic names")}let a=r.refit??!0,c;a?(t.some(i=>i.REML)&&o.push("refitting model(s) with ML (instead of REML)"),c=t.map((i,p)=>{if(!i.REML)return i.logLik;let{data:S,options:A,criterion:x}=e[p];return Kt(i.formula,S,{...A,REML:!1},x).logLik})):(t.some(i=>i.REML)&&t.some(i=>!i.REML)&&n.add("some models fit with REML = TRUE, some not"),c=t.map(i=>i.logLik));let l=t.map((i,p)=>p).sort((i,p)=>t[i].df-t[p].df||i-p),h=t[0].nObs,m=l.map(i=>t[i].df),w=l.map(i=>c[i]),N=w.map((i,p)=>p===0?NaN:2*Math.max(0,i-w[p-1])),u=m.map((i,p)=>p===0?NaN:i-m[p-1]),f=N.map((i,p)=>p===0||u[p]===0?NaN:ce(i,u[p]/2,2,!1,!1));return{names:l.map(i=>s[i]),npar:m,AIC:w.map((i,p)=>-2*i+2*m[p]),BIC:w.map((i,p)=>-2*i+Math.log(h)*m[p]),logLik:w,deviance:w.map(i=>-2*i),Chisq:N,Df:u,pValue:f,messages:o,warnings:n.list}}function Lo(t,r={}){return Array.isArray(t)?zo(t,r):jo(t,r)}export{lo as lmer,Lo as lmerAnova,vo as lmerContest,go as lmerSummary};
@@ -1,6 +1,13 @@
1
1
  import type { DataFrame } from "./modelFrame.js";
2
2
  import type { ContrastName } from "./modelMatrix.js";
3
3
  import { type MixedModelStructure } from "./mixedStructure.js";
4
+ /**
5
+ * A contrast of a factor of lmer's fixed effects: R's `contr.treatment`, `contr.sum`, `contr.helmert` or `contr.poly`
6
+ * (orthogonal polynomials in the level scores 1, 2, ..., columns `.L`, `.Q`, `.C`, `^4`, ...).
7
+ *
8
+ * @category Mixed models
9
+ */
10
+ export type LmerContrastName = ContrastName | "contr.poly";
4
11
  /**
5
12
  * Options of {@link lmer}.
6
13
  *
@@ -10,11 +17,12 @@ export interface LmerOptions {
10
17
  /** Whether to minimise the REML criterion (default `true`) or the ML deviance (`false`). */
11
18
  REML?: boolean;
12
19
  /**
13
- * A contrast per factor of the fixed-effects part (default `"contr.treatment"`); the random-effects terms always use
14
- * treatment contrasts. A name that is not a variable of the fixed-effects part (a grouping variable alone included)
15
- * gives the warning `variable 'B' is absent, its contrast will be ignored`.
20
+ * A contrast per factor of the fixed-effects part: `"contr.treatment"` (default), `"contr.sum"`, `"contr.helmert"` or
21
+ * `"contr.poly"` (see {@link LmerContrastName}); the random-effects terms always use treatment contrasts. A name that
22
+ * is not a variable of the fixed-effects part (a grouping variable alone included) gives the warning
23
+ * `variable 'B' is absent, its contrast will be ignored`.
16
24
  */
17
- contrasts?: Record<string, ContrastName>;
25
+ contrasts?: Record<string, LmerContrastName>;
18
26
  /** The order of the levels of a factor (`{ A: ["c", "a", "b"] }`), as `factor(x, levels = ...)` in R. */
19
27
  levels?: Record<string, readonly string[]>;
20
28
  }
@@ -155,6 +163,31 @@ export type MixedCriterion = (s: MixedModelStructure, theta: readonly number[],
155
163
  * @category Mixed models
156
164
  */
157
165
  export declare function lmer(formula: string, data: DataFrame, options?: LmerOptions): LmerResult;
166
+ /**
167
+ * What a fit by {@link lmer} was made from and with (internal: not exported from the package), for the functions that
168
+ * work on a fit beyond its result fields (lmerTest's tests in src/models/lmerTest.ts, the ANOVA tables, the comparison
169
+ * of fits): they need the model's structure, the data object (model comparison requires the same object), the options
170
+ * (to refit, for example by maximum likelihood) and the criterion (so that a refit uses the same one).
171
+ */
172
+ export interface LmerInternals {
173
+ /** The structure of the model (X, Z, the terms, the layout of θ, the model frame's rows) */
174
+ structure: MixedModelStructure;
175
+ /** The data frame given to lmer (the same object, not a copy) */
176
+ data: DataFrame;
177
+ /** The options given to lmer (a copy) */
178
+ options: LmerOptions;
179
+ /** Whether the REML criterion was minimised */
180
+ reml: boolean;
181
+ /** The criterion with its gradient that was minimised (the sparse one, or the injected one of the regression test) */
182
+ criterion: MixedCriterion;
183
+ /** The estimate θ̂ (a copy, unaffected by changes to the result's `theta`) */
184
+ theta: number[];
185
+ }
186
+ /**
187
+ * The internals of a fit (see {@link LmerInternals}). Internal. Throws a TypeError for an object that is not a result
188
+ * returned by {@link lmer}.
189
+ */
190
+ export declare function lmerInternals(fit: LmerResult): LmerInternals;
158
191
  /**
159
192
  * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
160
193
  * test of the sparse computation fits with the dense reference implementation through it.
@@ -367,6 +367,21 @@ function minimiseCriterion(s, reml, criterion) {
367
367
  export function lmer(formula, data, options = {}) {
368
368
  return lmerWithCriterion(formula, data, options, sparseCriterion);
369
369
  }
370
+ /**
371
+ * The internals of every result returned by {@link lmer} (and {@link lmerWithCriterion}), keyed by the result object
372
+ * itself: a copy of a result (`{ ...fit }`) has none.
373
+ */
374
+ const internalsByFit = new WeakMap();
375
+ /**
376
+ * The internals of a fit (see {@link LmerInternals}). Internal. Throws a TypeError for an object that is not a result
377
+ * returned by {@link lmer}.
378
+ */
379
+ export function lmerInternals(fit) {
380
+ const internals = typeof fit === "object" && fit !== null ? internalsByFit.get(fit) : undefined;
381
+ if (internals === undefined)
382
+ throw new TypeError("fit must be a result returned by lmer (not a copy of one)");
383
+ return internals;
384
+ }
370
385
  /**
371
386
  * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
372
387
  * test of the sparse computation fits with the dense reference implementation through it.
@@ -429,7 +444,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
429
444
  const messages = [...s.messages];
430
445
  if (singular)
431
446
  messages.push("boundary (singular) fit: see help('isSingular')");
432
- return {
447
+ const result = {
433
448
  formula,
434
449
  REML: reml,
435
450
  nObs: n,
@@ -454,4 +469,6 @@ export function lmerWithCriterion(formula, data, options, criterion) {
454
469
  messages,
455
470
  warnings: [...s.warnings],
456
471
  };
472
+ internalsByFit.set(result, { structure: s, data, options: { ...options }, reml, criterion, theta: [...theta] });
473
+ return result;
457
474
  }
@@ -0,0 +1,138 @@
1
+ import { Warnings } from "./glmFamily.js";
2
+ import { type LmerResult } from "./lmer.js";
3
+ import { type HypothesisType, type LmerHypotheses } from "./lmerHypotheses.js";
4
+ import { type LmerFRow, type LmerSatterthwaite } from "./lmerTest.js";
5
+ /**
6
+ * Options of {@link lmerAnova} for one fit.
7
+ *
8
+ * @category Mixed models
9
+ */
10
+ export interface LmerAnovaOptions {
11
+ /** The type of the sums of squares: `"III"` (default), `"II"` or `"I"` (also `3`, `2`, `1`). */
12
+ type?: LmerAnovaType | 1 | 2 | 3;
13
+ }
14
+ /**
15
+ * Result of {@link lmerAnova} for one fit: lmerTest's ANOVA table, one row per term of the fixed effects.
16
+ *
17
+ * @category Mixed models
18
+ */
19
+ export interface LmerAnovaTable {
20
+ /** The type of the sums of squares. */
21
+ type: LmerAnovaType;
22
+ /** The terms (R's row names), in the order of the formula's terms; terms without a test come last. */
23
+ terms: string[];
24
+ /** R's `Sum Sq`: F σ² NumDF. */
25
+ sumSq: number[];
26
+ /** R's `Mean Sq`: F σ². */
27
+ meanSq: number[];
28
+ /** R's `NumDF`. */
29
+ numDF: number[];
30
+ /** R's `DenDF`: Satterthwaite's denominator degrees of freedom. */
31
+ denDF: number[];
32
+ /** R's `F value`. */
33
+ F: number[];
34
+ /** R's `Pr(>F)`. */
35
+ pValue: number[];
36
+ /** R's messages (Type III: `Missing cells for: ...`). */
37
+ messages: string[];
38
+ /** R's warnings (about the eigenvalues of the Hessian of the deviance in the variance parameters). */
39
+ warnings: string[];
40
+ }
41
+ /**
42
+ * Options of {@link lmerAnova} for several fits.
43
+ *
44
+ * @category Mixed models
45
+ */
46
+ export interface LmerCompareOptions {
47
+ /** Refit the REML fits by maximum likelihood before comparing them (default `true`). */
48
+ refit?: boolean;
49
+ /** The names of the models, in the order given (default `"MODEL1"`, `"MODEL2"`, ...). */
50
+ names?: readonly string[];
51
+ }
52
+ /**
53
+ * Result of {@link lmerAnova} for several fits: lme4's comparison table, one row per model, sorted by the number of
54
+ * parameters.
55
+ *
56
+ * @category Mixed models
57
+ */
58
+ export interface LmerCompareTable {
59
+ /** The models' names (R's row names), in the order of the rows. */
60
+ names: string[];
61
+ /** The number of parameters of each model (fixed effects, θ and σ). */
62
+ npar: number[];
63
+ /** Akaike's information criterion, −2 logLik + 2 npar. */
64
+ AIC: number[];
65
+ /** Schwarz's criterion, −2 logLik + log(n) npar. */
66
+ BIC: number[];
67
+ /** The log-likelihood (of the ML refit, or the fit's own with `refit: false`). */
68
+ logLik: number[];
69
+ /** −2 logLik (R's `-2*log(L)`). */
70
+ deviance: number[];
71
+ /** The likelihood-ratio statistic against the row before (NaN in the first row). */
72
+ Chisq: number[];
73
+ /** The difference of npar from the row before (NaN in the first row). */
74
+ Df: number[];
75
+ /** R's `Pr(>Chisq)` (NaN in the first row and where Df is 0). */
76
+ pValue: number[];
77
+ /** R's messages (`refitting model(s) with ML (instead of REML)`). */
78
+ messages: string[];
79
+ /** R's warnings (duplicated names, a mix of REML and ML fits without refitting). */
80
+ warnings: string[];
81
+ }
82
+ /**
83
+ * The type of the sums of squares of an ANOVA table of {@link lmerAnova}.
84
+ *
85
+ * @category Mixed models
86
+ */
87
+ export type LmerAnovaType = "I" | "II" | "III";
88
+ /** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
89
+ export declare function anovaHypotheses(fit: LmerResult, type: HypothesisType): {
90
+ hypotheses: LmerHypotheses;
91
+ termLabels: string[];
92
+ };
93
+ /** The rows of an ANOVA table from the hypotheses and given Satterthwaite quantities (internal) */
94
+ export declare function anovaRowsOf(s: LmerSatterthwaite, { hypotheses }: LmerHypotheses, termLabels: readonly string[], warnings: Warnings): {
95
+ terms: string[];
96
+ rows: LmerFRow[];
97
+ };
98
+ /**
99
+ * The ANOVA table of a linear mixed model fitted by {@link lmer}, with Satterthwaite's denominator degrees of freedom
100
+ * (lmerTest's `anova()`), or, given an array of fits, the likelihood-ratio comparison of the models (lme4's
101
+ * `anova()` of several fits). Equivalent to `lmerTest::anova()` in R.
102
+ *
103
+ * For one fit: each term of the fixed effects is tested jointly (an F-test of its hypothesis matrix, of Type III by
104
+ * default, II or I as in lmerTest; see {@link lmerContest} for the test). Type III with an empty cell of an
105
+ * interaction gives the message `Missing cells for: ...`. A term without a test is listed last, with NaN.
106
+ *
107
+ * For several fits (fitted to the same data object, with the same rows): REML fits are first refitted by maximum
108
+ * likelihood (unless `refit: false`), the models are sorted by their number of parameters, and each is compared with
109
+ * the one before by the likelihood-ratio test.
110
+ *
111
+ * @param fit A result of {@link lmer} (the object it returned, not a copy), or an array of at least two.
112
+ * @param options For one fit `type`; for several `refit` and `names`.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * // R: anova(lmerTest::lmer(y ~ x * f + (1 | g), data))
117
+ * const data = {
118
+ * y: [3.1, 4.0, 5.2, 6.8, 7.1, 8.3, 2.2, 3.5, 3.9, 5.9, 6.1, 7.4, 4.4, 5.0, 6.9, 3.0, 4.1, 4.9],
119
+ * x: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
120
+ * f: ["u", "u", "v", "v", "u", "v", "u", "v", "v", "u", "v", "u", "v", "u", "u", "v", "u", "v"],
121
+ * g: ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d", "d", "e", "e", "e", "f", "f", "f"],
122
+ * };
123
+ * const fit = lmer("y ~ x * f + (1 | g)", data);
124
+ * const t = lmerAnova(fit);
125
+ * t.terms; // ["x", "f", "x:f"]
126
+ * t.numDF; // [1, 1, 1]
127
+ * t.F; // [82.027, 0.44207, 0.53285]
128
+ * // R: anova(lme4::lmer(y ~ x + (1 | g), data), fit)
129
+ * const c = lmerAnova([lmer("y ~ x + (1 | g)", data), fit], { names: ["small", "full"] });
130
+ * c.npar; // [4, 6]
131
+ * c.Chisq; // [NaN, 0.6817]
132
+ * c.messages; // ["refitting model(s) with ML (instead of REML)"]
133
+ * ```
134
+ *
135
+ * @category Mixed models
136
+ */
137
+ export declare function lmerAnova(fit: LmerResult, options?: LmerAnovaOptions): LmerAnovaTable;
138
+ export declare function lmerAnova(fits: readonly LmerResult[], options?: LmerCompareOptions): LmerCompareTable;
@@ -0,0 +1,134 @@
1
+ // ANOVA tables of linear mixed models fitted by lmer (src/models/lmer.ts): lmerTest's Type I, II and III tables of one
2
+ // fit (each term's hypothesis tested jointly with Satterthwaite's denominator degrees of freedom), and lme4's
3
+ // likelihood-ratio comparison of several fits.
4
+ //
5
+ // Written for rStats.js (no ported code) from oracle/lmertest-behaviour.md (sections 2 and 3). The hypothesis
6
+ // matrices come from src/models/lmerHypotheses.ts, the F-tests from src/models/lmerTest.ts; the comparison refits REML
7
+ // fits by maximum likelihood with lmer's own minimiser (the exact ML optimum).
8
+ import { pgamma1 } from "../distributions/gamma.js";
9
+ import { Warnings } from "./glmFamily.js";
10
+ import { lmerInternals, lmerWithCriterion } from "./lmer.js";
11
+ import { fixedEffectsDescription, lmerHypotheses } from "./lmerHypotheses.js";
12
+ import { fTestOf, lmerSatterthwaite } from "./lmerTest.js";
13
+ const TYPES = { I: "I", II: "II", III: "III", 1: "I", 2: "II", 3: "III" };
14
+ /** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
15
+ export function anovaHypotheses(fit, type) {
16
+ const { structure, data, options } = lmerInternals(fit);
17
+ const descOptions = {};
18
+ if (options.contrasts !== undefined)
19
+ descOptions.contrasts = options.contrasts;
20
+ if (options.levels !== undefined)
21
+ descOptions.levels = options.levels;
22
+ const desc = fixedEffectsDescription(fit.formula, data, descOptions);
23
+ if (desc.colNames.length !== structure.xColNames.length || desc.colNames.some((c, j) => c !== structure.xColNames[j])) {
24
+ throw new Error("lmerAnova: the columns of the hypotheses differ from the fit's fixed effects");
25
+ }
26
+ // an intercept-only model (or one without fixed effects) has an empty table
27
+ if (desc.terms.length === 0)
28
+ return { hypotheses: { hypotheses: [], messages: [] }, termLabels: [] };
29
+ return { hypotheses: lmerHypotheses(desc, type), termLabels: desc.terms.map((t) => t.label) };
30
+ }
31
+ /** The rows of an ANOVA table from the hypotheses and given Satterthwaite quantities (internal) */
32
+ export function anovaRowsOf(s, { hypotheses }, termLabels, warnings) {
33
+ const terms = [];
34
+ const rows = [];
35
+ for (const h of hypotheses) {
36
+ const row = h.values.length === 0 ? undefined : fTestOf(s, h.values, undefined, warnings);
37
+ if (row === undefined)
38
+ continue;
39
+ terms.push(h.term);
40
+ rows.push(row);
41
+ }
42
+ for (const label of termLabels) {
43
+ if (terms.includes(label))
44
+ continue;
45
+ terms.push(label);
46
+ rows.push({ sumSq: NaN, meanSq: NaN, numDF: NaN, denDF: NaN, F: NaN, pValue: NaN });
47
+ }
48
+ return { terms, rows };
49
+ }
50
+ function anovaOfFit(fit, options) {
51
+ const type = TYPES[String(options.type ?? "III")];
52
+ if (type === undefined)
53
+ throw new RangeError(`type must be "I", "II" or "III", not ${JSON.stringify(options.type)}`);
54
+ const { hypotheses, termLabels } = anovaHypotheses(fit, type);
55
+ const s = lmerSatterthwaite(fit);
56
+ const warnings = new Warnings();
57
+ s.warnings.forEach((w) => warnings.add(w));
58
+ const { terms, rows } = anovaRowsOf(s, hypotheses, termLabels, warnings);
59
+ const column = (k) => rows.map((r) => r[k]);
60
+ return {
61
+ type,
62
+ terms,
63
+ sumSq: column("sumSq"),
64
+ meanSq: column("meanSq"),
65
+ numDF: column("numDF"),
66
+ denDF: column("denDF"),
67
+ F: column("F"),
68
+ pValue: column("pValue"),
69
+ messages: [...hypotheses.messages],
70
+ warnings: warnings.list,
71
+ };
72
+ }
73
+ function compareFits(fits, options) {
74
+ if (fits.length < 2)
75
+ throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
76
+ const internals = fits.map(lmerInternals);
77
+ if (fits.some((f) => f.nObs !== fits[0].nObs))
78
+ throw new Error("models were not all fitted to the same size of dataset");
79
+ if (internals.some((i) => i.data !== internals[0].data))
80
+ throw new Error("all models must be fit to the same data object");
81
+ const warnings = new Warnings();
82
+ const messages = [];
83
+ let names = fits.map((_, i) => `MODEL${i + 1}`);
84
+ if (options.names !== undefined) {
85
+ if (options.names.length !== fits.length || options.names.some((n) => typeof n !== "string")) {
86
+ throw new TypeError(`names must be ${fits.length} strings, one per fit`);
87
+ }
88
+ if (new Set(options.names).size === options.names.length)
89
+ names = [...options.names];
90
+ else
91
+ warnings.add("failed to find model names, assigning generic names");
92
+ }
93
+ const refit = options.refit ?? true;
94
+ let logLik;
95
+ if (refit) {
96
+ if (fits.some((f) => f.REML))
97
+ messages.push("refitting model(s) with ML (instead of REML)");
98
+ logLik = fits.map((f, i) => {
99
+ if (!f.REML)
100
+ return f.logLik;
101
+ const { data, options: o, criterion } = internals[i];
102
+ return lmerWithCriterion(f.formula, data, { ...o, REML: false }, criterion).logLik;
103
+ });
104
+ }
105
+ else {
106
+ if (fits.some((f) => f.REML) && fits.some((f) => !f.REML))
107
+ warnings.add("some models fit with REML = TRUE, some not");
108
+ logLik = fits.map((f) => f.logLik);
109
+ }
110
+ // sorted by the number of parameters (stable)
111
+ const order = fits.map((_, i) => i).sort((a, b) => fits[a].df - fits[b].df || a - b);
112
+ const n = fits[0].nObs;
113
+ const npar = order.map((i) => fits[i].df);
114
+ const ll = order.map((i) => logLik[i]);
115
+ const Chisq = ll.map((v, k) => (k === 0 ? NaN : 2 * Math.max(0, v - ll[k - 1])));
116
+ const Df = npar.map((v, k) => (k === 0 ? NaN : v - npar[k - 1]));
117
+ const pValue = Chisq.map((x, k) => (k === 0 || Df[k] === 0 ? NaN : pgamma1(x, Df[k] / 2, 2, false, false)));
118
+ return {
119
+ names: order.map((i) => names[i]),
120
+ npar,
121
+ AIC: ll.map((v, k) => -2 * v + 2 * npar[k]),
122
+ BIC: ll.map((v, k) => -2 * v + Math.log(n) * npar[k]),
123
+ logLik: ll,
124
+ deviance: ll.map((v) => -2 * v),
125
+ Chisq,
126
+ Df,
127
+ pValue,
128
+ messages,
129
+ warnings: warnings.list,
130
+ };
131
+ }
132
+ export function lmerAnova(fit, options = {}) {
133
+ return Array.isArray(fit) ? compareFits(fit, options) : anovaOfFit(fit, options);
134
+ }