(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({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=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=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;nc*i[u]));for(let c=0;c2*(i.random-.5)));for(;r--;){const _=o,c=s(l.dot(o));if(o=c.Q,h=c.R,k(o.values,_.values)(s===n?1:0)-1/t;for(let s=0;st[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;sthis.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{const h=e.row(a),_=t.values;let c=0;for(let u=0,f=o;un*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;un*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;un*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;it[s])}_apply_colwise_array(t,e){const r=this.values,[s,n]=this.shape;for(let i=0,a=0;ar*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;nr.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=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;nMath.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>>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>>1^e[1&t];for(;r>>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;it.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;it[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=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)=>ss>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";n0?this._container[0]:null}*iterate(){for(let t=0,e=this._container.length;tthis._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({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{for(let o=0;oi[1]-i[0]);let n=0;for(let i=0;is[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;nr.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;sa.value,"min");for(let a=0;an.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)=>ag<=y?s(t.row(g),t.row(y)):a.entry(y,g)];const o=[];for(let g=0;gb.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{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;in&&(n=a,s=i)}n=-1/0;for(let i=0;in&&(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;aMath.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;gp[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;my[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;dt.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;vb.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;b1e-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;h0?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=0&&!o;){o=!0;for(let h=0;h.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{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;s0?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;px.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;j0?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{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;ac*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;e4?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;y0){const j=-2*h*_*Math.pow(x,_-1)/(h*Math.pow(x,_)+1);for(let S=0;S0){const re=2*i*_/((.01+L)*(h*Math.pow(L,_)+1));for(let P=0;PA.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;v0){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;vMath.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;at[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=g){u=1,f=1;for(let M=0;Mf&&++d,p+=n[y]/(1+f/u);const A=(n[y]/(u+f))**2;for(let M=0;M150?.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;_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;on.entry(o,h)&&(s[o]=h)}}else{n=this._matrix.clone();for(let o=0;on.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;or.entry(m,v)&&(e[m]=v,b=r.entry(m,e[m]))}for(let m=0;mi&&(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;ho.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_/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&&++rthis._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[c,u]).filter(([c,u])=>c{c=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&&++no.findIndex(d=>d===f)<0),i);for(let f=0;fthis._get_distance(m,A,b)));v<0&&(d+=v)}dh.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)o.element==i)<0?(i.reachability_distance=a,e.push(i)):ao.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{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;aa[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=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_)&&(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.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;er.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;er){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;n0)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{const r=e.length,s=e[0];for(let n=1;n{for(let s=0;sFloat64Array.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-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();++aRs&&(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]}))}})();