You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

8 lines
69 KiB

(function(){"use strict";function q(l,t){return Math.sqrt(k(l,t))}function k(l,t){if(l.length!=t.length)return;const e=l.length;let r=0;for(let s=0;s<e;++s){const n=l[s]-t[s];r+=n*n}return r}function ur(l,t){if(l.length!==t.length)return;let e=l.length,r=0,s=0,n=0;for(let i=0;i<e;++i)r+=l[i]*t[i],s+=l[i]*l[i],n+=t[i]*t[i];return Math.acos(r/(Math.sqrt(s)*Math.sqrt(n)))}function fr(l,t){if(l.length!=t.length)return;const e=l.length;let r=0;for(let s=0;s<e;++s)r+=Math.abs(l[s]-t[s]);return r}function dr(l,t){if(l.length!=t.length)return;const e=l.length;let r=[];for(let s=0;s<e;++s)r.push(Math.abs(l[s]-t[s]));return Math.max(...r)}function pr(l,t){if(l.length!==t.length)return;const e=l.length;let r=0;for(let s=0;s<e;++s)r+=Math.abs(l[s]-t[s])/(Math.abs(l[s])+Math.abs(t[s]));return r}function mr(l,t){if(l.length!=t.length)return;const e=l.length;let r=0,s=0;for(let n=0;n<e;++n){const i=l[n]!=0,a=t[n]!=0;r+=i||a,s+=i&&a}return(r-s)/r}function gr(l,t){if(l.length!=t.length)return;const e=l.length;let r=0;for(let s=0;s<e;++s)r+=l[s]!=t[s];return r/e}function yr(l,t){if(l.length!=t.length)return;const e=l.length;let r=0;for(let s=0;s<e;++s)r+=l[s]!=0!=(t[s]!=0);return 2*r/(e+r)}function wr(l,t){if(l.length!=t.length)return;const e=l.length;let r=0,s=0,n=0;for(let i=0;i<e;++i){const a=l[i]!=0,o=t[i]!=0;r+=a&&o,s+=a&&!o,n+=!a&&a}return s==0||n==0?0:2*s*n/(r*(e-r-s-n)+s*n)}function Q(l,t,e=q){const r=l.shape[0];let s=e=="precomputed"?l:F(l,e),n=new Array(r);for(let i=0;i<r;++i)n[i]=Array.from(s.row(i)).map((a,o)=>({i,j:o,distance:a})).sort((a,o)=>a.distance-o.distance).slice(1,t+1);return n}function F(l,t=q){let e=l.shape[0];const r=new w(e,e);for(let s=0;s<e;++s){const n=l.row(s);for(let i=s+1;i<e;++i){const a=t(n,l.row(i));r.set_entry(s,i,a),r.set_entry(i,s,a)}}return r}function z(l,t,e=null){if(e||(e=Math.max(Math.round(t-l)+1,1)),e<2)return e===1?[l]:[];let r=new Array(e);for(let s=e-=1;s>=0;--s)r[s]=(s*t+(e-s)*l)/e;return r}function I(l,t=q){let e=null;if(l instanceof w){let[s,n]=l.shape;if(s===1)e=l.row(0);else{if(n!==1)throw new Error("Matrix must be 1d!");e=l.col(0)}}else e=l;const r=e.length;return t(e,new Float64Array(r))}function vr(l,t=q){const e=I(l,t);return l.map(r=>r/e)}function br(l){let t,e,r=l.length,s=0,n=0;for(let i=0;i<r;++i)t=l[i]-n,e=s+t,n=e-s-t,s=e;return s}function R(l){const t=l.length;let e=0,r=0;for(let s=0;s<t;++s){const n=l[s],i=e+n;Math.abs(e)>=Math.abs(n)?r+=e-i+n:r+=n-i+e,e=i}return e+r}function se(l){const[t,e]=l.shape,r=new w(t,e,"identity"),s=new w(e,e,0);for(let n=0;n<e;++n){let i=l.col(n);for(let o=0;o<n;++o){const h=r.col(o),_=R(h.map((c,u)=>c*i[u]));for(let c=0;c<t;++c)i[c]-=_*h[c];s.set_entry(o,n,_)}const a=I(i,q);for(let o=0;o<t;++o)r.set_entry(o,n,i[o]/a);s.set_entry(n,n,a)}return{R:s,Q:r}}function Ar(l){const[t,e]=l.shape,r=new w(t,t,"I"),s=l.clone();for(let n=0;n<e;++n){const i=w.from(s.col(n).slice(n)),a=I(i),o=i.entry(0,0),h=-Math.sign(o),_=o-h*a,c=i.divide(_).set_entry(0,0,1),u=-h*_/a,f=c.outer(c),d=s.get_block(n,0),p=d.sub(f.dot(d).mult(u)),g=r.get_block(0,n),y=g.sub(g.dot(f).mult(u));s.set_block(n,0,p),r.set_block(0,n,y)}return{R:s,Q:r}}function N(l,t=2,{seed:e=1212,max_iterations:r=100,qr:s=se,tol:n=1e-8}={}){const i=e instanceof O?e:new O(e);l instanceof w||(l=w.from(l));const a=l.shape[0];let{Q:o,R:h}=s(new w(a,t,()=>2*(i.random-.5)));for(;r--;){const _=o,c=s(l.dot(o));if(o=c.Q,h=c.R,k(o.values,_.values)<n)break}return{eigenvalues:h.diag,eigenvectors:o.transpose().to2dArray}}function Mr(l,t){const e=l.length;if(e!=t.length)throw new Error("Array a and b must have the same length!");let r=0;for(let s=0;s<e;++s)r+=l*t;return r}class w{constructor(t=null,e=null,r=null){if(this._rows=t,this._cols=e,this._data=null,t&&e){if(!r)return this._data=new Float64Array(t*e),this;if(typeof r=="function"){this._data=new Float64Array(t*e);for(let s=0;s<t;++s)for(let n=0;n<e;++n)this._data[s*e+n]=r(s,n);return this}if(typeof r=="string"){if(r==="zeros")return new w(t,e,0);if(r==="identity"||r==="I"){this._data=new Float64Array(t*e);for(let s=0;s<t;++s)this._data[s*e+s]=1;return this}if(r==="center"&&t==e){this._data=new Float64Array(t*e),r=(s,n)=>(s===n?1:0)-1/t;for(let s=0;s<t;++s)for(let n=0;n<e;++n)this._data[s*e+n]=r(s,n);return this}}if(typeof r=="number"){this._data=new Float64Array(t*e);for(let s=0;s<t;++s)for(let n=0;n<e;++n)this._data[s*e+n]=r;return this}}return this}static from(t,e="row"){if(t instanceof w)return t.clone();if(w.isArray(t)){let r=t.length;if(r===0)throw new Error("Array is empty");if(w.isArray(t[0])){let s=t[0].length;for(let n=0;n<r;++n)if(t[n].length!==s)throw new Error("various array lengths");return new w(r,s,(n,i)=>t[n][i])}if(e==="row")return new w(1,r,(s,n)=>t[n]);if(e==="col")return new w(r,1,s=>t[s]);if(e==="diag")return new w(r,r,(s,n)=>s==n?t[s]:0);throw new Error("1d array has NaN entries")}if(typeof t=="number")return new w(1,1,t);throw new Error("error")}row(t){const e=this.values,r=this._cols;return e.subarray(t*r,(t+1)*r)}*iterate_rows(){const t=this._cols,e=this._rows,r=this.values;for(let s=0;s<e;++s)yield r.subarray(s*t,(s+1)*t)}*[Symbol.iterator](){for(const t of this.iterate_rows())yield t}set_row(t,e){const r=this._cols;if(w.isArray(e)&&e.length===r){const s=t*r;for(let n=0;n<r;++n)this.values[s+n]=e[n]}else{if(!(e instanceof w&&e.shape[1]===r&&e.shape[0]===1))throw new Error("Values not valid! Needs to be either an Array, a Float64Array, or a fitting Matrix!");{const s=t*r;for(let n=0;n<r;++n)this.values[s+n]=e._data[n]}}return this}swap_rows(t,e){const r=this._cols,s=this.values;for(let n=t*r,i=e*r,a=0;a<r;++a,++n,++i){const o=s[n];s[n]=s[i],s[i]=o}}col(t){const e=new Float64Array(this._rows);for(let r=0;r<this._rows;++r)e[r]=this.values[r*this._cols+t];return e}entry(t,e){return this.values[t*this._cols+e]}set_entry(t,e,r){return this.values[t*this._cols+e]=r,this}add_entry(t,e,r){return this.values[t*this._cols+e]+=r,this}sub_entry(t,e,r){return this.values[t*this._cols+e]-=r,this}transpose(){return new w(this._cols,this._rows,(t,e)=>this.entry(e,t))}get T(){return this.transpose()}inverse(){const t=this._rows,e=this._cols,r=this.clone(),s=new w(t,e,"I");for(let n=0;n<e;++n){let i=n,a=Math.abs(r.entry(n,n));for(let _=n+1;_<t;++_){const c=Math.abs(r.entry(_,n));a<c&&(i=_,a=c)}if(a===0)throw new Error("Cannot compute inverse of Matrix, determinant is zero");i!==n&&(r.swap_rows(n,i),s.swap_rows(n,i));const o=r.row(n),h=s.row(n);for(let _=0;_<t;++_)if(_!==n){const c=r.row(_),u=s.row(_);if(c[n]!==0){const f=c[n]/o[n];for(let d=n;d<e;++d)c[d]-=f*o[d];for(let d=0;d<e;++d)u[d]-=f*h[d]}}else{const c=o[n];for(let u=n;u<e;++u)o[u]/=c;for(let u=0;u<e;++u)h[u]/=c}}return s}dot(t){if(t instanceof w){let e=this;const[r,s]=e.shape,[n,i]=t.shape;if(s!==n)throw new Error(`A.dot(B): A is a ${e.shape.join(" ⨯ ")}-Matrix, B is a ${t.shape.join(" ⨯ ")}-Matrix:
A has ${s} cols and B ${n} rows.
Must be equal!`);return new w(r,i,(a,o)=>{const h=e.row(a),_=t.values;let c=0;for(let u=0,f=o;u<s;++u,f+=i)c+=h[u]*_[f];return c})}if(w.isArray(t)){let e=this._rows;if(t.length!==e)throw new Error(`A.dot(B): A has ${e} cols and B has ${t.length} rows. Must be equal!`);let r=new Array(e);for(let s=0;s<e;++s)r[s]=R(this.row(s).map(n=>n*t[s]));return r}throw new Error("B must be Matrix or Array")}transDot(t){if(t instanceof w){let e=this;const[r,s]=e.shape,[n,i]=t.shape;if(r!==n)throw new Error(`A.dot(B): A is a ${[s,r].join(" ⨯ ")}-Matrix, B is a ${t.shape.join(" ⨯ ")}-Matrix:
A has ${r} cols and B ${n} rows, which must be equal!`);return new w(s,i,(a,o)=>{const h=e.values,_=t.values;let c=0;for(let u=0,f=a,d=o;u<r;++u,f+=s,d+=i)c+=h[f]*_[d];return c})}if(w.isArray(t)){let e=this._cols;if(t.length!==e)throw new Error(`A.dot(B): A has ${e} cols and B has ${t.length} rows. Must be equal!`);let r=new Array(e);for(let s=0;s<e;++s)r[s]=R(this.col(s).map(n=>n*t[s]));return r}throw new Error("B must be Matrix or Array")}dotTrans(t){if(t instanceof w){let e=this;const[r,s]=e.shape,[n,i]=t.shape;if(s!==i)throw new Error(`A.dot(B): A is a ${e.shape.join(" ⨯ ")}-Matrix, B is a ${[i,n].join(" ⨯ ")}-Matrix:
A has ${s} cols and B ${i} rows, which must be equal!`);return new w(r,n,(a,o)=>{const h=e.row(a),_=t.row(o);let c=0;for(let u=0;u<s;++u)c+=h[u]*_[u];return c})}if(w.isArray(t)){let e=this._rows;if(t.length!==e)throw new Error(`A.dot(B): A has ${e} cols and B has ${t.length} rows. Must be equal!`);let r=new Array(e);for(let s=0;s<e;++s)r[s]=R(this.row(s).map(n=>n*t[s]));return r}throw new Error("B must be Matrix or Array")}outer(t){let e=this,r=e._data.length;if(r!=t._data.length)return;let s=new w;return s.shape=[r,r,(n,i)=>n<=i?e._data[n]*t._data[i]:s.entry(i,n)],s}concat(t,e="horizontal"){const r=this,[s,n]=r.shape,[i,a]=t.shape;if(e=="horizontal"){if(s!=i)throw new Error(`A.concat(B, "horizontal"): A and B need same number of rows, A has ${s} rows, B has ${i} rows.`);const o=new w(s,n+a,"zeros");return o.set_block(0,0,r),o.set_block(0,n,t),o}if(e=="vertical"){if(n!=a)throw new Error(`A.concat(B, "vertical"): A and B need same number of columns, A has ${n} columns, B has ${a} columns.`);const o=new w(s+i,n,"zeros");return o.set_block(0,0,r),o.set_block(s,0,t),o}if(e=="diag"){const o=new w(s+i,n+a,"zeros");return o.set_block(0,0,r),o.set_block(s,n,t),o}throw new Error(`type must be "horizontal" or "vertical", but type is ${e}!`)}set_block(t,e,r){const s=Math.min(this._rows-t,r.shape[0]),n=Math.min(this._cols-e,r.shape[1]);for(let i=0;i<s;++i)for(let a=0;a<n;++a)this.set_entry(i+t,a+e,r.entry(i,a));return this}get_block(t,e,r=null,s=null){const[n,i]=this.shape;if(s=s??i,(r=r??n)<=t||s<=e)throw new Error(`
end_row must be greater than start_row, and
end_col must be greater than start_col, but
end_row = ${r}, start_row = ${t}, end_col = ${s}, and start_col = ${e}!`);const a=new w(r-t,s-e,"zeros");for(let o=t,h=0;o<r;++o,++h)for(let _=e,c=0;_<s;++_,++c)a.set_entry(h,c,this.entry(o,_));return a}gather(t,e){const r=t.length,s=e.length,n=new w(r,s);for(let i=0;i<r;++i){const a=t[i];for(let o=0;o<r;++o){const h=e[o];n.set_entry(i,o,this.entry(a,h))}}return n}_apply_array(t,e){const r=this.values,[s,n]=this.shape;for(let i=0,a=0;a<s;++a)for(let o=0;o<n;++o,++i)r[i]=t(r[i],e(a,o));return this}_apply_rowwise_array(t,e){return this._apply_array(e,(r,s)=>t[s])}_apply_colwise_array(t,e){const r=this.values,[s,n]=this.shape;for(let i=0,a=0;a<s;++a){const o=t[a];for(let h=0;h<n;++h,++i)r[i]=e(r[i],o)}return this}_apply(t,e){const r=this.values,[s,n]=this.shape;if(t instanceof w){const i=t.values,[a,o]=t.shape;if(a===1){if(n!==o)throw new Error("cols !== value_cols");for(let h=0,_=0;_<s;++_)for(let c=0;c<n;++c,++h)r[h]=e(r[h],i[c])}else if(o===1){if(s!==a)throw new Error("rows !== value_rows");for(let h=0,_=0;_<s;++_){const c=i[_];for(let u=0;u<n;++u,++h)r[h]=e(r[h],c)}}else{if(s!=a||n!=o)throw new Error("error");for(let h=0,_=s*n;h<_;++h)r[h]=e(r[h],i[h])}}else if(w.isArray(t))if(t.length===s)for(let i=0,a=0;a<s;++a){const o=t[a];for(let h=0;h<n;++h,++i)r[i]=e(r[i],o)}else{if(t.length!==n)throw new Error("error");for(let i=0,a=0;a<s;++a)for(let o=0;o<n;++o,++i)r[i]=e(r[i],t[o])}else for(let i=0,a=s*n;i<a;++i)r[i]=e(r[i],t);return this}clone(){let t=new w;return t._rows=this._rows,t._cols=this._cols,t._data=this.values.slice(0),t}mult(t,{inline:e=!1}={}){return(e?this:this.clone())._apply(t,(r,s)=>r*s)}divide(t,{inline:e=!1}={}){return(e?this:this.clone())._apply(t,(r,s)=>r/s)}add(t,{inline:e=!1}={}){return(e?this:this.clone())._apply(t,(r,s)=>r+s)}sub(t,{inline:e=!1}={}){return(e?this:this.clone())._apply(t,(r,s)=>r-s)}get shape(){return[this._rows,this._cols]}set shape([t,e,r=()=>0]){this._rows=t,this._cols=e,this._data=new Float64Array(t*e);for(let s=0,n=0;n<t;++n)for(let i=0;i<e;++i,++s)this._data[s]=r(n,i);return this}get to2dArray(){const t=[];for(const e of this.iterate_rows())t.push(e);return t}get asArray(){const t=[];for(const e of this.iterate_rows())t.push(Array.from(e));return t}get diag(){const t=this._rows,e=this._cols,r=Math.min(t,e);let s=new Float64Array(r);for(let n=0;n<r;++n)s[n]=this.entry(n,n);return s}get mean(){return this.sum/(this._rows*this._cols)}get sum(){return R(this.values)}get values(){return this._data}get meanRows(){const t=this.values,e=this._rows,r=this._cols,s=Float64Array.from({length:e});for(let n=0,i=0;i<e;++i){let a=0;for(let o=0;o<r;++o,++n)a+=t[n];s[i]=a/r}return s}get meanCols(){const t=this.values,e=this._rows,r=this._cols,s=Float64Array.from({length:r});for(let n=0;n<r;++n){let i=0;for(let a=n,o=0;o<e;++o,a+=r)i+=t[a];s[n]=i/e}return s}static solve_CG(t,e,r,s=.001){r===null&&(r=new O);const n=t.shape[0],i=e.shape[1];let a=new w(n,0);for(let o=0;o<i;++o){const h=w.from(e.col(o)).T;let _=new w(n,1,()=>r.random),c=h.sub(t.dot(_)),u=c.clone();do{const f=t.dot(u),d=c.transDot(c).entry(0,0)/u.transDot(f).entry(0,0);_=_.add(u.mult(d));const p=c.sub(f.mult(d)),g=p.transDot(p).entry(0,0)/c.transDot(c).entry(0,0);u=p.add(u.mult(g)),c=p}while(Math.abs(c.mean)>s);a=a.concat(_,"horizontal")}return a}static solve(t,e){let{L:r,U:s}="L"in t&&"U"in t?t:w.LU(t),n=r.shape[0],i=e.clone();for(let a=0;a<n;++a){for(let o=0;o<a-1;++o)i.sub_entry(0,a,r.entry(a,o)*i.entry(1,o));i.set_entry(0,a,i.entry(0,a)/r.entry(a,a))}for(let a=n-1;a>=0;--a){for(let o=n-1;o>a;--o)i.sub_entry(0,a,s.entry(a,o)*i.entry(0,o));i.set_entry(0,a,i.entry(0,a)/s.entry(a,a))}return i}static LU(t){const e=t.shape[0],r=new w(e,e,"zeros"),s=new w(e,e,"identity");for(let n=0;n<e;++n){for(let i=n;i<e;++i){let a=0;for(let o=0;o<n;++o)a+=r.entry(i,o)*s.entry(o,n);r.set_entry(i,n,t.entry(i,n)-a)}for(let i=n;i<e;++i){if(r.entry(n,n)===0)return;let a=0;for(let o=0;o<n;++o)a+=r.entry(n,o)*s.entry(o,i);s.set_entry(n,i,(t.entry(n,i)-a)/r.entry(n,n))}}return{L:r,U:s}}static det(t){const e=t.shape[0],{L:r,U:s}=w.LU(t),n=r.diag,i=s.diag;let a=n[0]*i[0];for(let o=1;o<e;++o)a*=n[o]*i[o];return a}static SVD(t,e=2){let r=t.transDot(t),s=t.dotTrans(t),{eigenvectors:n,eigenvalues:i}=N(r,e),{eigenvectors:a}=N(s,e);return{U:a,Sigma:i.map(o=>Math.sqrt(o)),V:n}}static isArray(t){return Array.isArray(t)||t instanceof Float64Array||t instanceof Float32Array}}class O{constructor(t){return this._N=624,this._M=397,this._MATRIX_A=2567483615,this._UPPER_MASK=2147483648,this._LOWER_MASK=2147483647,this._mt=new Array(this._N),this._mti=this.N+1,this.seed=t||new Date().getTime(),this}set seed(t){this._seed=t;let e=this._mt;for(e[0]=t>>>0,this._mti=1;this._mti<this._N;this._mti+=1){let r=this._mti,s=e[r-1]^e[r-1]>>>30;e[r]=(1812433253*((4294901760&s)>>>16)<<16)+1812433253*(65535&s)+r,e[r]>>>=0}}get seed(){return this._seed}get random(){return this.random_int*(1/4294967296)}get random_int(){let t,e=new Array(0,this._MATRIX_A);if(this._mti>=this._N){let r,s=this._N-this._M,n=this._M-this._N;for(r=0;r<s;++r)t=this._mt[r]&this._UPPER_MASK|this._mt[r+1]&this._LOWER_MASK,this._mt[r]=this._mt[r+this._M]^t>>>1^e[1&t];for(;r<this._N-1;++r)t=this._mt[r]&this._UPPER_MASK|this._mt[r+1]&this._LOWER_MASK,this._mt[r]=this._mt[r+n]^t>>>1^e[1&t];t=this._mt[this._N-1]&this._UPPER_MASK|this._mt[0]&this._LOWER_MASK,this._mt[this._N-1]=this._mt[this._M-1]^t>>>1^e[1&t],this._mti=0}return t=this._mt[this._mti+=1],t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}gauss_random(){let t,e,r;if(this._val!=null)return t=this._val,this._val=null,t;do t=2*this.random-1,e=2*this.random-1,r=t*t+e*e;while(!r||r>1);const s=Math.sqrt(-2*Math.log(r)/r);return this._val=e*s,t*s}choice(t,e){if(t instanceof w){let r=t.shape[0];if(e>r)throw new Error("n bigger than A!");let s=new Array(e),n=z(0,r-1);for(let i=0,a=n.length;i<e;++i,--a){let o=this.random_int%a;s[i]=n.splice(o,1)[0]}return s.map(i=>t.row(i))}if(Array.isArray(t)||t instanceof Float64Array){let r=t.length;if(e>r)throw new Error("n bigger than A!");let s=new Array(e),n=z(0,r-1);for(let i=0,a=n.length;i<e;++i,--a){let o=this.random_int%a;s[i]=n.splice(o,1)[0]}return s.map(i=>t[i])}}static choice(t,e,r=1212){return new O(r).choice(t,e)}}function ne(l){let t;for(const e of l)e!=null&&(t<e||t===void 0&&e>=e)&&(t=e);return t}function $(l){let t;for(const e of l)e!=null&&(t>e||t===void 0&&e<=e)&&(t=e);return t}class E{constructor(t=null,e=s=>s,r="min"){return t?E.heapify(t,e,r):(this._accessor=e,this._container=[],this._comparator=r=="min"?(s,n)=>s<n:r=="max"?(s,n)=>s>n:r,this)}static heapify(t,e=s=>s,r="min"){const s=new E(null,e,r),n=s._container;for(const i of t)n.push({element:i,value:e(i)});for(let i=Math.floor(t.length/2-1);i>=0;--i)s._heapify_down(i);return s}_swap(t,e){const r=this._container;[r[e],r[t]]=[r[t],r[e]]}_heapify_up(){const t=this._container;let e=t.length-1;for(;e>0;){let r=Math.floor((e-1)/2);if(!this._comparator(t[e].value,t[r].value))break;this._swap(r,e),e=r}}push(t){const e={element:t,value:this._accessor(t)};return this._container.push(e),this._heapify_up(),this}_heapify_down(t=0){const e=this._container,r=this._comparator,s=e.length;let n=2*t+1,i=2*t+2,a=t;if(a>s)throw"index higher than length";n<s&&r(e[n].value,e[a].value)&&(a=n),i<s&&r(e[i].value,e[a].value)&&(a=i),a!==t&&(this._swap(t,a),this._heapify_down(a))}pop(){const t=this._container;if(t.length===0)return null;if(t.length===1)return t.pop();this._swap(0,t.length-1);const e=t.pop();return this._heapify_down(),e}get first(){return this._container.length>0?this._container[0]:null}*iterate(){for(let t=0,e=this._container.length;t<e;++t)yield this._container[t].element}toArray(){return this.data().sort((t,e)=>this._comparator(t,e)?-1:0)}data(){return this._container.map(t=>t.element)}raw_data(){return this._container}get length(){return this._container.length}get empty(){return this.length===0}}class K{constructor(t=null){if(this._list=new Set,t)for(const e of t)this.make_set(e);return this}make_set(t){const e=this._list;return e.has(t)||(e.add(t),t.__disjoint_set={},t.__disjoint_set.parent=t,t.__disjoint_set.children=new Set([t]),t.__disjoint_set.size=1),this}find(t){return this._list.has(t)?t.__disjoint_set.parent!==t?(t.__disjoint_set.children.add(...t),t.__disjoint_set.parent=this.find(t.__disjoint_set.parent),t.__disjoint_set.parent):t:null}union(t,e){let r=this.find(t),s=this.find(e);return r===s||(r.__disjoint_set.size<s.__disjoint_set.size&&([r,s]=[s,r]),s.__disjoint_set.parent=r,s.__disjoint_set.children.forEach(r.__disjoint_set.children.add,r.__disjoint_set.children),r.__disjoint_set.size+=s.__disjoint_set.size),this}}class X{constructor(t=null,e=q){return this._Node=class{constructor(r,s=null,n=null,i=null){this.pivot=r,this.child1=s,this.child2=n,this.radius=i}},this._Leaf=class{constructor(r){this.points=r}},this._metric=e,t&&this.add(t),this}add(t){return t=t.map((e,r)=>({index:r,element:e})),this._root=this._construct(t),this}_construct(t){if(t.length===1)return new this._Leaf(t);{let e,r=this._greatest_spread(t),s=t.sort((c,u)=>c.element[r]-u.element[r]),n=s.length,i=Math.floor(n/2),a=t[i],o=s.slice(0,i),h=s.slice(i,n),_=Math.max(...t.map(c=>this._metric(a.element,c.element)));return e=o.length>0&&h.length>0?new this._Node(a,this._construct(o),this._construct(h),_):new this._Leaf(t),e}}_greatest_spread(t){let e=t[0].element.length,r=new Array(e);for(let i=0;i<e;++i)r[i]=[1/0,-1/0];let s=t.reduce((i,a)=>{for(let o=0;o<e;++o)i[o][0]=Math.min(i[o][0],a.element[o]),i[o][1]=Math.max(i[o][1],a.element[o]);return i},r);s=s.map(i=>i[1]-i[0]);let n=0;for(let i=0;i<e;++i)n=s[i]>s[n]?i:n;return n}search(t,e=5){return this._search(t,e,new E(null,r=>this._metric(r.element,t),"max"),this._root)}_search(t,e,r,s){if(r.length>=e&&s.pivot&&s.radius&&this._metric(t,s.pivot.element)-s.radius>=r.first.value)return r;if(s.child1&&this._search(t,e,r,s.child1),s.child2&&this._search(t,e,r,s.child2),s.points)for(let n=0,i=s.points.length;n<i;++n){let a=s.points[n];e>r.length?r.push(a):(r.push(a),r.pop())}return r}}class ie{constructor(t=null,e=q){this._metric=e,this._elements=t instanceof w?t:w.from(t);const r=this._elements.shape[0];this._D=e==="precomputed"?this._elements.clone():F(this._elements,e),this.KNN=[];for(let s=0;s<r;++s){const n=this._D.row(s),i=new E(null,a=>a.value,"min");for(let a=0;a<r;++a)i.push({value:n[a],index:a});this.KNN.push(i)}}search(t,e=5){const r=this._metric,s=this.KNN;let n;if(Array.isArray(t)){if(this._metric=="precomputed")throw"Search by query element is only possible when not using a precomputed distance matrix!";const a=this._elements,o=s.length;let h=null,_=1/0;for(let c=0;c<o;++c){const u=r(t,a.row(c));u<_&&(h=c,_=u)}n=s[h]}else Number.isInteger(t)&&(n=s[t]);let i=[];for(let a=0;a<e;++a)i.push(n.pop());return i.forEach(a=>n.push(a.element)),i}}class D{constructor(t,e,r){if(this._parameters=Object.assign(Object.seal(e),r),Array.isArray(t))this._type="array",this.X=w.from(t);else{if(!(t instanceof w))throw new Error("No valid type for X!");this._type="matrix",this.X=t}return[this._N,this._D]=this.X.shape,this._randomizer=new O(this._parameters.seed),this._is_initialized=!1,this}parameter(t=null,e=null){if(t===null)return Object.assign({},this._parameters);if(!this._parameters.hasOwnProperty(t))throw new Error(`${t} is not a valid parameter!`);return e!==null?(this._parameters[t]=e,this._is_initialized=!1,this):this._parameters[t]}para(t=null,e=null){return this.parameter(t,e)}p(t=null,e=null){return this.parameter(t,e)}transform(){return this.check_init(),this.projection}*generator(){return this.transform()}check_init(){return this._is_initialized||typeof this.init!="function"||(this.init(),this._is_initialized=!0),this}get projection(){if(this.hasOwnProperty("Y"))return this.check_init(),this._type==="matrix"?this.Y:this.Y.to2dArray;throw new Error("The dataset is not transformed yet!")}async transform_async(...t){return this.transform(...t)}static transform(...t){return new this(...t).transform()}static async transform_async(...t){return this.transform(...t)}static*generator(...t){const e=new this(...t).generator();for(const r of e)yield r}}class J extends D{constructor(t,e){return super(t,{d:2,seed:1212,eig_args:{}},e),this._parameters.eig_args.hasOwnProperty("seed")||(this._parameters.eig_args.seed=this._randomizer),this}transform(t=null){const e=this.principal_components();if(t==null){const r=this.X;return this.Y=r.dot(e),this.projection}if(Array.isArray(t))return w.from(t).dot(e).asArray;if(t instanceof w)return t.dot(e);throw new Error("No valid type for A!")}principal_components(){if(this.V)return this.V;const{d:t,eig_args:e}=this._parameters,r=this.X,s=r.sub(r.meanCols),n=s.transDot(s),{eigenvectors:i}=N(n,t,e);return this.V=w.from(i).transpose(),this.V}static principal_components(t,e){return new this(t,e).principal_components()}}class W extends D{constructor(t,e){return super(t,{d:2,metric:q,seed:1212,eig_args:{}},e),this._parameters.eig_args.hasOwnProperty("seed")||(this._parameters.eig_args.seed=this._randomizer),this}transform(){const t=this.X,e=t.shape[0],{d:r,metric:s,eig_args:n}=this._parameters,i=s==="precomputed"?t:F(t,s),a=i.meanCols,o=i.meanRows,h=i.mean;this._d_X=i;const _=new w(e,e,(u,f)=>i.entry(u,f)-a[u]-o[f]+h),{eigenvectors:c}=N(_,r,n);return this.Y=w.from(c).transpose(),this.projection}stress(){const t=this.X.shape[0],e=this.Y,r=this._d_X,s=new w;s.shape=[t,t,(a,o)=>a<o?q(e.row(a),e.row(o)):s.entry(o,a)];let n=0,i=0;for(let a=0;a<t;++a)for(let o=a+1;o<t;++o)n+=Math.pow(r.entry(a,o)-s.entry(a,o),2),i+=Math.pow(r.entry(a,o),2);return Math.sqrt(n/i)}}class qr extends D{constructor(t,e){return super(t,{neighbors:void 0,d:2,metric:q,seed:1212,eig_args:{}},e),this.parameter("neighbors",Math.min(this._parameters.neighbors??Math.max(Math.floor(this.X.shape[0]/10),2),this._N-1)),this._parameters.eig_args.hasOwnProperty("seed")||(this._parameters.eig_args.seed=this._randomizer),this}transform(){this.check_init();const t=this.X,e=this._N,{d:r,metric:s,eig_args:n,neighbors:i}=this._parameters,a=new w;a.shape=[e,e,(g,y)=>g<=y?s(t.row(g),t.row(y)):a.entry(y,g)];const o=[];for(let g=0;g<e;++g){const y=[];for(let b=0;b<e;++b)y.push({index:b,distance:a.entry(g,b)});const m=new E(y,b=>b.distance,"min");o.push(m.toArray().slice(1,i+1))}const h=new w(e,e,(g,y)=>{const m=o[g].find(b=>b.index===y);return m?m.distance:1/0});for(let g=0;g<e;++g)for(let y=0;y<e;++y){let m=h.entry(g,y);for(let b=0;b<e;++b)m=Math.min(m,h.entry(g,b)+h.entry(b,y));h.set_entry(g,y,m)}let _=new Float64Array(e),c=new Float64Array(e),u=0;const f=new w(e,e,(g,y)=>{let m=h.entry(g,y);return m=m===1/0?0:m,_[g]+=m,c[y]+=m,u+=m,m});_=_.map(g=>g/e),c=c.map(g=>g/e),u/=e**2;const d=new w(e,e,(g,y)=>f.entry(g,y)-_[g]-c[y]+u),{eigenvectors:p}=N(d,r,n);return this.Y=w.from(p).transpose(),this.projection}}class xr extends D{constructor(t,e){return super(t,{d:2,metric:q,seed:1212},e),this}_choose_distant_objects(t){const e=this.X.shape[0];let r=this._randomizer.random_int%e-1,s=null,n=-1/0;for(let i=0;i<e;++i){const a=t(r,i);a>n&&(n=a,s=i)}n=-1/0;for(let i=0;i<e;++i){const a=t(s,i);a>n&&(n=a,r=i)}return[r,s,n]}transform(){const t=this.X,e=t.shape[0],{d:r,metric:s}=this._parameters,n=new w(e,r,0);let i=(a,o)=>s(t.row(a),t.row(o));for(let a=0;a<r;++a){let o=i;const[h,_,c]=this._choose_distant_objects(i);if(c!==0){for(let u=0;u<e;++u){const f=(i(h,u)**2+c**2-i(_,u)**2)/(2*c);n.set_entry(u,a,f)}i=(u,f)=>Math.sqrt(o(u,f)**2-(n.entry(u,a)-n.entry(f,a))**2)}}return this.Y=n,this.projection}}class Cr extends D{constructor(t,e){return super(t,{labels:null,d:2,seed:1212,eig_args:{}},e),this._parameters.eig_args.hasOwnProperty("seed")||(this._parameters.eig_args.seed=this._randomizer),this}transform(){const t=this.X,[e,r]=t.shape,{d:s,labels:n,eig_args:i}=this._parameters;if(n===null||n.length!=e)throw new Error("LDA needs parameter label to every datapoint to work!");const a={};let o=0;n.forEach((d,p)=>{d in a?(a[d].count++,a[d].rows.push(t.row(p))):a[d]={id:o++,count:1,rows:[t.row(p)]}});const h=t.mean,_=new w(o,r);for(const d in a){const p=w.from(a[d].rows).meanCols;for(let g=0;g<r;++g)_.set_entry(a[d].id,g,p[g])}let c=new w(r,r);for(const d in a){const p=_.row(a[d].id),g=new w(r,1,m=>p[m]-h),y=a[d].count;c=c.add(g.dotTrans(g).mult(y))}let u=new w(r,r);for(const d in a){const p=_.row(a[d].id),g=new w(r,1,m=>p[m]),y=a[d].rows;for(let m=0,b=a[d].count;m<b;++m){const v=new w(r,1,(A,M)=>y[m][A]-g.entry(A,0));u=u.add(v.dotTrans(v))}}let{eigenvectors:f}=N(u.inverse().dot(c),s,i);return f=w.from(f).transpose(),this.Y=t.dot(f),this.projection}}class jr extends D{constructor(t,e){return super(t,{neighbors:void 0,d:2,metric:q,seed:1212,eig_args:{}},e),this.parameter("neighbors",Math.min(e.neighbors??Math.max(Math.floor(this._N/10),2),this._N-1)),this._parameters.eig_args.hasOwnProperty("seed")||(this._parameters.eig_args.seed=this._randomizer),this}transform(){const t=this.X,e=this._N,r=this._D,{neighbors:s,d:n,eig_args:i,metric:a}=this._parameters,o=Q(t,s,a),h=new w(s,1,1),_=new w(e,e);for(let d=0;d<e;++d){const p=o[d],g=new w(s,r,(b,v)=>t.entry(p[b].j,v)-t.entry(d,v)),y=g.dotTrans(g);if(s>r){const b=R(y.diag)/1e3;for(let v=0;v<s;++v)y.add_entry(v,v,b)}let m=w.solve_CG(y,h,this._randomizer);m=m.divide(m.sum);for(let b=0;b<s;++b)_.set_entry(d,p[b].j,m.entry(b,0))}const c=new w(e,e,"identity").sub(_),u=c.transDot(c),{eigenvectors:f}=N(u.T.inverse(),n+1,i);return this.Y=w.from(f.slice(1,1+n)).T,this.projection}}class Sr extends D{constructor(t,e){if(super(t,{neighbors:void 0,d:2,metric:q,seed:1212,eig_args:{}},e),this.parameter("neighbors",Math.min(e.neighbors??Math.max(Math.floor(this._N/10),2),this._N-1)),this._parameters.eig_args.hasOwnProperty("seed")||(this._parameters.eig_args.seed=this._randomizer),this._D<=this.parameter("d"))throw new Error(`Dimensionality of X (D = ${this._D}) must be greater than the required dimensionality of the result (d = ${this.parameter("d")})!`);return this}transform(){const t=this.X,[e,r]=t.shape,{d:s,neighbors:n,metric:i,eig_args:a}=this._parameters,o=Q(t,n,i),h=new w(r,r,"center"),_=new w(e,e,0);for(let u=0;u<e;++u){const f=[u,...o[u].map(b=>b.j)];let d=w.from(f.map(b=>t.row(b)));d=d.dot(h);const p=d.dotTrans(d),{eigenvectors:g}=N(p,s,a),y=w.from(g),m=y.transDot(y).add(1/Math.sqrt(n+1));for(let b=0;b<n+1;++b)for(let v=0;v<n+1;++v)_.add_entry(f[b],f[v],m.entry(b,v)-(b===v?1:0))}const{eigenvectors:c}=N(_,s+1,a);return this.Y=w.from(c.slice(1)).transpose(),this.projection}}class Dr extends D{constructor(t,e){return super(t,{perplexity:50,epsilon:10,d:2,metric:k,seed:1212},e),[this._N,this._D]=this.X.shape,this._iter=0,this.Y=new w(this._N,this.parameter("d"),()=>1e-4*this._randomizer.gauss_random()),this}init(){const t=Math.log(this.parameter("perplexity")),e=this._N,r=this._D,{metric:s}=this._parameters,n=this.X;let i;if(s=="precomputed")i=druid.Matrix.from(n);else{i=new w(e,e);for(let h=0;h<e;++h){const _=n.row(h);for(let c=h+1;c<e;++c){const u=s(_,n.row(c));i.set_entry(h,c,u),i.set_entry(c,h,u)}}}const a=new w(e,e,0);this._ystep=new w(e,r,0),this._gains=new w(e,r,1);for(let h=0;h<e;++h){const _=i.row(h),c=a.row(h);let u,f=-1/0,d=1/0,p=1,g=50,y=!1;for(;!y&&g--;){u=0;let m=0;for(let v=0;v<e;++v){const A=_[v],M=h!==v?Math.exp(-A*p):0;m+=A*M,c[v]=M,u+=M}const b=u>0?Math.log(u)+p*m/u:0;b>t?(f=p,p=d===1/0?2*p:(p+d)/2):(d=p,p=f===-1/0?p/2:(p+f)/2),y=Math.abs(b-t)<1e-4}for(let m=0;m<e;++m)c[m]/=u}const o=2*e;for(let h=0;h<e;++h)for(let _=h;_<e;++_){const c=Math.max((a.entry(h,_)+a.entry(_,h))/o,1e-100);a.set_entry(h,_,c),a.set_entry(_,h,c)}return this._P=a,this}transform(t=500){this.check_init();for(let e=0;e<t;++e)this.next();return this.projection}*generator(t=500){this.check_init();for(let e=0;e<t;++e)this.next(),yield this.projection;return this.projection}next(){const t=++this._iter,e=this._P,r=this._ystep,s=this._gains,n=this._N,{d:i,epsilon:a}=this._parameters;let o=this.Y;const h=t<100?4:1,_=new w(n,n,"zeros");let c=0;for(let p=0;p<n;++p)for(let g=p+1;g<n;++g){let y=0;for(let b=0;b<i;++b){const v=o.entry(p,b)-o.entry(g,b);y+=v*v}const m=1/(1+y);_.set_entry(p,g,m),_.set_entry(g,p,m),c+=2*m}const u=new w(n,n,0);for(let p=0;p<n;++p)for(let g=p+1;g<n;++g){const y=Math.max(_.entry(p,g)/c,1e-100);u.set_entry(p,g,y),u.set_entry(g,p,y)}const f=new w(n,i,"zeros");for(let p=0;p<n;++p)for(let g=0;g<n;++g){const y=4*(h*e.entry(p,g)-u.entry(p,g))*_.entry(p,g);for(let m=0;m<i;++m)f.add_entry(p,m,y*(o.entry(p,m)-o.entry(g,m)))}let d=new Float64Array(i);for(let p=0;p<n;++p)for(let g=0;g<i;++g){const y=f.entry(p,g),m=r.entry(p,g),b=s.entry(p,g);let v=Math.sign(y)===Math.sign(m)?.8*b:b+.2;v<.01&&(v=.01),s.set_entry(p,g,v);const A=(t<250?.5:.8)*m-a*v*y;r.set_entry(p,g,A),o.add_entry(p,g,A),d[g]+=o.entry(p,g)}for(let p=0;p<n;++p)for(let g=0;g<i;++g)o.sub_entry(p,g,d[g]/n);return this.Y}}function ae(l,t,e=300){const r=t.length;let s=.001,n=1e4,i=t.slice(),a=l(i),o=!1;for(;e-->=0&&!o;){o=!0;for(let h=0;h<r;++h){i[h]+=1e-6;let _=l(i);i[h]-=1e-6;let c=(_-a)/1e-6;Math.abs(c)>.01&&(o=!1),i[h]-=s*c,a=l(i)}s*=n>=a?1.05:.4,n=a}return i}class zr extends D{constructor(t,e){if(super(t,{n_neighbors:15,local_connectivity:1,min_dist:1,d:2,metric:q,seed:1212,_spread:1,_set_op_mix_ratio:1,_repulsion_strength:1,_negative_sample_rate:5,_n_epochs:350,_initial_alpha:1},e),[this._N,this._D]=this.X.shape,this.parameter("n_neighbors")>this._N)throw new Error(`Parameter n_neighbors (=${this.parameter("n_neighbors")}) needs to be smaller than dataset size (N=${this._N})!`);if(this.parameter("local_connectivity")>this.parameter("n_neighbors"))throw new Error(`Parameter local_connectivity (=${this.parameter("local_connectivity")}) needs to be smaller than parameter n_neighbors (=${this.parameter("n_neighbors")})`);this._iter=0;const r=this._randomizer;return this.Y=new w(this._N,this.parameter("d"),()=>r.random),this}_find_ab_params(t,e){const r=z(0,3*t,300),s=z(0,3*t,300);for(let n=0,i=r.length;n<i;++n){const a=r[n];s[n]=a<e?1:Math.exp(-(a-e)/t)}return ae(n=>{const i=z(1,300).map((a,o)=>{return s[o]-(h=r[o],_=n[0],c=n[1],1/(1+_*Math.pow(h,2*c)));var h,_,c});return Math.sqrt(R(i.map(a=>a*a)))},[1,1])}_compute_membership_strengths(t,e,r){for(let s=0,n=t.length;s<n;++s){const i=r[s],a=t[s];for(let o=0,h=a.length;o<h;++o){const _=a[o].value-i;a[o].value=_>0?Math.exp(-_/e[s]):1}}return t}_smooth_knn_dist(t,e){const{local_connectivity:n,metric:i}=this._parameters,a=Math.log2(e),o=[],h=[],_=this.X,c=_.shape[0],u=[];if(i==="precomputed")for(let p=0;p<c;++p)u.push(t.search(p,e).reverse());else for(const p of _)u.push(t.search(p,e).raw_data().reverse());const f=Math.floor(n),d=n-f;for(let p=0;p<c;++p){let g=0,y=1/0,m=1,b=0;const v=u[p],A=v.filter(x=>x.value>0),M=A.length;M>=n?f>0?(b=A[f-1].value,d>1e-5&&(b+=d*(A[f].value-A[f-1].value))):b=d*A[0].value:M>0&&(b=A[M-1].value);for(let x=0;x<64;++x){let C=0;for(let j=0;j<e;++j){const S=v[j].value-b;C+=S>0?Math.exp(-S/m):1}if(Math.abs(C-a)<1e-5)break;C>a?[y,m]=[m,(g+y)/2]:[g,m]=y===1/0?[m,2*m]:[m,(g+y)/2]}if(b>0){const x=v.reduce((C,j)=>C+j.value,0)/v.length;m<.001*x&&(m=.001*x)}else{const x=u.reduce((C,j)=>C+j.reduce((S,T)=>S+T.value,0)/j.length);m<.001*x&&(m=.001*x)}o[p]=b,h[p]=m}return{distances:u,sigmas:h,rhos:o}}_fuzzy_simplicial_set(t,e){const r=t.shape[0],{metric:s,_set_op_mix_ratio:n}=this._parameters,i=s==="precomputed"?new ie(t,"precomputed"):new X(t.to2dArray,s);let{distances:a,sigmas:o,rhos:h}=this._smooth_knn_dist(i,e);a=this._compute_membership_strengths(a,o,h);const _=new w(r,r,"zeros");for(let f=0;f<r;++f){const d=a[f];for(let p=0;p<d.length;++p)_.set_entry(f,d[p].element.index,d[p].value)}const c=_.T,u=_.mult(c);return _.add(c).sub(u).mult(n).add(u.mult(1-n))}_make_epochs_per_sample(t){const e=this._weights,r=new Float32Array(e.length).fill(-1),s=t/ne(e);return e.forEach((n,i)=>{const a=n*s;a>0&&(r[i]=Math.round(t/a))}),r}_tocoo(t){const e=[],r=[],s=[],[n,i]=t.shape;for(let a=0;a<n;++a)for(let o=0;o<i;++o){const h=t.entry(a,o);h!==0&&(e.push(a),r.push(o),s.push(h))}return{rows:e,cols:r,data:s}}init(){const{_spread:t,min_dist:e,n_neighbors:r,_n_epochs:s,_negative_sample_rate:n}=this._parameters,[i,a]=this._find_ab_params(t,e);this._a=i,this._b=a,this._graph=this._fuzzy_simplicial_set(this.X,r);const{rows:o,cols:h,data:_}=this._tocoo(this._graph);return this._head=o,this._tail=h,this._weights=_,this._epochs_per_sample=this._make_epochs_per_sample(s),this._epochs_per_negative_sample=this._epochs_per_sample.map(c=>c*n),this._epoch_of_next_sample=this._epochs_per_sample.slice(),this._epoch_of_next_negative_sample=this._epochs_per_negative_sample.slice(),this}graph(){return this.check_init(),{cols:this._head,rows:this._tail,weights:this._weights}}transform(t=350){this.parameter("_n_epochs")!=t&&(this.parameter("_n_epochs",t),this.init()),this.check_init();for(let e=0;e<t;++e)this.next();return this.projection}*generator(t=350){this.parameter("_n_epochs")!=t&&(this.parameter("_n_epochs",t),this.init()),this.check_init();for(let e=0;e<t;++e)this.next(),yield this.projection;return this.projection}_clip(t){return t>4?4:t<-4?-4:t}_optimize_layout(t,e,r,s){const n=this._randomizer,{_repulsion_strength:i,d:a}=this._parameters,{_alpha:o,_a:h,_b:_,_epochs_per_sample:c,_epochs_per_negative_sample:u,_epoch_of_next_negative_sample:f,_epoch_of_next_sample:d,_clip:p}=this,g=s.length;for(let y=0,m=c.length;y<m;++y)if(d[y]<=this._iter){const b=r[y],v=s[y],A=t.row(b),M=e.row(v),x=k(A,M);if(x>0){const j=-2*h*_*Math.pow(x,_-1)/(h*Math.pow(x,_)+1);for(let S=0;S<a;++S){const T=p(j*(A[S]-M[S]))*o;A[S]+=T,M[S]-=T}}d[y]+=c[y];const C=(this._iter-f[y])/u[y];for(let j=0;j<C;++j){const S=n.random_int%g,T=e.row(s[S]),L=k(A,T);if(L>0){const re=2*i*_/((.01+L)*(h*Math.pow(L,_)+1));for(let P=0;P<a;++P){const U=p(re*(A[P]-T[P]))*o;A[P]+=U,T[P]-=U}}else if(b===S)continue}f[y]+=C*u[y]}return t}next(){const t=++this._iter,e=this.Y,{_initial_alpha:r,_n_epochs:s}=this._parameters;return this._alpha=r*(1-t/s),this.Y=this._optimize_layout(e,e,this._head,this._tail),this.Y}}class Rr extends D{constructor(t,e){return super(t,{weight_adj:500,c:5,d:2,metric:q,tol:1e-8,seed:1212},e),this}init(t=null,e=null){const r=this.X,s=r.shape[0],{c:n,d:i,metric:a,seed:o}=this._parameters;this.n_inliers=2*n,this.n_outliers=1*n,this.n_random=1*n,this.Y=t||new J(r,{d:i,seed:o}).transform(),this.knn=e||new X(r.to2dArray,a);const{triplets:h,weights:_}=this._generate_triplets(this.n_inliers,this.n_outliers,this.n_random);return this.triplets=h,this.weights=_,this.lr=1e3*s/h.shape[0],this.C=1/0,this.vel=new w(s,i,0),this.gain=new w(s,i,1),this}_generate_triplets(t,e,r){const{metric:s,weight_adj:n}=this._parameters,i=this.X,a=i.shape[0],o=this.knn,h=Math.min(t+20,a),_=new w(a,h),c=new w(a,h);for(let v=0;v<a;++v)o.search(i.row(v),h+1).raw_data().filter(A=>A.value!=0).sort((A,M)=>A.value-M.value).forEach((A,M)=>{_.set_entry(v,M,A.element.index),c.set_entry(v,M,A.value)});const u=new Float64Array(a);for(let v=0;v<a;++v)u[v]=Math.max((c.entry(v,3)+c.entry(v,4)+c.entry(v,5)+c.entry(v,6))/4,1e-10);const f=this._find_p(c,u,_);let d=this._sample_knn_triplets(f,_,t,e),p=d.shape[0];const g=new Float64Array(p);for(let v=0;v<p;++v){const A=d.entry(v,0),M=d.entry(v,2);g[v]=s(i.row(A),i.row(M))}let y=this._find_weights(d,f,_,g,u);if(r>0){const{random_triplets:v,random_weights:A}=this._sample_random_triplets(i,r,u);d=d.concat(v,"vertical"),y=Float64Array.from([...y,...A])}p=d.shape[0];let m=-1/0;for(let v=0;v<p;++v)isNaN(y[v])&&(y[v]=0),m<y[v]&&(m=y[v]);let b=-1/0;for(let v=0;v<p;++v)y[v]/=m,y[v]+=1e-4,y[v]=Math.log(1+n*y[v]),b<y[v]&&(b=y[v]);for(let v=0;v<p;++v)y[v]/=b;return{triplets:d,weights:y}}_find_p(t,e,r){const[s,n]=t.shape;return new w(s,n,(i,a)=>Math.exp(-(t.entry(i,a)**2)/e[i]/e[r.entry(i,a)]))}_sample_knn_triplets(t,e,r,s){const n=e.shape[0],i=new w(n*r*s,3);for(let a=0;a<n;++a){let o=a*r*s;const h=this.__argsort(t.row(a));for(let _=0;_<r;++_){let c=_*s;const u=e.entry(a,h[_]),f=this._rejection_sample(s,n,h.slice(0,_+1));for(let d=0;d<s;++d){const p=o+c+d,g=f[d];i.set_entry(p,0,a),i.set_entry(p,1,u),i.set_entry(p,2,g)}}}return i}__argsort(t){return z(0,t.length-1).sort((e,r)=>t[r]-t[e])}_rejection_sample(t,e,r){const s=this._randomizer,n=z(0,e-1).filter(i=>r.indexOf(i)<0);return s.choice(n,Math.min(t,n.length-2))}_find_weights(t,e,r,s,n){const i=t.shape[0],a=new Float64Array(i);for(let o=0;o<i;++o){const h=t.entry(o,0),_=r.row(h).indexOf(t.entry(o,1)),c=e.entry(h,_);let u=Math.exp(-(s[o]**2)/(n[h]*n[t.entry(o,2)]));u<1e-20&&(u=1e-20),a[o]=c/u}return a}_sample_random_triplets(t,e,r){const s=this.parameter("metric"),n=this._randomizer,i=t.shape[0],a=new w(i*e,3),o=new Float64Array(i*e);for(let h=0;h<i;++h){const _=h*e,c=[...z(0,h-1),...z(h+1,i-1)];for(let u=0;u<e;++u){let[f,d]=n.choice(c,2),p=Math.exp(-(s(t.row(h),t.row(f))**2)/(r[h]*r[f]));p<1e-20&&(p=1e-20);let g=Math.exp(-(s(t.row(h),t.row(d))**2)/(r[h]*r[d]));g<1e-20&&(g=1e-20),p<g&&([f,d]=[d,f],[p,g]=[g,p]);const y=_+u;a.set_entry(y,0,h),a.set_entry(y,1,f),a.set_entry(y,2,d),o[y]=p/g}}return{random_triplets:a,random_weights:o}}_grad(t){const e=this.n_inliers,r=this.n_outliers,s=this.triplets,n=this.weights,[i,a]=t.shape,o=s.shape[0],h=new w(i,a,0);let _=new Float64Array(a),c=new Float64Array(a),u=1,f=1,d=0,p=0;const g=i*e*r;for(let y=0;y<o;++y){const[m,b,v]=s.row(y);if(y%r==0||y>=g){u=1,f=1;for(let M=0;M<a;++M){const x=t.entry(m,M),C=t.entry(b,M),j=t.entry(v,M);_[M]=x-C,c[M]=x-j,u+=_[M]**2,f+=c[M]**2}}else{f=1;for(let M=0;M<a;++M){const x=t.entry(m,M),C=t.entry(v,M);c[M]=x-C,f+=c[M]**2}}u>f&&++d,p+=n[y]/(1+f/u);const A=(n[y]/(u+f))**2;for(let M=0;M<a;++M){const x=_[M]*f*A,C=c[M]*u*A;h.add_entry(m,M,x-C),h.sub_entry(b,M,x),h.add_entry(v,M,C)}}return{grad:h,loss:p,n_viol:d}}transform(t=400){this.check_init();for(let e=0;e<t;++e)this._next(e);return this.projection}*generator(t=800){this.check_init();for(let e=0;e<t;++e)this._next(e),yield this.projection;return this.projection}_next(t){const e=t>150?.5:.3,r=this.C,s=this.vel,n=this.Y.add(s.mult(e)),{grad:i,loss:a,n_viol:o}=this._grad(n);return this.C=a,this.Y=this._update_embedding(n,t,i),this.lr*=r>a+this._parameters.tol?1.01:.9,this.Y}_update_embedding(t,e,r){const[s,n]=t.shape,i=e>150?.9:.5,a=this.gain,o=this.vel,h=this.lr;for(let _=0;_<s;++_)for(let c=0;c<n;++c){const u=Math.sign(o.entry(_,c))!=Math.sign(r.entry(_,c))?a.entry(_,c)+.2:Math.max(.8*a.entry(_,c),.01);a.set_entry(_,c,u),o.set_entry(_,c,i*o.entry(_,c)-h*a.entry(_,c)*r.entry(_,c)),t.set_entry(_,c,t.entry(_,c)+o.entry(_,c))}return t}}class Nr{constructor(t,e="complete",r=q){if(this._id=0,this._matrix=t instanceof w?t:w.from(t),this._metric=r,this._linkage=e,r==="precomputed"&&this._matrix.shape[0]!==this._matrix.shape[1])throw new Error("If metric is 'precomputed', then matrix has to be square!");return this.init(),this.root=this.do(),this}get_clusters(t,e="distance"){let r,s=[];switch(e){case"distance":r=n=>n.dist;break;case"depth":r=n=>n.depth;break;default:throw new Error("invalid type")}return this._traverse(this.root,r,t,s),s}_traverse(t,e,r,s){e(t)<=r?s.push(t.leaves()):(this._traverse(t.left,e,r,s),this._traverse(t.right,e,r,s))}init(){const t=this._metric,e=this._matrix,r=this._n=e.shape[0],s=this._d_min=new Float64Array(r);let n;if(t!=="precomputed"){n=new w(r,r,0);for(let o=0;o<r;++o){s[o]=0;for(let h=0;h<r;++h)n.set_entry(o,h,o===h?1/0:t(e.row(o),e.row(h))),n.entry(o,s[o])>n.entry(o,h)&&(s[o]=h)}}else{n=this._matrix.clone();for(let o=0;o<r;++o)for(let h=0;h<r;++h)o===h?n.set_entry(o,h,1/0):n.entry(o,s[o])>n.entry(o,h)&&(s[o]=h)}this._distance_matrix=n;const i=this._clusters=new Array(r),a=this._c_size=new Uint16Array(r);for(let o=0;o<r;++o)i[o]=[],i[o][0]=new oe(this._id++,null,null,0,e.row(o),o,1,0),a[o]=1;return this}do(){const t=this._n,e=this._d_min,r=this._distance_matrix,s=this._clusters,n=this._c_size,i=this._linkage;let a=null;for(let o=0,h=t-1;o<h;++o){let _=0;for(let m=0;m<t;++m){let b=r.entry(m,e[m]);for(let v=m+1;v<t;++v)b>r.entry(m,v)&&(e[m]=v,b=r.entry(m,e[m]))}for(let m=0;m<t;++m)r.entry(m,e[m])<r.entry(_,e[_])&&(_=m);let c=e[_],u=s[_][0],f=s[c][0],d=u.isLeaf?[u.index]:u.index,p=f.isLeaf?[f.index]:f.index,g=d.concat(p),y=new oe(this._id++,u,f,r.entry(_,c),null,g);u.parent=y,f.parent=y,s[_].unshift(y),n[_]+=n[c];for(let m=0;m<t;++m){const b=r.entry(_,m),v=r.entry(c,m);let A;switch(i){case"single":A=Math.min(b,v);break;case"complete":A=Math.max(b,v);break;case"average":A=(n[_]*b+n[c]*v)/(n[_]+n[m])}r.set_entry(m,_,A),r.set_entry(_,m,A)}r.set_entry(_,_,1/0);for(let m=0;m<t;++m)r.set_entry(m,c,1/0),r.set_entry(c,m,1/0);a=y}return a}}class oe{constructor(t,e,r,s,n,i,a,o){return this.id=t,this.left=e,this.right=r,this.dist=s,this.index=i,this.size=a??e.size+r.size,this.depth=o??1+Math.max(e.depth,r.depth),this.centroid=n??this._calculate_centroid(e,r),this.parent=null,this}_calculate_centroid(t,e){const r=t.size,s=e.size,n=t.centroid,i=e.centroid,a=this.size,o=t.centroid.length,h=new Float64Array(o);for(let _=0;_<o;++_)h[_]=(r*n[_]+s*i[_])/a;return h}get isLeaf(){return this.depth===0}leaves(){if(this.isLeaf)return[this];const t=this.left,e=this.right;return(t.isLeaf?[t]:t.leaves()).concat(e.isLeaf?[e]:e.leaves())}descendants(){if(this.isLeaf)return[this];const t=this.left.descendants(),e=this.right.descendants();return t.concat(e).concat([this])}}class Er{constructor(t,e,r=q,s=1987,n=!0){this._metric=r,this._matrix=t,this._K=e;const[i,a]=t.shape;return this._N=i,this._D=a,e>i&&(e=i),this._randomizer=new O(s),this._clusters=new Array(i).fill(void 0),this._cluster_centroids=this._get_random_centroids(e),n&&this.init(e,this._cluster_centroids),this}get_clusters(){const t=this._K,e=this._clusters,r=new Array(t).fill().map(()=>new Array);return e.forEach((s,n)=>r[s].push(n)),r}_furthest_point(t,e){const r=this._matrix,s=this._metric;let n=t.length;return E.heapify(e,i=>{const a=r.row(i);let o=0;for(let h=0;h<n;++h)o+=s(a,t[h]);return o},"max").pop().element}_get_random_centroids(t){const e=this._N,r=this._randomizer,s=this._matrix,n=new Array(t).fill(),i=z(0,e-1),a=r.random_int%(e-1);n[0]=s.row(a);const o=[a],h=Math.floor((e-t)/t);for(let _=1;_<t;++_){const c=r.choice(i.filter(f=>o.indexOf(f)==-1),h),u=this._furthest_point(n.slice(0,_),c);o.push(u),n[_]=s.row(u)}return n}_iteration(t){const e=t.length,r=this._N,s=this._D,n=this._matrix,i=this._metric,a=this._clusters;let o=!1;for(let h=0;h<r;++h){const _=n.row(h);let c=1/0,u=null;for(let f=0;f<e;++f){let d=i(t[f],_);d<c&&(c=d,u=f)}a[h]!==u&&(o=!0),a[h]=u}for(let h=0;h<e;++h){const _=t[h];for(let c=0;c<s;++c)_[c]=0}return this._compute_centroid(t),{clusters_changed:o,cluster_centroids:t}}_compute_centroid(t){const e=t.length,r=this._N,s=this._D,n=this._matrix,i=this._clusters,a=new Array(e).fill(0);for(let o=0;o<r;++o){const h=n.row(o),_=i[o];a[_]++;const c=t[_];for(let u=0;u<s;++u)c[u]+=h[u]}for(let o=0;o<e;++o){const h=a[o];t[o]=t[o].map(_=>_/h)}}init(t,e){t||(t=this._K),e||(e=this._get_random_centroids(t));let r=!1;do{const s=this._iteration(e);e=s.cluster_centroids,r=s.clusters_changed}while(r)}}class he{constructor(t,e,r=null,s=q,n=1212){this._metric=s,this._matrix=t,this._A=this._matrix.to2dArray,this._K=e;const[i,a]=t.shape;return this._N=i,this._D=a,this._max_iter=r||10*Math.log10(i),this._distance_matrix=new w(i,i,"zeros"),e>i&&(e=i),this._randomizer=new O(n),this._clusters=new Array(i).fill(void 0),this._cluster_medoids=this._get_random_medoids(e),this._is_initialized=!1,this}get_clusters(){const t=this._K,e=this._A;this._is_initialized||this.init(t,this._cluster_medoids);const r=new Array(t).fill().map(()=>new Array);return e.forEach((s,n)=>{r[this._nearest_medoid(s,n).index_nearest].push(n)}),r.medoids=this._cluster_medoids,r}async*generator(){const t=this._max_iter;yield this.get_clusters();let e=!1,r=0;do e=this._iteration(),yield this.get_clusters();while(!e&&++r<t)}_iteration(){const t=this._A,e=this._K,r=this._cluster_medoids,s=t.map((a,o)=>this._nearest_medoid(a,o)),n=new Array(e).fill(0),i=new Array(e).fill(null);if(t.forEach((a,o)=>{if(r.findIndex(h=>h===o)<0){const h=s[o].distance_nearest,_=new Array(e).fill(-h);t.forEach((c,u)=>{if(o===u)return;const f=this._get_distance(u,o,c,a),{index_nearest:d,distance_nearest:p,distance_second:g}=s[u];if(_[d]+=Math.min(f,g)-p,f<p)for(let y=0;y<e;++y)y!==d&&(_[y]+=f-p)}),_.map((c,u)=>[c,u]).filter(([c,u])=>c<n[u]).forEach(([c,u])=>{c<n[u]&&(n[u]=c,i[u]=o)})}}),$(n)>=0)return!0;for(;$(n)<0;){const a=n.map((o,h)=>[o,h]).sort(([o],[h])=>o-h)[0][1];r.filter(o=>o==i[a]).length==0&&(r[a]=i[a]),n[a]=0,n.map((o,h)=>[o,h]).filter(([o])=>o<0).forEach(([o,h])=>{const _=t[h];let c=0;t.forEach((u,f)=>{r.findIndex(d=>d!=h&&d==f)>=0||a!=h&&(s[f].index_nearest===r[h]?c+=Math.min(this._get_distance(f,h,u,_),s[f].distance_second)-s[f].distance_nearest:c+=Math.min(this._get_distance(f,h,u,_)-s[f].distance_nearest,0))}),n[h]=c})}return this._cluster_medoids=r,!1}_get_distance(t,e,r=null,s=null){if(t===e)return 0;const n=this._distance_matrix,i=this._A,a=this._metric;let o=n.entry(t,e);return o===0&&(o=a(r||i[t],s||i[e]),n.set_entry(t,e,o),n.set_entry(e,t,o)),o}_nearest_medoid(t,e){const r=this._cluster_medoids,s=this._A,[n,i]=r.map((a,o)=>{const h=s[a];return[this._get_distance(e,a,t,h),o]}).sort((a,o)=>a[0]-o[0]);return{distance_nearest:n[0],index_nearest:n[1],distance_second:i[0],index_second:i[1]}}init(t,e){t||(t=this._K),e||(e=this._get_random_medoids(t));const r=this._max_iter;let s=!1,n=0;do s=this._iteration();while(!s&&++n<r);return this}_get_random_medoids(t){const e=this._N,r=this._A,s=z(0,e-1),n=this._randomizer,i=Math.min(e,10+Math.ceil(Math.sqrt(e))),a=new Array(i).fill(1/0),o=[];let h=1/0,_=n.choice(s,i);for(let c=0;c<i;++c){const u=_[c],f=r[u];for(let d=0;d<i;++d){if(d===c)continue;const p=r[_[d]];a[c]+=this._get_distance(c,d,f,p)}a[c]<h&&(h=a[c],o.push(u))}for(let c=1;c<t;++c){let u=1/0;_=n.choice(s.filter(f=>o.findIndex(d=>d===f)<0),i);for(let f=0;f<i;++f){let d=0;const p=_[f],g=r[p];for(let y=0;y<i;++y){if(y===f)continue;const m=_[y],b=r[m];let v=this._get_distance(p,m,g,b)-$(o.map(A=>this._get_distance(m,A,b)));v<0&&(d+=v)}d<u&&(u=d,o.push(p))}h+=u}return o.slice(0,t)}}class Tr{constructor(t,e,r,s=q){return this._matrix=t,this._epsilon=e,this._min_points=r,this._metric=s,this._ordered_list=[],this._clusters=[],this._DB=new Array(t.shape[0]).fill(),this.init(),this}init(){const t=this._ordered_list,e=this._matrix,r=e.shape[0],s=this._DB,n=this._clusters;let i=this._cluster_index=0;for(let a=0;a<r;++a)s[a]={element:e.row(a),index:a,reachability_distance:void 0,processed:!1};for(const a of s)if(!a.processed&&(a.neighbors=this._get_neighbors(a),a.processed=!0,n.push([a.index]),i=n.length-1,t.push(a),this._core_distance(a)!=null)){const o=new E(null,h=>h.reachability_distance,"min");this._update(a,o),this._expand_cluster(o,n[i])}return this}_get_neighbors(t){if("neighbors"in t)return t.neighbors;const e=this._DB,r=this._metric,s=this._epsilon,n=[];for(const i of e)i.index!=t.index&&r(t.element,i.element)<s&&n.push(i);return n}_core_distance(t){const e=this._min_points,r=this._metric;if(!(t.neighbors&&t.neighbors.length<=e))return r(t.element,t.neighbors[e].element)}_update(t,e){const r=this._metric,s=this._core_distance(t),n=this._get_neighbors(t);for(const i of n){if(i.processed)continue;const a=Math.max(s,r(t.element,i.element));e.raw_data().findIndex(o=>o.element==i)<0?(i.reachability_distance=a,e.push(i)):a<i.reachability_distance&&(i.reachability_distance=a,e=E.heapify(e.data(),o=>o.reachability_distance,"min"))}}_expand_cluster(t,e){const r=this._ordered_list;for(;!t.empty;){const s=t.pop().element;s.neighbors=this._get_neighbors(s),s.processed=!0,e.push(s.index),r.push(s),this._core_distance(s)!=null&&(this._update(s,t),this._expand_cluster(t,e))}}get_clusters(){const t=[],e=[],r=this._min_points;for(const s of this._clusters)s.length<r?e.push(...s):t.push(s);return t.push(e),t}get_cluster_affirmation(){const t=this._matrix.shape[0],e=new Array(t).fill(),r=this.get_clusters();for(let s=0,n=r.length;s<n;++s){const i=r[s];for(const a of i)e[a]=s<n-1?s:-1}return e}}class Or extends D{constructor(t,e){return super(t,{neighbors:void 0,control_points:void 0,d:2,metric:q,seed:1212},e),this.parameter("neighbors",Math.min(e.neighbors??Math.max(Math.floor(this._N/10),2),this._N-1)),this.parameter("control_points",Math.min(e.control_points??Math.ceil(Math.sqrt(this._N)),this._N-1)),this._is_initialized=!1,this}init(t=W,e={},r=X){if(this._is_initialized)return this;const s=this.X,n=this._N,i=this.parameter("neighbors"),a=this.parameter("d"),o=this.parameter("seed"),h=this.parameter("metric");e=Object.assign({d:a,metric:h,seed:o},e);const _=this.parameter("control_points"),c=new he(s,_,null,h).get_clusters().medoids,u=new w(_,n,"zeros");c.forEach((v,A)=>{u.set_entry(A,v,1)});const f=new t(w.from(c.map(v=>s.row(v))),e).transform(),d=s.to2dArray,p=new r(d,h),g=new w(n,n,"I"),y=-1/i;d.forEach((v,A)=>{for(const{index:M}of p.search(v,i).iterate())A!==M&&g.set_entry(A,M,y)});const m=g.concat(u,"vertical"),b=new w(n,a,"zeros").concat(f,"vertical");return this._A=m,this._b=b,this._is_initialized=!0,this}transform(){this.check_init();const t=this._A,e=this._b,r=t.transDot(t),s=t.transDot(e);return this.Y=w.solve_CG(r,s,this._randomizer),this.projection}}class Pr extends D{constructor(t,e){return super(t,{metric:q,seed:1212},e),[this._N,this._D]=this.X.shape,this._distance_matrix=new w(this._N,this._N,0),this}__lazy_distance_matrix(t,e,r){const s=this._distance_matrix,n=this.X,i=s.entry(t,e);if(i===0){let a=r(n.row(t),n.row(e));return s.set_entry(t,e,a),s.set_entry(e,t,a),a}return i}_make_minimum_spanning_tree(t=q){const e=this._N,r=[...this.X];let s=new K(r);const n=[];let i=[];for(let a=0;a<e;++a)for(let o=a+1;o<e;++o)i.push([a,o,this.__lazy_distance_matrix(a,o,t)]);i=i.sort((a,o)=>a[2]-o[2]);for(const[a,o,h]of i){const _=s.find(r[a]),c=s.find(r[o]);_!==c&&(n.push([a,o,h]),s.union(_,c))}return n.sort((a,o)=>a[2]-o[2])}init(){const{metric:t}=this._parameters;return this.Y=new w(this._N,2,0),this._Emst=this._make_minimum_spanning_tree(t),this._is_initialized=!0,this}__hull_cross([t,e],[r,s],[n,i]){return(r-t)*(i-e)-(s-e)*(n-t)<=0}__hull(t){const e=t.sort(([i,a],[o,h])=>a-h||i-o),r=e.length;if(r<=2)return e;const s=[];for(let i=0;i<r;++i){for(;s.length>=2&&this.__hull_cross(s[s.length-2],s[s.length-1],e[i]);)s.pop();s.push(e[i])}const n=[];for(let i=r-1;i>=0;--i){for(;n.length>=2&&this.__hull_cross(n[n.length-2],n[n.length-1],e[i]);)n.pop();n.push(e[i])}return n.pop(),s.pop(),s.concat(n)}__findAngle([t,e],[r,s]){const n=q([t,e],[r,s]);if(n===0)return{sin:0,cos:1};const i=[(r-t)/n,(s-e)/n],a=i[0];let o=Math.sqrt(1-a*a);return o=i[1]>=0?-o:o,{sin:o,cos:a}}__align_hull(t,e,r){let s,n,i,a=-1;for(let h=0;h<t.length;++h){const _=q(t[h],e);(a===-1||s>_)&&(s=_,a=h)}r?(n=t[a],i=t[(a+1)%t.length]):(a==0&&(a=t.length-1),n=t[a],i=t[(a-1)%t.length]);const o={tx:-t[a][0],ty:-t[a][1]};if(t.length>=2){const{sin:h,cos:_}=this.__findAngle(n,i);o.sin=h,o.cos=_}else o.sin=0,o.cos=1;return o}__transform([t,e],{tx:r,ty:s,sin:n,cos:i}){let a=t+r,o=e+s;return[a*i-o*n,a*n+o*i]}__transform_component(t,e,r){const s=t.length;for(let n=0;n<s;++n){const i=t[n],[a,o]=this.__transform(i,e);i[0]=a,i[1]=o+r}}__align_components(t,e,r){const s=[...t.__disjoint_set.children],n=[...e.__disjoint_set.children],i=this.__hull(s),a=this.__hull(n),o=this.__align_hull(i,t,!1),h=this.__align_hull(a,e,!0);this.__transform_component(s,o,0),this.__transform_component(n,h,r)}transform(){this._is_initialized||this.init();const t=this._Emst,e=this.Y.to2dArray,r=new K(e.map((s,n)=>(s.i=n,s)));for(const[s,n,i]of t){const a=r.find(e[s]),o=r.find(e[n]);a!==o&&(this.__align_components(a,o,i),r.union(a,o))}return this.projection}*generator(){this._is_initialized||this.init();const t=this._Emst,e=this.Y.to2dArray,r=new K(e.map((s,n)=>(s.i=n,s)));for(const[s,n,i]of t){const a=r.find(e[s]),o=r.find(e[n]);a!==o&&(this.__align_components(a,o,i),r.union(a,o),yield this.projection)}return this.projection}}class kr extends D{constructor(t,e){return super(t,{magic:.1,d:2,metric:q,seed:1212,init_DR:"random",init_parameters:{}},e),this}init(){const t=this.X.shape[0],{d:e,metric:r,init_DR:s,init_parameters:n}=this._parameters;if(s==="random"){const i=this._randomizer;this.Y=new w(t,e,()=>i.random)}else{if(!["PCA","MDS"].includes(s))throw new Error('init_DR needs to be either "random" or a DR method!');this.Y=w.from(s=="PCA"?J.transform(this.X,n):W.transform(this.X,n))}return this.distance_matrix=r=="precomputed"?w.from(this.X):F(this.X,r),this}transform(t=200){this._is_initialized||this.init();for(let e=0;e<t;++e)this._step();return this.projection}*generator(t=200){this._is_initialized||this.init();for(let e=0;e<t;++e)this._step(),yield this.projection;return this.projection}_step(){const t=this.parameter("magic"),e=this.distance_matrix,r=this.X.shape[0],{d:s,metric:n}=this._parameters;let i=this.Y,a=new w(r,s,0),o=new Float64Array(s);for(let h=0;h<r;++h){let _=new Float64Array(s),c=new Float64Array(s);const u=i.row(h);for(let f=0;f<r;++f){if(h===f)continue;const d=i.row(f),p=new Float64Array(s);for(let v=0;v<s;++v)p[v]=u[v]-d[v];const g=n(u,d),y=e.entry(h,f),m=y-g,b=Math.max(y*g,.01);for(let v=0;v<s;++v)_[v]+=p[v]*m/b,c[v]+=(m-Math.pow(p[v],2)*(1+m/g)/g)/b}for(let f=0;f<s;++f){const d=i.entry(h,f)+(t*_[f]/Math.abs(c[f])||0);a.set_entry(h,f,d),o[f]+=d}}for(let h=0;h<s;++h)o[h]/=r;for(let h=0;h<r;++h)for(let _=0;_<s;++_)i.set_entry(h,_,a.entry(h,_)-o[_]);return i}}class Fr extends D{constructor(t,e){return super(t,{d:2,metric:q,seed:1212,decay_start:.1,decay_cte:.34,init_DR:{type:"random"}},e),this}init(){const t=this._N,e=this.parameter("d");this._add=this.__add(e),this._sub_div=this.__sub_div(e),this._minus=this.__minus(e),this._mult=this.__mult(e),this._LR_init=Math.max(2,.005*t),this._LR=this._LR_init,this._offset=-Math.exp(-1/this.parameter("decay_cte")),this._momentums=new w(t,e,0),this._grads=new w(t,e,0),this._indices=z(0,t-1);const r=this._randomizer;this.Y=new w(t,e,()=>r.random-.5);const s=this.parameter("metric");s==="precomputed"?(this._HD_metric=function(n,i,a){return a.entry(n,i)},this._HD_metric_exaggeration=function(n,i,a){return Math.pow(a.entry(n,i),2)}):(this._HD_metric=function(n,i,a){return s(a.row(n),a.row(i))},this._HD_metric_exaggeration=s==q?function(n,i,a){return k(a.row(n),a.row(i))}:function(n,i,a){return Math.pow(s(a.row(n),a.row(i)),2)})}transform(t=500){this.check_init(),this._decay_start=Math.round(this.parameter("decay_start")*t);for(let e=0;e<t;++e)this._step(e,t);return this.projection}*generator(t=500){this.check_init(),this._decay_start=Math.round(this.parameter("decay_start")*t);for(let e=0;e<t;++e)this._step(e,t),yield this.projection;return this.projection}_step(t,e){const r=this._decay_start;if(t>r){const s=this.parameter("decay_cte"),n=this._offset,i=(t-r)/(e-r);this._LR=this._LR_init*(Math.exp(-i*i/s)+n),this._distance_exaggeration=!1}else this._distance_exaggeration=!0;this._nestrov_iteration(this._distance_exaggeration)}__quartets(){const t=this._N,e=t-t%4,r=this._randomizer.choice(this._indices,e),s=[];for(let n=0;n<e;n+=4)s.push(Uint32Array.of(r[n],r[n+1],r[n+2],r[n+3]));return s}_nestrov_iteration(t){const e=this._momentums.mult(.99,{inline:!0}),r=this._LR,s=this._fill_MDS_grads(this.Y.add(e),this._grads,t),[n,i]=e.shape;for(let a=0;a<n;++a){const o=s.row(a),h=I(o);if(h==0)continue;const _=r/h,c=e.row(a);for(let u=0;u<i;++u)c[u]-=_*o[u]}this.Y.add(e,{inline:!0})}_fill_MDS_grads(t,e,r=!1,s=!0){s&&e.values.fill(0);const n=this._add,i=this.X;let a;a=r==1?this._HD_metric_exaggeration:this._HD_metric;const o=new Float64Array(6),h=this.__quartets();for(const[_,c,u,f]of h){o[0]=a(_,c,i),o[1]=a(_,u,i),o[2]=a(_,f,i),o[3]=a(c,u,i),o[4]=a(c,f,i),o[5]=a(u,f,i);const d=R(o);if(d>0)for(let b=0;b<6;++b)o[b]/=d,o[b]+=1e-11;const[p,g,y,m]=this._compute_quartet_grads(t,[_,c,u,f],o);n(e.row(_),p),n(e.row(c),g),n(e.row(u),y),n(e.row(f),m)}return e}_compute_quartet_grads(t,e,[r,s,n,i,a,o]){const[h,_,c,u]=e.map(Bs=>t.row(Bs)),f=q(h,_)+1e-12,d=q(h,c)+1e-12,p=q(h,u)+1e-12,g=q(_,c)+1e-12,y=q(_,u)+1e-12,m=q(c,u)+1e-12,b=R([f,d,p,g,y,m]),[v,A,M,x]=this._ABCD_grads(h,_,c,u,f,d,p,g,y,m,r,b),[C,j,S,T]=this._ABCD_grads(h,c,_,u,d,f,p,g,m,y,s,b),[L,re,P,U]=this._ABCD_grads(h,u,c,_,p,d,f,m,y,g,n,b),[Es,Ts,Os,Ps]=this._ABCD_grads(_,c,h,u,g,f,y,d,m,p,i,b),[ks,Fs,Is,Ls]=this._ABCD_grads(_,u,h,c,y,f,g,p,m,d,a,b),[$s,Ks,Xs,Gs]=this._ABCD_grads(c,u,h,_,m,d,g,p,y,f,o,b),V=this._add;return[V(v,C,L,Os,Is,Xs),V(A,S,U,Es,ks,Gs),V(M,j,P,Ts,Ls,$s),V(x,T,re,Ps,Fs,Ks)]}_ABCD_grads(t,e,r,s,n,i,a,o,h,_,c,u){const f=n/u,d=(c-f)/u*2,p=this._minus,g=this._add,y=this._mult,m=this._sub_div;return[y(p(y(g(m(t,e,n),m(t,r,i),m(t,s,a)),f),m(t,e,n)),d),y(p(y(g(m(e,t,n),m(e,r,o),m(e,s,h)),f),m(e,t,n)),d),y(g(m(r,t,i),m(r,e,o),m(r,s,_)),f*d),y(g(m(s,t,a),m(s,e,h),m(s,r,_)),f*d)]}__minus(t){return(e,r)=>{for(let s=0;s<t;++s)e[s]-=r[s];return e}}__add(t){return(...e)=>{const r=e.length,s=e[0];for(let n=1;n<r;++n){const i=e[n];for(let a=0;a<t;++a)s[a]+=i[a]}return s}}__mult(t){return(e,r)=>{for(let s=0;s<t;++s)e[s]*=r;return e}}__sub_div(t){return(e,r,s)=>Float64Array.from({length:t},(n,i)=>(e[i]-r[i])/s)}}var Ir="0.6.3",le=Object.freeze({__proto__:null,BallTree:X,DisjointSet:K,FASTMAP:xr,Heap:E,Hierarchical_Clustering:Nr,ISOMAP:qr,KMeans:Er,KMedoids:he,KNN:ie,LDA:Cr,LLE:jr,LSP:Or,LTSA:Sr,MDS:W,Matrix:w,OPTICS:Tr,PCA:J,Randomizer:O,SAMMON:kr,SQDMDS:Fr,TSNE:Dr,TopoMap:Pr,TriMap:Rr,UMAP:zr,canberra:pr,chebyshev:dr,cosine:ur,distance_matrix:F,euclidean:q,euclidean_squared:k,hamming:gr,inner_product:Mr,jaccard:mr,k_nearest_neighbors:Q,kahan_sum:br,linspace:z,manhattan:fr,max:ne,min:$,neumair_sum:R,norm:I,normalize:vr,powell:ae,qr:se,qr_householder:Ar,simultaneous_poweriteration:N,sokal_michener:yr,version:Ir,yule:wr}),G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Lr(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var Z,_e;function tt(){if(_e)return Z;_e=1;var l=Array.isArray;return Z=l,Z}var et,ce;function $r(){if(ce)return et;ce=1;var l=typeof G=="object"&&G&&G.Object===Object&&G;return et=l,et}var rt,ue;function st(){if(ue)return rt;ue=1;var l=$r(),t=typeof self=="object"&&self&&self.Object===Object&&self,e=l||t||Function("return this")();return rt=e,rt}var nt,fe;function it(){if(fe)return nt;fe=1;var l=st(),t=l.Symbol;return nt=t,nt}var at,de;function Kr(){if(de)return at;de=1;var l=it(),t=Object.prototype,e=t.hasOwnProperty,r=t.toString,s=l?l.toStringTag:void 0;function n(i){var a=e.call(i,s),o=i[s];try{i[s]=void 0;var h=!0}catch{}var _=r.call(i);return h&&(a?i[s]=o:delete i[s]),_}return at=n,at}var ot,pe;function Xr(){if(pe)return ot;pe=1;var l=Object.prototype,t=l.toString;function e(r){return t.call(r)}return ot=e,ot}var ht,me;function ge(){if(me)return ht;me=1;var l=it(),t=Kr(),e=Xr(),r="[object Null]",s="[object Undefined]",n=l?l.toStringTag:void 0;function i(a){return a==null?a===void 0?s:r:n&&n in Object(a)?t(a):e(a)}return ht=i,ht}var lt,ye;function Gr(){if(ye)return lt;ye=1;function l(t){return t!=null&&typeof t=="object"}return lt=l,lt}var _t,we;function ct(){if(we)return _t;we=1;var l=ge(),t=Gr(),e="[object Symbol]";function r(s){return typeof s=="symbol"||t(s)&&l(s)==e}return _t=r,_t}var ut,ve;function Br(){if(ve)return ut;ve=1;var l=tt(),t=ct(),e=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function s(n,i){if(l(n))return!1;var a=typeof n;return a=="number"||a=="symbol"||a=="boolean"||n==null||t(n)?!0:r.test(n)||!e.test(n)||i!=null&&n in Object(i)}return ut=s,ut}var ft,be;function Ae(){if(be)return ft;be=1;function l(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}return ft=l,ft}var dt,Me;function Hr(){if(Me)return dt;Me=1;var l=ge(),t=Ae(),e="[object AsyncFunction]",r="[object Function]",s="[object GeneratorFunction]",n="[object Proxy]";function i(a){if(!t(a))return!1;var o=l(a);return o==r||o==s||o==e||o==n}return dt=i,dt}var pt,qe;function Yr(){if(qe)return pt;qe=1;var l=st(),t=l["__core-js_shared__"];return pt=t,pt}var mt,xe;function Ur(){if(xe)return mt;xe=1;var l=Yr(),t=function(){var r=/[^.]+$/.exec(l&&l.keys&&l.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function e(r){return!!t&&t in r}return mt=e,mt}var gt,Ce;function Vr(){if(Ce)return gt;Ce=1;var l=Function.prototype,t=l.toString;function e(r){if(r!=null){try{return t.call(r)}catch{}try{return r+""}catch{}}return""}return gt=e,gt}var yt,je;function Qr(){if(je)return yt;je=1;var l=Hr(),t=Ur(),e=Ae(),r=Vr(),s=/[\\^$.*+?()[\]{}|]/g,n=/^\[object .+?Constructor\]$/,i=Function.prototype,a=Object.prototype,o=i.toString,h=a.hasOwnProperty,_=RegExp("^"+o.call(h).replace(s,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function c(u){if(!e(u)||t(u))return!1;var f=l(u)?_:n;return f.test(r(u))}return yt=c,yt}var wt,Se;function Jr(){if(Se)return wt;Se=1;function l(t,e){return t==null?void 0:t[e]}return wt=l,wt}var vt,De;function ze(){if(De)return vt;De=1;var l=Qr(),t=Jr();function e(r,s){var n=t(r,s);return l(n)?n:void 0}return vt=e,vt}var bt,Re;function B(){if(Re)return bt;Re=1;var l=ze(),t=l(Object,"create");return bt=t,bt}var At,Ne;function Wr(){if(Ne)return At;Ne=1;var l=B();function t(){this.__data__=l?l(null):{},this.size=0}return At=t,At}var Mt,Ee;function Zr(){if(Ee)return Mt;Ee=1;function l(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}return Mt=l,Mt}var qt,Te;function ts(){if(Te)return qt;Te=1;var l=B(),t="__lodash_hash_undefined__",e=Object.prototype,r=e.hasOwnProperty;function s(n){var i=this.__data__;if(l){var a=i[n];return a===t?void 0:a}return r.call(i,n)?i[n]:void 0}return qt=s,qt}var xt,Oe;function es(){if(Oe)return xt;Oe=1;var l=B(),t=Object.prototype,e=t.hasOwnProperty;function r(s){var n=this.__data__;return l?n[s]!==void 0:e.call(n,s)}return xt=r,xt}var Ct,Pe;function rs(){if(Pe)return Ct;Pe=1;var l=B(),t="__lodash_hash_undefined__";function e(r,s){var n=this.__data__;return this.size+=this.has(r)?0:1,n[r]=l&&s===void 0?t:s,this}return Ct=e,Ct}var jt,ke;function ss(){if(ke)return jt;ke=1;var l=Wr(),t=Zr(),e=ts(),r=es(),s=rs();function n(i){var a=-1,o=i==null?0:i.length;for(this.clear();++a<o;){var h=i[a];this.set(h[0],h[1])}}return n.prototype.clear=l,n.prototype.delete=t,n.prototype.get=e,n.prototype.has=r,n.prototype.set=s,jt=n,jt}var St,Fe;function ns(){if(Fe)return St;Fe=1;function l(){this.__data__=[],this.size=0}return St=l,St}var Dt,Ie;function is(){if(Ie)return Dt;Ie=1;function l(t,e){return t===e||t!==t&&e!==e}return Dt=l,Dt}var zt,Le;function H(){if(Le)return zt;Le=1;var l=is();function t(e,r){for(var s=e.length;s--;)if(l(e[s][0],r))return s;return-1}return zt=t,zt}var Rt,$e;function as(){if($e)return Rt;$e=1;var l=H(),t=Array.prototype,e=t.splice;function r(s){var n=this.__data__,i=l(n,s);if(i<0)return!1;var a=n.length-1;return i==a?n.pop():e.call(n,i,1),--this.size,!0}return Rt=r,Rt}var Nt,Ke;function os(){if(Ke)return Nt;Ke=1;var l=H();function t(e){var r=this.__data__,s=l(r,e);return s<0?void 0:r[s][1]}return Nt=t,Nt}var Et,Xe;function hs(){if(Xe)return Et;Xe=1;var l=H();function t(e){return l(this.__data__,e)>-1}return Et=t,Et}var Tt,Ge;function ls(){if(Ge)return Tt;Ge=1;var l=H();function t(e,r){var s=this.__data__,n=l(s,e);return n<0?(++this.size,s.push([e,r])):s[n][1]=r,this}return Tt=t,Tt}var Ot,Be;function _s(){if(Be)return Ot;Be=1;var l=ns(),t=as(),e=os(),r=hs(),s=ls();function n(i){var a=-1,o=i==null?0:i.length;for(this.clear();++a<o;){var h=i[a];this.set(h[0],h[1])}}return n.prototype.clear=l,n.prototype.delete=t,n.prototype.get=e,n.prototype.has=r,n.prototype.set=s,Ot=n,Ot}var Pt,He;function cs(){if(He)return Pt;He=1;var l=ze(),t=st(),e=l(t,"Map");return Pt=e,Pt}var kt,Ye;function us(){if(Ye)return kt;Ye=1;var l=ss(),t=_s(),e=cs();function r(){this.size=0,this.__data__={hash:new l,map:new(e||t),string:new l}}return kt=r,kt}var Ft,Ue;function fs(){if(Ue)return Ft;Ue=1;function l(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}return Ft=l,Ft}var It,Ve;function Y(){if(Ve)return It;Ve=1;var l=fs();function t(e,r){var s=e.__data__;return l(r)?s[typeof r=="string"?"string":"hash"]:s.map}return It=t,It}var Lt,Qe;function ds(){if(Qe)return Lt;Qe=1;var l=Y();function t(e){var r=l(this,e).delete(e);return this.size-=r?1:0,r}return Lt=t,Lt}var $t,Je;function ps(){if(Je)return $t;Je=1;var l=Y();function t(e){return l(this,e).get(e)}return $t=t,$t}var Kt,We;function ms(){if(We)return Kt;We=1;var l=Y();function t(e){return l(this,e).has(e)}return Kt=t,Kt}var Xt,Ze;function gs(){if(Ze)return Xt;Ze=1;var l=Y();function t(e,r){var s=l(this,e),n=s.size;return s.set(e,r),this.size+=s.size==n?0:1,this}return Xt=t,Xt}var Gt,tr;function ys(){if(tr)return Gt;tr=1;var l=us(),t=ds(),e=ps(),r=ms(),s=gs();function n(i){var a=-1,o=i==null?0:i.length;for(this.clear();++a<o;){var h=i[a];this.set(h[0],h[1])}}return n.prototype.clear=l,n.prototype.delete=t,n.prototype.get=e,n.prototype.has=r,n.prototype.set=s,Gt=n,Gt}var Bt,er;function ws(){if(er)return Bt;er=1;var l=ys(),t="Expected a function";function e(r,s){if(typeof r!="function"||s!=null&&typeof s!="function")throw new TypeError(t);var n=function(){var i=arguments,a=s?s.apply(this,i):i[0],o=n.cache;if(o.has(a))return o.get(a);var h=r.apply(this,i);return n.cache=o.set(a,h)||o,h};return n.cache=new(e.Cache||l),n}return e.Cache=l,Bt=e,Bt}var Ht,rr;function vs(){if(rr)return Ht;rr=1;var l=ws(),t=500;function e(r){var s=l(r,function(i){return n.size===t&&n.clear(),i}),n=s.cache;return s}return Ht=e,Ht}var Yt,sr;function bs(){if(sr)return Yt;sr=1;var l=vs(),t=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,e=/\\(\\)?/g,r=l(function(s){var n=[];return s.charCodeAt(0)===46&&n.push(""),s.replace(t,function(i,a,o,h){n.push(o?h.replace(e,"$1"):a||i)}),n});return Yt=r,Yt}var Ut,nr;function As(){if(nr)return Ut;nr=1;function l(t,e){for(var r=-1,s=t==null?0:t.length,n=Array(s);++r<s;)n[r]=e(t[r],r,t);return n}return Ut=l,Ut}var Vt,ir;function Ms(){if(ir)return Vt;ir=1;var l=it(),t=As(),e=tt(),r=ct(),s=l?l.prototype:void 0,n=s?s.toString:void 0;function i(a){if(typeof a=="string")return a;if(e(a))return t(a,i)+"";if(r(a))return n?n.call(a):"";var o=a+"";return o=="0"&&1/a==-1/0?"-0":o}return Vt=i,Vt}var Qt,ar;function qs(){if(ar)return Qt;ar=1;var l=Ms();function t(e){return e==null?"":l(e)}return Qt=t,Qt}var Jt,or;function xs(){if(or)return Jt;or=1;var l=tt(),t=Br(),e=bs(),r=qs();function s(n,i){return l(n)?n:t(n,i)?[n]:e(r(n))}return Jt=s,Jt}var Wt,hr;function Cs(){if(hr)return Wt;hr=1;var l=ct();function t(e){if(typeof e=="string"||l(e))return e;var r=e+"";return r=="0"&&1/e==-1/0?"-0":r}return Wt=t,Wt}var Zt,lr;function js(){if(lr)return Zt;lr=1;var l=xs(),t=Cs();function e(r,s){s=l(s,r);for(var n=0,i=s.length;r!=null&&n<i;)r=r[t(s[n++])];return n&&n==i?r:void 0}return Zt=e,Zt}var te,_r;function Ss(){if(_r)return te;_r=1;var l=js();function t(e,r,s){var n=e==null?void 0:l(e,r);return n===void 0?s:n}return te=t,te}var Ds=Ss(),zs=Lr(Ds);const Rs=200,cr="UMAP";function Ns(l){return Array.isArray(l)?Array.isArray(l[0])?"multivector":"vector":typeof l=="object"?l.indices?"sparse":"named":"unknown"}self.onmessage=function(l){var a,o,h,_,c;let t=new Date().getTime();const e=((a=l==null?void 0:l.data)==null?void 0:a.params)||{},r=e.algorithm||cr,s=[],n=(h=(o=l.data)==null?void 0:o.result)==null?void 0:h.points,i=e.using;if(!n||n.length===0){self.postMessage({data:[],error:"No data found"});return}if(n.length===1){self.postMessage({data:[],error:`cannot perform ${e.algorithm||cr} on single point`});return}for(let u=0;u<n.length;u++)i?s.push(zs((c=n[u])==null?void 0:c.vector,i)):s.push((_=n[u])==null?void 0:_.vector);for(let u=0;u<s.length;u++){const f=s[u],d=Ns(f);if(d!=="vector"){if(d==="named"){self.postMessage({data:[],error:"Please select a valid vector name (by `using`), default vector is not defined"});return}self.postMessage({data:[],error:"Vector visualization is not supported for vector type: "+d});return}}if(s.length)if(r==="PCA"){const f=new le[r](s,{}).transform();self.postMessage({result:ee(f),error:null})}else{const f=new le[r](s,{}).generator();let d=[];for(d of f)Date.now()-t>Rs&&(t=Date.now(),self.postMessage({result:ee(d),error:null}));self.postMessage({result:ee(d),error:null})}};function ee(l){return l.map(t=>({x:t[0],y:t[1]}))}})();