@numero-uno-jpn/rstats 0.15.1 → 0.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.ja.md +8 -8
- package/README.md +8 -8
- package/dist/chunks/chunk-2CUKVVRO.js +2 -0
- package/dist/chunks/{chunk-3QTVXDUM.js → chunk-3WQCKGKP.js} +2 -2
- package/dist/chunks/{chunk-4ILI2FSB.js → chunk-4Z2XDWKV.js} +1 -1
- package/dist/chunks/{chunk-5XQZNKHZ.js → chunk-AJBLCNZ7.js} +2 -2
- package/dist/chunks/chunk-D4F7GQAY.js +2 -0
- package/dist/chunks/chunk-EBQMGCQZ.js +2 -0
- package/dist/chunks/{chunk-5OSQ76OO.js → chunk-HBMHR5SS.js} +2 -2
- package/dist/chunks/{chunk-7J4HW6VF.js → chunk-IBPWRQIF.js} +2 -2
- package/dist/chunks/chunk-JLAH3X77.js +2 -0
- package/dist/chunks/chunk-LG74QY5U.js +2 -0
- package/dist/chunks/{chunk-735NNFAS.js → chunk-PEYGUK32.js} +2 -2
- package/dist/chunks/{chunk-H4CHJMFU.js → chunk-PWVQVJTP.js} +1 -1
- package/dist/chunks/{chunk-LY2T6DA6.js → chunk-Q4PGYESP.js} +2 -2
- package/dist/chunks/{chunk-OLPTFKIZ.js → chunk-RCAL4VHM.js} +2 -2
- package/dist/chunks/{chunk-IQOVOHZG.js → chunk-SREPSVTT.js} +2 -2
- package/dist/chunks/chunk-UFT662QZ.js +2 -0
- package/dist/chunks/{chunk-Z3C3G5XI.js → chunk-VWJ74UHC.js} +2 -2
- package/dist/chunks/{chunk-SAZAEPZC.js → chunk-XNPU54NH.js} +1 -1
- package/dist/chunks/{chunk-5SQFDLNG.js → chunk-XPLDEK6D.js} +2 -2
- package/dist/chunks/{chunk-VOIJKNL2.js → chunk-YGT4P7EU.js} +1 -1
- package/dist/chunks/{chunk-GEJCBCMP.js → chunk-YVREYVI2.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +48 -4
- package/dist/distributions/beta.d.ts +1 -1
- package/dist/distributions/beta.js +64 -1
- package/dist/distributions/exponential.js +11 -2
- package/dist/distributions/f.js +104 -21
- package/dist/distributions/gamma.d.ts +13 -2
- package/dist/distributions/gamma.js +91 -12
- package/dist/distributions/geometric.js +16 -3
- package/dist/distributions/invgamma.js +56 -10
- package/dist/distributions/kumaraswamy.js +98 -17
- package/dist/distributions/lognormal.js +28 -4
- package/dist/distributions/nbeta.js +540 -37
- package/dist/distributions/nchisq.d.ts +25 -0
- package/dist/distributions/nchisq.js +330 -92
- package/dist/distributions/negbinomial.js +20 -5
- package/dist/distributions/normal.js +3 -0
- package/dist/distributions/nt.js +263 -51
- package/dist/distributions/pareto.js +68 -19
- package/dist/distributions/t.js +48 -10
- package/dist/distributions/triangular.js +66 -27
- package/dist/distributions/tukey.js +94 -50
- package/dist/distributions/uniform.js +12 -9
- package/dist/distributions/weibull.js +43 -8
- package/dist/distributions.js +2 -2
- package/dist/internal/ddexp.d.ts +5 -0
- package/dist/internal/ddexp.js +28 -3
- package/dist/internal/discrete.js +30 -7
- package/dist/internal/invert.js +49 -0
- package/dist/internal/noncentral.d.ts +34 -0
- package/dist/internal/noncentral.js +115 -2
- package/dist/internal/poissonMixture.d.ts +7 -2
- package/dist/internal/poissonMixture.js +113 -32
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +14 -14
- package/dist/special/dd.d.ts +1 -1
- package/dist/special/dd.js +4 -1
- package/dist/special/igam.js +93 -15
- package/dist/special/incbet.d.ts +10 -0
- package/dist/special/incbet.js +154 -48
- package/dist/special/incbetLargeA.js +47 -13
- package/dist/special/incbetPrefactor.d.ts +52 -0
- package/dist/special/incbetPrefactor.js +92 -0
- package/dist/special/incbetTemme.js +15 -3
- package/dist/special/loader.js +33 -7
- package/dist/special.js +2 -2
- package/dist/tests.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-5YMP4WAJ.js +0 -2
- package/dist/chunks/chunk-BDJPSEA7.js +0 -2
- package/dist/chunks/chunk-KO6QQPC6.js +0 -2
- package/dist/chunks/chunk-TYFGVCVQ.js +0 -2
- package/dist/chunks/chunk-UWBYDIOH.js +0 -2
- package/dist/chunks/chunk-UZHY5DWN.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 0.15.
|
|
2
|
-
import{a as q,c as p,e as v,f as O,h as U,o as F,r as g,s as j,v as N,y as R}from"./chunk-
|
|
1
|
+
/*! rStats.js 0.15.2 | 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 q,c as p,e as v,f as O,h as U,o as F,r as g,s as j,v as N,y as R}from"./chunk-XNPU54NH.js";function H(e,n={}){if(n.exact){let i=n.norm===void 0?"2":A(n.norm);if(i==="2"){let l=g(e,{nu:0,nv:0}).d,m=Math.min(...l);return m===0?1/0:Math.max(...l)/m}return j(e,{type:i})*j(N(e),{type:i})}let a=n.norm==="I"?"I":"O";if((n.method??"qr")==="direct"){if(n.triangular)return 1/C(p(e),(n.uplo??"U")==="U",a);let i=n.norm??"O",l=i.toUpperCase();if(l!=="1"&&l!=="O"&&l!=="I")throw new RangeError(`argument type[1]='${i}' must be one of '1','O', or 'I'`);return 1/R(e,{norm:l==="I"?"I":"O"})}let b=p(e),f=b.nrow<b.ncol?v(O(b)):e;return 1/C(p(F(U(f))),!0,a)}function C(e,n,a){return L(a==="I"?O(e):e,n)}function A(e){let n=e.toUpperCase();if(n==="1"||n==="O")return"O";if(n==="E")return"F";if(n==="I"||n==="F"||n==="M"||n==="2")return n;throw new RangeError(`invalid norm "${e}"`)}function L(e,n){let a=Math.min(e.nrow,e.ncol),b=e.nrow,f=(o,t)=>e.data[o+t*b],i=!n,l=0;for(let o=0;o<a;o++){let[t,u]=i?[o,a-o]:[0,o+1],s=0;for(let c=t;c<t+u;c++)s+=Math.abs(f(c,o));l=Math.max(l,s)}let m=1,r=new Float64Array(a),k=o=>{for(let t=0;t<a;t++)r[t]*=o};for(let o=0;o<a;o++){let t=i?a-1-o:o,u=f(t,t);if(r[t]!==0&&(m=r[t]>0?-Math.abs(m):Math.abs(m)),Math.abs(m-r[t])>Math.abs(u)){let d=Math.abs(u)/Math.abs(m-r[t]);k(d),m*=d}let s=m-r[t],c=-m-r[t],x=Math.abs(s),y=Math.abs(c);if(u!==0?(s/=u,c/=u):(s=1,c=1),o!==a-1){let[d,E]=i?[0,t-1]:[t+1,a-1];for(let M=d;M<=E;M++)y+=Math.abs(r[M]+c*f(t,M)),r[M]+=s*f(t,M),x+=Math.abs(r[M]);if(x<y){let M=c-s;s=c;for(let I=d;I<=E;I++)r[I]+=M*f(t,I)}}r[t]=s}k(1/$(r));let w=1;for(let o=0;o<a;o++){let t=i?o:a-1-o,u=f(t,t);if(Math.abs(r[t])>Math.abs(u)){let s=Math.abs(u)/Math.abs(r[t]);k(s),w*=s}if(u!==0?r[t]/=u:r[t]=1,o<a-1){let s=-r[t];if(i)for(let c=t+1;c<a;c++)r[c]+=s*f(c,t);else for(let c=0;c<t;c++)r[c]+=s*f(c,t)}}let h=1/$(r);return k(h),w*=h,l!==0?w/l:0}function $(e){let n=0;for(let a of e)n+=Math.abs(a);return n}function J(e,n={}){let a=n.tol??Math.sqrt(Number.EPSILON),b=p(e),{d:f,u:i,v:l}=g(e),m=b.nrow,r=b.ncol,k=q(r,m),w=Math.max(a*(f[0]??0),0);for(let h=0;h<f.length;h++){if(!(f[h]>w))continue;let o=1/f[h];for(let t=0;t<m;t++){let u=i[t][h]*o;for(let s=0;s<r;s++)k.data[s+t*r]+=l[s][h]*u}}return v(k)}export{H as a,J as b};
|
package/dist/descriptive.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 0.15.
|
|
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};
|
|
1
|
+
/*! rStats.js 0.15.2 | 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-VWJ74UHC.js";import"./chunks/chunk-3WQCKGKP.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-Q4PGYESP.js";import{a as ee,b as Le,c as Ce,d as Pe,e as Ue,f as qe}from"./chunks/chunk-SREPSVTT.js";import"./chunks/chunk-4Z2XDWKV.js";import"./chunks/chunk-IBPWRQIF.js";import{a as G,e as I,f as J}from"./chunks/chunk-PEYGUK32.js";import"./chunks/chunk-UFT662QZ.js";import{a as H}from"./chunks/chunk-HBMHR5SS.js";import{b as _,c as X}from"./chunks/chunk-PWVQVJTP.js";import"./chunks/chunk-2CUKVVRO.js";import"./chunks/chunk-LG74QY5U.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};
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
// (the beta(1/2, 1/2) distribution is symmetric).
|
|
9
9
|
import { vectorize } from "../internal/vectorize.js";
|
|
10
10
|
import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
|
|
11
|
-
import { ddAdd, ddLog, twoSum } from "../special/dd.js";
|
|
11
|
+
import { ddAdd, ddLog, ddMulNum, ddSub, twoSum } from "../special/dd.js";
|
|
12
|
+
import { ddExp } from "../internal/ddexp.js";
|
|
12
13
|
import { pbeta1, qbeta1 } from "./beta.js";
|
|
13
14
|
const valid = (a, b) => Number.isFinite(a) && Number.isFinite(b) && a < b;
|
|
14
15
|
export function darcsine1(x, a, b, log) {
|
|
@@ -26,6 +27,12 @@ export function darcsine1(x, a, b, log) {
|
|
|
26
27
|
return -LOGPI_DD[0] - 0.5 * l[0] - (LOGPI_DD[1] + 0.5 * l[1]);
|
|
27
28
|
}
|
|
28
29
|
const LOGPI_DD = [1.1447298858494002, 1.0265951162707826e-17];
|
|
30
|
+
/** log(2 / pi) and log(pi / 2) in double-double */
|
|
31
|
+
const LOG_2_OVER_PI_DD = [Math.LN2 - LOGPI_DD[0], 2.3190468138462996e-17 - LOGPI_DD[1]];
|
|
32
|
+
const LOG_HALF_PI_DD = [-LOG_2_OVER_PI_DD[0], -LOG_2_OVER_PI_DD[1]];
|
|
33
|
+
/** Below this z, asin(sqrt(z)) is sqrt(z) to double precision (the next term is z/6 relative) */
|
|
34
|
+
const TINY = 1e-20;
|
|
35
|
+
const MIN_NORMAL = 2 ** -1022;
|
|
29
36
|
export function parcsine1(q, a, b, lowerTail, logP) {
|
|
30
37
|
if (Number.isNaN(q) || !valid(a, b))
|
|
31
38
|
return NaN;
|
|
@@ -34,9 +41,23 @@ export function parcsine1(q, a, b, lowerTail, logP) {
|
|
|
34
41
|
if (q >= b)
|
|
35
42
|
return dt1(lowerTail, logP);
|
|
36
43
|
const w = b - a;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
44
|
+
const nearA = q - a <= b - q;
|
|
45
|
+
// distance to the nearer end, and the tail on that side
|
|
46
|
+
const d = nearA ? q - a : b - q;
|
|
47
|
+
const z = d / w;
|
|
48
|
+
if (z < TINY) {
|
|
49
|
+
// (2/pi) asin(sqrt(z)) = (2/pi) sqrt(z) (1 + z/6 + ...): sqrt(d) / sqrt(w), and its log from log d - log w, keep the
|
|
50
|
+
// digits where z is subnormal or 0
|
|
51
|
+
const l = ddAdd(LOG_2_OVER_PI_DD, ddMulNum(ddSub(ddLog([d, 0]), ddLog([w, 0])), 0.5));
|
|
52
|
+
const sq = (Math.sqrt(d) / Math.sqrt(w)) * (2 / Math.PI);
|
|
53
|
+
const near = sq >= MIN_NORMAL ? sq : Math.exp(l[0]);
|
|
54
|
+
if (lowerTail === nearA)
|
|
55
|
+
return logP ? l[0] + l[1] : near;
|
|
56
|
+
return logP ? Math.log1p(-near) : 1 - near;
|
|
57
|
+
}
|
|
58
|
+
if (nearA)
|
|
59
|
+
return pbeta1(z, 0.5, 0.5, lowerTail, logP);
|
|
60
|
+
return pbeta1(z, 0.5, 0.5, !lowerTail, logP);
|
|
40
61
|
}
|
|
41
62
|
export function qarcsine1(p, a, b, lowerTail, logP) {
|
|
42
63
|
if (Number.isNaN(p) || !valid(a, b))
|
|
@@ -44,6 +65,29 @@ export function qarcsine1(p, a, b, lowerTail, logP) {
|
|
|
44
65
|
const bd = quantileBoundaries(p, a, b, lowerTail, logP);
|
|
45
66
|
if (bd !== undefined)
|
|
46
67
|
return bd;
|
|
68
|
+
// Where the lower or upper probability is below e^-40, the distance to that end is w sin^2(pi p / 2) = w (pi p / 2)^2
|
|
69
|
+
// (1 - O(p^2)), from logs (sin^2 underflowed: qarcsine(1.7e-208, 0, 2.6e187) was 0, not 1.9e-228). The log of a
|
|
70
|
+
// tiny probability in double-double from its linear value (log p rounded loses eps |log p| relative); 1 - p is exact
|
|
71
|
+
// for p >= 1/2
|
|
72
|
+
const given = logP ? [p, 0] : ddLog([p, 0]);
|
|
73
|
+
const other = logP
|
|
74
|
+
? p > -Math.LN2
|
|
75
|
+
? ddLog([-Math.expm1(p), 0])
|
|
76
|
+
: [Math.log1p(-Math.exp(p)), 0]
|
|
77
|
+
: p >= 0.5
|
|
78
|
+
? ddLog([1 - p, 0])
|
|
79
|
+
: [Math.log1p(-p), 0];
|
|
80
|
+
const [lower, upper] = lowerTail ? [given, other] : [other, given];
|
|
81
|
+
for (const [lt, fromA] of [
|
|
82
|
+
[lower, true],
|
|
83
|
+
[upper, false],
|
|
84
|
+
]) {
|
|
85
|
+
if (!(lt[0] < -40))
|
|
86
|
+
continue;
|
|
87
|
+
const e = ddAdd(ddMulNum(ddAdd(lt, LOG_HALF_PI_DD), 2), ddLog([b - a, 0]));
|
|
88
|
+
const dist = e[0] < -746 ? 0 : ddExp(e)[0];
|
|
89
|
+
return fromA ? Math.min(a + dist, b) : Math.max(b - dist, a);
|
|
90
|
+
}
|
|
47
91
|
const z = qbeta1(p, 0.5, 0.5, lowerTail, logP);
|
|
48
92
|
if (z <= 0.5)
|
|
49
93
|
return a + (b - a) * z;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type Vectorizable, type VectorResult } from "../internal/vectorize.js";
|
|
2
2
|
import { type DensityOptions, type TailOptions } from "../internal/dpq.js";
|
|
3
3
|
import type { NoncentralOption } from "../internal/noncentral.js";
|
|
4
|
-
/** Log density (0 <
|
|
4
|
+
/** Log density (0 < a, b < Inf; also at x = 0 or 1, which a quantile search in log x reaches by underflow, as dbeta) */
|
|
5
5
|
export declare function dbetaLog(x: number, _xc: number, a: number, b: number): number;
|
|
6
6
|
export declare function dbeta1(x: number, a: number, b: number, log: boolean): number;
|
|
7
7
|
export declare function pbeta1(q: number, a: number, b: number, lowerTail: boolean, logP: boolean): number;
|
|
@@ -13,6 +13,7 @@ import { dbinomExponent } from "../special/loader.js";
|
|
|
13
13
|
import { ddAdd, ddLog, ddMul, ddNeg, twoSum } from "../special/dd.js";
|
|
14
14
|
import { dnbeta1, pnbeta1, qnbeta1 } from "./nbeta.js";
|
|
15
15
|
import { qnorm } from "./normal.js";
|
|
16
|
+
import { qgammaStd } from "./gamma.js";
|
|
16
17
|
/** Form x and 1 - x as a double-double pair based on the smaller of the two (no rounding of 1 - x brought in) */
|
|
17
18
|
function pair(x) {
|
|
18
19
|
return x <= 0.5 ? [[x, 0], twoSum(1, -x)] : [twoSum(1, -(1 - x)), [1 - x, 0]];
|
|
@@ -25,6 +26,10 @@ function pair(x) {
|
|
|
25
26
|
*/
|
|
26
27
|
function dbetaCore(x, a, b, log) {
|
|
27
28
|
const [xd, xcd] = pair(x);
|
|
29
|
+
if ((a + b) * Math.min(xd[0], xcd[0]) < 2.2250738585072014e-308) {
|
|
30
|
+
const l = dbetaDirectLog(xd, xcd, a, b);
|
|
31
|
+
return log ? l : Math.exp(l);
|
|
32
|
+
}
|
|
28
33
|
const { e } = dbinomExponent(a, b, xd, xcd);
|
|
29
34
|
// With m = ab/(a+b), log(denom)/2 = log(2 pi m)/2 and log(ab/(a+b)) - log(denom)/2 = log(m/(2 pi))/2
|
|
30
35
|
const m = (a * b) / (a + b);
|
|
@@ -59,8 +64,20 @@ function dbetaShape1Log(x, a, b) {
|
|
|
59
64
|
const t = ddAdd(ddLog([s, 0]), ddMul(twoSum(s, -1), ddLog(l)));
|
|
60
65
|
return t[0] + t[1];
|
|
61
66
|
}
|
|
62
|
-
/**
|
|
67
|
+
/**
|
|
68
|
+
* log f = (a - 1) log x + (b - 1) log(1 - x) - log B(a, b) directly, in double-double, for (a + b) x or (a + b)(1 - x)
|
|
69
|
+
* below the normal range: the deviances of dbinomExponent take the log of that product, which has then lost its
|
|
70
|
+
* digits or underflowed to 0 (dbeta(2.7e-289, 7.5e-126, 7.6e-180) threw a TypeError). Such products need tiny shapes
|
|
71
|
+
* or x, where the terms are of moderate size and Loader's form brings nothing
|
|
72
|
+
*/
|
|
73
|
+
function dbetaDirectLog(xd, xcd, a, b) {
|
|
74
|
+
const t = ddAdd(ddMul(twoSum(a, -1), ddLog(xd)), ddMul(twoSum(b, -1), ddLog(xcd)));
|
|
75
|
+
return t[0] + (t[1] - lbeta(a, b));
|
|
76
|
+
}
|
|
77
|
+
/** Log density (0 < a, b < Inf; also at x = 0 or 1, which a quantile search in log x reaches by underflow, as dbeta) */
|
|
63
78
|
export function dbetaLog(x, _xc, a, b) {
|
|
79
|
+
if (!(x > 0 && x < 1))
|
|
80
|
+
return dbeta1(x, a, b, true);
|
|
64
81
|
return dbetaCore(x, a, b, true);
|
|
65
82
|
}
|
|
66
83
|
export function dbeta1(x, a, b, log) {
|
|
@@ -143,6 +160,41 @@ export function betaQuantileGuess(a, b, lower, logTarget) {
|
|
|
143
160
|
const x = a / (a + b * Math.exp(2 * w));
|
|
144
161
|
return x > 0 && x < 1 ? x : undefined;
|
|
145
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* The quantile where the relative spread of Beta(a, b) about its mean m = a/(a + b) (the coefficient of variation
|
|
165
|
+
* sqrt(b / (a (a + b + 1)))) is below 1e-15: the distribution function then rises from 0 to 1 within a few dozen ulps
|
|
166
|
+
* of m, and Newton's method on its log fails where the rise is within an ulp (qbeta(1.47e-15, 1.69e160, 1.62e175,
|
|
167
|
+
* { lowerTail: false }) returned 0, qbeta(exp(-226.4), 2.7e43, 8.3e95, { logP: true }) 2.7e-20 for m = 3.3e-53,
|
|
168
|
+
* qbeta(0.3, 1.3e32, 1.3e32) 0.49999998; measured to work down to a spread of 2e-16). Bisects the doubles in
|
|
169
|
+
* m (1 ± 1e-13) (100 times the spread) for the smallest x with I_x(a, b) >= target (lower) or 1 - I_x(a, b) <= target;
|
|
170
|
+
* undefined when the spread is larger or the target is not bracketed there
|
|
171
|
+
*/
|
|
172
|
+
function stepQuantile(a, b, lower, logTarget) {
|
|
173
|
+
const s = Math.min(a, b);
|
|
174
|
+
const l = Math.max(a, b);
|
|
175
|
+
// log of the coefficient of variation (a + b + 1 as l (1 + s/l) to the rounding, without overflow)
|
|
176
|
+
const lcv = 0.5 * (Math.log(b) - Math.log(a) - Math.log(l) - Math.log1p(s / l));
|
|
177
|
+
if (!(lcv < Math.log(1e-15)))
|
|
178
|
+
return undefined;
|
|
179
|
+
const ok = (x) => {
|
|
180
|
+
const v = betaInc(a, b, x, 1 - x, lower, true);
|
|
181
|
+
return lower ? v >= logTarget : v <= logTarget;
|
|
182
|
+
};
|
|
183
|
+
const m = 1 / (1 + b / a);
|
|
184
|
+
let lo = m * (1 - 1e-13);
|
|
185
|
+
let hi = m * (1 + 1e-13);
|
|
186
|
+
if (ok(lo) || !ok(hi))
|
|
187
|
+
return undefined;
|
|
188
|
+
for (;;) {
|
|
189
|
+
const mid = lo + (hi - lo) / 2;
|
|
190
|
+
if (mid === lo || mid === hi)
|
|
191
|
+
return hi;
|
|
192
|
+
if (ok(mid))
|
|
193
|
+
hi = mid;
|
|
194
|
+
else
|
|
195
|
+
lo = mid;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
146
198
|
/**
|
|
147
199
|
* Solve for the quantile in frame (a, b) when the answer lies in (0, 1/2].
|
|
148
200
|
* I_x(a, b) = target if lower, otherwise 1 - I_x(a, b) = target.
|
|
@@ -152,6 +204,9 @@ function solveLeftHalf(a, b, lower, logTarget, linearTarget) {
|
|
|
152
204
|
const atMin = betaInc(a, b, Number.MIN_VALUE, 1, lower, true);
|
|
153
205
|
if (lower ? atMin >= logTarget : atMin <= logTarget)
|
|
154
206
|
return 0;
|
|
207
|
+
const step = stepQuantile(a, b, lower, logTarget);
|
|
208
|
+
if (step !== undefined)
|
|
209
|
+
return step;
|
|
155
210
|
// Starting value: near 0, the tail approximation I_x(a, b) ≈ x^a / (a B(a, b)); otherwise the A&S 26.5.22 approximation
|
|
156
211
|
let x0 = 0.25;
|
|
157
212
|
let tail = Infinity;
|
|
@@ -165,6 +220,14 @@ function solveLeftHalf(a, b, lower, logTarget, linearTarget) {
|
|
|
165
220
|
if (g !== undefined && g < 0.5)
|
|
166
221
|
x0 = g;
|
|
167
222
|
}
|
|
223
|
+
if (b > 1e10 && b > 1e10 * a) {
|
|
224
|
+
// b X tends to Gamma(a): start from the gamma quantile. From 0.25 the log probability (about b log(3/4)) and the
|
|
225
|
+
// log density each round to 1e-16 of their size, and their difference, the Newton slope, was noise for b = 4e204
|
|
226
|
+
// (qbeta(9.3e-85, 1, 4e204, { lowerTail: false }) returned 0)
|
|
227
|
+
const g = qgammaStd(logTarget, a, lower, true) / b;
|
|
228
|
+
if (g > 0 && g < 0.5)
|
|
229
|
+
x0 = g;
|
|
230
|
+
}
|
|
168
231
|
return invertContinuous({
|
|
169
232
|
logTarget,
|
|
170
233
|
...(linearTarget !== undefined && { linearTarget }),
|
|
@@ -5,7 +5,9 @@
|
|
|
5
5
|
// Argument handling (rate = 0, Inf) is matched to R's output.
|
|
6
6
|
import { vectorize } from "../internal/vectorize.js";
|
|
7
7
|
import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
|
|
8
|
-
import { expNeg, log1mExp, logOneMinusExpNeg, mulDD } from "../internal/ddexp.js";
|
|
8
|
+
import { ddExp, expNeg, log1mExp, logOneMinusExpNeg, mulDD } from "../internal/ddexp.js";
|
|
9
|
+
import { ddLog, ddSub } from "../special/dd.js";
|
|
10
|
+
const MIN_NORMAL = 2 ** -1022;
|
|
9
11
|
export function dexp1(x, rate, log) {
|
|
10
12
|
if (Number.isNaN(x) || Number.isNaN(rate))
|
|
11
13
|
return NaN;
|
|
@@ -18,7 +20,14 @@ export function dexp1(x, rate, log) {
|
|
|
18
20
|
return NaN;
|
|
19
21
|
if (log)
|
|
20
22
|
return Math.log(rate) - t[0] - t[1];
|
|
21
|
-
|
|
23
|
+
const e = expNeg(t);
|
|
24
|
+
// exp(-rate x) subnormal while a large rate brings the density back: from the log in double-double (it had lost
|
|
25
|
+
// digits: dexp(2.5e-294, 3e296) was 8e-8 off)
|
|
26
|
+
if (e < MIN_NORMAL && rate > 1 && t[0] < 1500) {
|
|
27
|
+
const l = ddSub(ddLog([rate, 0]), t);
|
|
28
|
+
return l[0] < -746 ? 0 : ddExp(l)[0];
|
|
29
|
+
}
|
|
30
|
+
return rate * e;
|
|
22
31
|
}
|
|
23
32
|
/** Log or linear value of P[X > x], according to the tail direction */
|
|
24
33
|
function expTail(t, lowerTail, logP) {
|
package/dist/distributions/f.js
CHANGED
|
@@ -9,28 +9,77 @@ import { vectorize } from "../internal/vectorize.js";
|
|
|
9
9
|
import { d0, dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
|
|
10
10
|
import { invertContinuous } from "../internal/invert.js";
|
|
11
11
|
import { lbeta } from "../special/beta.js";
|
|
12
|
-
import {
|
|
12
|
+
import { SMALL_SHAPE, smallShapeG } from "../special/incbetPrefactor.js";
|
|
13
|
+
import { betaInc, betaIncBoth, betaIncBothDD, betaIncDD, betaIncTinyX } from "../special/incbet.js";
|
|
13
14
|
import { dbinomRawDD } from "../special/loader.js";
|
|
14
|
-
import { ddAdd, ddDiv, twoProd } from "../special/dd.js";
|
|
15
|
+
import { ddAdd, ddDiv, ddLog, ddMul, ddNeg, ddSub, twoProd, twoSum } from "../special/dd.js";
|
|
15
16
|
import { dgamma1, pgamma1, qgamma1 } from "./gamma.js";
|
|
16
17
|
import { dnf1, pnf1, qnf1 } from "./nbeta.js";
|
|
17
18
|
import { betaQuantileGuess } from "./beta.js";
|
|
19
|
+
const LOG_DBL_MIN = Math.log(2.2250738585072014e-308);
|
|
20
|
+
/**
|
|
21
|
+
* Log density in double-double from log p and log q (p = m x/(n + m x), q = 1 - p = n/(n + m x)), with a = m/2, b = n/2:
|
|
22
|
+
* f(x) = (m/n) p^(a-1) q^(b+1) / B(a, b) (the beta density of p times dp/dx = (m/n) q^2)
|
|
23
|
+
* log(1/B(a, b)) for a small shape from 1/B(a, b) = ab/(a + b) Γ(1+a+b)/(Γ(1+a) Γ(1+b)) (incbetPrefactor.ts)
|
|
24
|
+
*/
|
|
25
|
+
function fLogDensity(m, n, lp, lq) {
|
|
26
|
+
const a = m / 2;
|
|
27
|
+
const b = n / 2;
|
|
28
|
+
const s = Math.min(a, b);
|
|
29
|
+
const lib = s < SMALL_SHAPE ? ddAdd([Math.log(s) - Math.log1p(s / Math.max(a, b)), 0], smallShapeG(a, b)) : [-lbeta(a, b), 0];
|
|
30
|
+
// (a - 1 and b + 1 exactly, in double-double: their rounding times log p of -700 was 3e-14 of the density)
|
|
31
|
+
return ddAdd(ddAdd(ddAdd(ddSub(ddLog([m, 0]), ddLog([n, 0])), ddMul(lp, twoSum(a, -1))), ddMul(lq, twoSum(b, 1))), lib);
|
|
32
|
+
}
|
|
33
|
+
function fromLog(e, log) {
|
|
34
|
+
return log ? e[0] + e[1] : Math.exp(e[0]) * (1 + e[1]);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* p = m x/(n + m x) and q = n/(n + m x) in double-double, or undefined where m x is huge (from 1e290; the callers then
|
|
38
|
+
* form q ≈ n/(m x) directly). Rounding in p and q would be amplified m/2 and n/2 times respectively (5e-13 relative at
|
|
39
|
+
* df1 = 1e6). Where m x is below 1e-290 the double-double product loses its low part or underflows (pf(1.29e-232,
|
|
40
|
+
* 1.78e-123, 2.18e-48) was 0 although pf at 2.6e-269 was 1), so m x and n are first scaled by 2^600 (exactly; the
|
|
41
|
+
* smaller of m and x is below 1e-145 there, and n below 1e127, so that n 2^600 stays finite; for a larger n, p is below
|
|
42
|
+
* DBL_MIN and the callers work from its log)
|
|
43
|
+
*/
|
|
44
|
+
function fRatios(x, m, n) {
|
|
45
|
+
let mx = twoProd(m, x);
|
|
46
|
+
if (!(Number.isFinite(mx[0]) && Number.isFinite(mx[1]) && Math.abs(mx[0]) < 1e290))
|
|
47
|
+
return undefined;
|
|
48
|
+
let nn = n;
|
|
49
|
+
if (x > 0 && mx[0] < 1e-290 && n < 1e127) {
|
|
50
|
+
const S = 2 ** 600;
|
|
51
|
+
mx = m < x ? twoProd(m * S, x) : twoProd(m, x * S);
|
|
52
|
+
nn = n * S;
|
|
53
|
+
}
|
|
54
|
+
const d = ddAdd(mx, [nn, 0]);
|
|
55
|
+
return [ddDiv(mx, d), ddDiv([nn, 0], d)];
|
|
56
|
+
}
|
|
18
57
|
function fDensity(x, m, n, log) {
|
|
19
|
-
// p
|
|
20
|
-
//
|
|
21
|
-
|
|
58
|
+
// p or q below DBL_MIN (m x/n beyond e^±708): the ratios themselves would be subnormal or underflow (the density was
|
|
59
|
+
// NaN, as R's is: df(1.33e-322, 1.04, 206159)). The tiny one is r/(1 + r) or 1/(1 + r), r = m x/n, whose log is
|
|
60
|
+
// -|log r| to within DBL_MIN; the other is 1 to within DBL_MIN
|
|
61
|
+
if (x > 0 && x < Infinity && Math.abs(Math.log(m) + Math.log(x) - Math.log(n)) > 700) {
|
|
62
|
+
const lr = ddAdd(ddSub(ddLog([m, 0]), ddLog([n, 0])), ddLog([x, 0]));
|
|
63
|
+
if (lr[0] < LOG_DBL_MIN)
|
|
64
|
+
return fromLog(fLogDensity(m, n, lr, [-Math.exp(lr[0]), 0]), log);
|
|
65
|
+
if (-lr[0] < LOG_DBL_MIN)
|
|
66
|
+
return fromLog(fLogDensity(m, n, [-Math.exp(-lr[0]), 0], ddNeg(lr)), log);
|
|
67
|
+
}
|
|
68
|
+
const r = fRatios(x, m, n);
|
|
22
69
|
let pd;
|
|
23
70
|
let qd;
|
|
24
|
-
if (
|
|
25
|
-
|
|
26
|
-
pd = ddDiv(mx, d);
|
|
27
|
-
qd = ddDiv([n, 0], d);
|
|
71
|
+
if (r !== undefined) {
|
|
72
|
+
[pd, qd] = r;
|
|
28
73
|
}
|
|
29
74
|
else {
|
|
30
75
|
// m x is huge (the double-double product overflows): p ≈ 1, q ≈ n/(m x) in double precision
|
|
31
76
|
qd = [n / m / x, 0];
|
|
32
77
|
pd = [1, -qd[0]];
|
|
33
78
|
}
|
|
79
|
+
// A small df: Loader's form loses about ε |log(df/2)| / 2 in its exponent (incbetPrefactor.ts), and the factor m^2 n
|
|
80
|
+
// below underflowed (df(6.6e-112, 3.2e-173, 1868) was -Infinity on the log scale, NaN at x = 4.6e-157)
|
|
81
|
+
if (Math.min(m, n) / 2 < SMALL_SHAPE)
|
|
82
|
+
return fromLog(fLogDensity(m, n, ddLog(pd), ddLog(qd)), log);
|
|
34
83
|
const p = pd[0];
|
|
35
84
|
const q = qd[0];
|
|
36
85
|
if (m >= 2) {
|
|
@@ -62,6 +111,7 @@ export function dfDensity1(x, m, n, log) {
|
|
|
62
111
|
return dgamma1(x, m / 2, 2 / m, log); // χ²_m / m
|
|
63
112
|
if (!Number.isFinite(m)) {
|
|
64
113
|
// n / χ²_n: 1/x follows a gamma distribution with shape n/2, scale 2/n
|
|
114
|
+
// At tiny x this is 0 / 0 = NaN (x^2 underflows), as R gives (df(1e-300, Inf, 5) is NaN); the log is finite
|
|
65
115
|
const dens = dgamma1(1 / x, n / 2, 2 / n, log);
|
|
66
116
|
return log ? dens - 2 * Math.log(x) : dens / (x * x);
|
|
67
117
|
}
|
|
@@ -69,14 +119,34 @@ export function dfDensity1(x, m, n, log) {
|
|
|
69
119
|
return m < 2 ? NaN : d0(log); // R gives NaN at x = Inf when df1 < 2
|
|
70
120
|
return fDensity(x, m, n, log);
|
|
71
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* [log, linear] of P[F <= x] (lower) / P[F > x] where m x/(n + m x) or n/(n + m x) is below DBL_MIN, from the log of
|
|
124
|
+
* that ratio (betaIncTinyX); undefined elsewhere. With r = m x/n the ratios are r/(1 + r) and 1/(1 + r), so the log of
|
|
125
|
+
* the smaller one is -|log r| to within DBL_MIN. Forming the ratio itself would round it in the subnormal range
|
|
126
|
+
* (pf(5.43e-319, 1.04, 206159) was off by 4.5e-14) or underflow it to 0 (pf(1e300, 0.169, 1.18e-86, { lowerTail: false })
|
|
127
|
+
* was 0, about 1 expected)
|
|
128
|
+
*/
|
|
129
|
+
function pfTiny(x, m, n, lower, wantLog) {
|
|
130
|
+
// (a cheap filter first: the double-double logarithms are only needed out there)
|
|
131
|
+
// (x = 0 and Infinity, which the quantile search reaches, are left to the ratios below)
|
|
132
|
+
if (!(x > 0 && x < Infinity) || Math.abs(Math.log(m) + Math.log(x) - Math.log(n)) < 700)
|
|
133
|
+
return undefined;
|
|
134
|
+
const lr = ddSub(ddAdd(ddLog([m, 0]), ddLog([x, 0])), ddLog([n, 0]));
|
|
135
|
+
if (lr[0] < LOG_DBL_MIN)
|
|
136
|
+
return betaIncTinyX(m / 2, n / 2, Math.exp(lr[0]), lr, lower, wantLog);
|
|
137
|
+
if (-lr[0] < LOG_DBL_MIN)
|
|
138
|
+
return betaIncTinyX(n / 2, m / 2, Math.exp(-lr[0]), ddNeg(lr), !lower, wantLog);
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
72
141
|
/** P[F <= x] (lower) / P[F > x] (!lower). x finite and positive, m, n finite */
|
|
73
142
|
function pfRaw(x, m, n, lower, log) {
|
|
143
|
+
const t = pfTiny(x, m, n, lower, log);
|
|
144
|
+
if (t !== undefined)
|
|
145
|
+
return log ? t[0] : t[1];
|
|
74
146
|
// Form m x/(n + m x) and n/(n + m x) in double-double (rounding would be amplified m/2 and n/2 times)
|
|
75
|
-
const
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
return betaIncDD(m / 2, n / 2, ddDiv(mx, d), ddDiv([n, 0], d), lower, log);
|
|
79
|
-
}
|
|
147
|
+
const r = fRatios(x, m, n);
|
|
148
|
+
if (r !== undefined)
|
|
149
|
+
return betaIncDD(m / 2, n / 2, r[0], r[1], lower, log);
|
|
80
150
|
// m x is huge: form 1 - z = n/(n + m x) ≈ (n/m)/x directly
|
|
81
151
|
const zc = n / m / x;
|
|
82
152
|
return betaInc(m / 2, n / 2, 1 - zc, zc, lower, log);
|
|
@@ -91,11 +161,12 @@ function fQuantileGuess(m, n, lower, logTarget) {
|
|
|
91
161
|
}
|
|
92
162
|
/** [log, linear] of pfRaw (each value identical to pfRaw) */
|
|
93
163
|
function pfRawBoth(x, m, n, lower) {
|
|
94
|
-
const
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
164
|
+
const t = pfTiny(x, m, n, lower, true);
|
|
165
|
+
if (t !== undefined)
|
|
166
|
+
return t;
|
|
167
|
+
const r = fRatios(x, m, n);
|
|
168
|
+
if (r !== undefined)
|
|
169
|
+
return betaIncBothDD(m / 2, n / 2, r[0], r[1], lower);
|
|
99
170
|
const zc = n / m / x;
|
|
100
171
|
return betaIncBoth(m / 2, n / 2, 1 - zc, zc, lower);
|
|
101
172
|
}
|
|
@@ -138,9 +209,21 @@ export function qf1(p, m, n, lowerTail, logP) {
|
|
|
138
209
|
// Near 0, P[F <= x] ≈ (m x / n)^(m/2) / ((m/2) B(m/2, n/2)). The answer is 0 if it underflows
|
|
139
210
|
if (lower && (logTarget + Math.log(m / 2) + lbeta(m / 2, n / 2)) / (m / 2) + Math.log(n / m) < -746)
|
|
140
211
|
return 0;
|
|
141
|
-
// Near infinity, P[F > x] ≈ (n / (m x))^(n/2) / ((n/2) B(m/2, n/2)). Inf if it overflows
|
|
142
|
-
|
|
212
|
+
// Near infinity, P[F > x] ≈ (n / (m x))^(n/2) / ((n/2) B(m/2, n/2)). Inf if it overflows, as confirmed by the upper
|
|
213
|
+
// tail at the largest double (the leading term alone sent qf(5.95e-155, 2875.5, 1, { lowerTail: false }) to Infinity,
|
|
214
|
+
// where pf(1.797e308, ...) is 5.9503e-155, below p)
|
|
215
|
+
if (!lower &&
|
|
216
|
+
-(logTarget + Math.log(n / 2) + lbeta(m / 2, n / 2)) / (n / 2) + Math.log(n / m) > 709.78 &&
|
|
217
|
+
pfRaw(Number.MAX_VALUE, m, n, false, true) > logTarget) {
|
|
218
|
+
return Infinity;
|
|
219
|
+
}
|
|
220
|
+
// The other way round, a tiny df2 leaves the lower tail below the target up to the largest double (nearly all the
|
|
221
|
+
// mass lies beyond it: qf(8.8e-131, 0.754, 4.6e-152) returned 1.8e308, where pf is 2.4e-149), and a tiny df1 the
|
|
222
|
+
// upper tail below the target from the smallest positive number on
|
|
223
|
+
if (lower && n < 1 && pfRaw(Number.MAX_VALUE, m, n, true, true) < logTarget)
|
|
143
224
|
return Infinity;
|
|
225
|
+
if (!lower && m < 1 && pfRaw(Number.MIN_VALUE, m, n, false, true) < logTarget)
|
|
226
|
+
return 0;
|
|
144
227
|
return invertContinuous({
|
|
145
228
|
logTarget,
|
|
146
229
|
...(linearTarget !== undefined && { linearTarget }),
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type Vectorizable, type VectorResult } from "../internal/vectorize.js";
|
|
2
2
|
import { type DensityOptions, type TailOptions } from "../internal/dpq.js";
|
|
3
|
+
import { type DD } from "../special/dd.js";
|
|
3
4
|
/**
|
|
4
5
|
* Parameters of the gamma distribution. Give either `rate` or `scale`; if both are given,
|
|
5
6
|
* `scale` must equal `1 / rate`.
|
|
@@ -18,8 +19,18 @@ export declare function gammaScale(params: GammaParams): number;
|
|
|
18
19
|
export declare function dgammaStdLog(x: number, shape: number): number;
|
|
19
20
|
export declare function dgamma1(x: number, shape: number, scale: number, log: boolean): number;
|
|
20
21
|
export declare function pgamma1(q: number, shape: number, scale: number, lowerTail: boolean, logP: boolean): number;
|
|
21
|
-
/**
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* log of the standardized gamma quantile when it is below the smallest normal double (else undefined): there
|
|
24
|
+
* P(shape, x) = x^shape / Gamma(shape + 1) to double precision, so log x = (log P + lgamma(shape + 1)) / shape.
|
|
25
|
+
* lower, logTarget and linearTarget as from smallerTail. log P from the linear target in double-double where there is
|
|
26
|
+
* one (log P rounded would lose eps |log P| / shape relative in x)
|
|
27
|
+
*/
|
|
28
|
+
export declare function logTinyGammaQuantile(logTarget: number, lower: boolean, shape: number, linearTarget: number | undefined): DD | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Quantile of the standardized gamma distribution times scale (default 1). 0 < p < 1 (range checks are the caller's
|
|
31
|
+
* job). Where the standardized quantile is below the smallest normal double the scaling is done in logs
|
|
32
|
+
*/
|
|
33
|
+
export declare function qgammaStd(p: number, shape: number, lowerTail: boolean, logP: boolean, scale?: number): number;
|
|
23
34
|
export declare function qgamma1(p: number, shape: number, scale: number, lowerTail: boolean, logP: boolean): number;
|
|
24
35
|
/**
|
|
25
36
|
* Density of the gamma distribution. Equivalent to R's `dgamma(x, shape, rate = 1, scale = 1/rate, log = FALSE)`.
|