chromosomix 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ const Vn="HDF5::MetaCooler";const Mi="HDF5::MMetaCooler",uo="HDF5::Cooler",ln="HDF5::SCOOL";const Un="cells",ho=["bins","pixels","indexes"];const zo=["symmetric-upper","square"],Sn="genome-then-length",ke="__unbinned__",ic=["","null","none","nan"];function V(e){if(e==null)return"None";if(typeof e=="boolean")return e?"True":"False";if(typeof e=="number")return Number.isInteger(e),String(e);if(Array.isArray(e))return`[${e.map(V).join(", ")}]`;if(typeof e!="string")return String(e);const t=e.includes("'")&&!e.includes('"')?'"':"'",n=e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(new RegExp(t,"g"),`\\${t}`);return`${t}${n}${t}`}function Dt(e){return`[${e.map(V).join(", ")}]`}function xi(e){const t=e.trim();if(!/^[+-]?[0-9](?:_?[0-9])*$/.test(t))return null;const n=Number(t.replace(/_/g,""));return Number.isFinite(n)?n:null}class C extends Error{code;detail;constructor(t,n,s={}){super(n),this.name="ViewerError",this.code=t,this.detail=s}}class st extends C{constructor(t,n={},s="format"){super(s,t,n),this.name="MetaCoolerFormatError"}}function _e(e,t=20){return e.length<=t?Dt(e):`${Dt(e.slice(0,t))} ... (${e.length-t} more)`}let Ve=null;function Re(){const e=globalThis;return typeof e.window<"u"?!1:typeof e.process<"u"&&e.process?.versions?.node!=null}function ae(){return Ve||(Ve=ac().catch(e=>{throw Ve=null,new C("not-hdf5",`Could not initialise the HDF5 (h5wasm) runtime: ${cc(e)}`,{runtime:Re()?"node":"browser"})}),Ve)}async function ac(){let e;return Re()?e=await import("h5wasm/node"):e=await import("./hdf5_hl-8FoHa7pu.js"),await e.ready,{File:e.File,Group:e.Group,Dataset:e.Dataset,FS:e.FS,Module:e.Module}}function cc(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}const ws=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),lc=new Intl.NumberFormat(void 0,{maximumFractionDigits:3}),uc=new Intl.NumberFormat(void 0,{maximumSignificantDigits:3}),Ro=new Map,hc=new Intl.NumberFormat("en-US",{maximumFractionDigits:0}),At={int(e){return Number.isFinite(e)?ws.format(e):"—"},num(e){if(!Number.isFinite(e))return"—";if(Number.isInteger(e))return ws.format(e);const t=Math.abs(e);return t>=.001?lc.format(e):t>=1e-7?uc.format(e):e.toExponential(2)},fixed(e,t){if(!Number.isFinite(e))return"—";let n=Ro.get(t);return n===void 0&&(n=new Intl.NumberFormat(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}),Ro.set(t,n)),n.format(e)},pct(e,t=1){return Number.isFinite(e)?`${(e*100).toFixed(t)}%`:"—"},pos(e){return Number.isFinite(e)?hc.format(Math.round(e)):"—"},bp(e){return Number.isFinite(e)?Math.abs(e)>=1e6?`${(e/1e6).toFixed(2)} Mb`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)} kb`:`${ws.format(e)} bp`:"—"},bytes(e){if(!Number.isFinite(e))return"—";const t=["B","kB","MB","GB","TB"];let n=e,s=0;for(;n>=1e3&&s<t.length-1;)n/=1e3,s++;return`${s===0?n:n.toFixed(1)} ${t[s]}`}};function fc(e){return!Number.isFinite(e)||e<=0?"—":e>=1e6?`${ps(e/1e6)} Mb`:e>=1e3?`${ps(e/1e3)} kb`:`${ps(e)} bp`}function ps(e){return String(Number(e.toFixed(2)))}function St(){return typeof MessageChannel>"u"?new Promise(e=>{setTimeout(e,0)}):new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e()},t.port2.postMessage(void 0)})}const Ke=256,dc=["#FFFEF9","#FCF9CE","#FFF2A9","#FDE188","#FFCA67","#FAAA4B","#F78E40","#F15C34","#ED3024","#D42027","#B01F29","#7A1128","#1A0A10"],mc=["#FFFFFF","#FFF5F0","#FEE0D2","#FCBBA1","#FC9272","#FB6A4A","#EF3B2C","#CB181D","#A50F15","#67000D"],gc=["#053061","#2166AC","#4393C3","#92C5DE","#D1E5F0","#F7F7F7","#FDDBC7","#F4A582","#D6604D","#B2182B","#67001F"],wc=["#1659b1","#487BA8","#819EC8","#D1E6F1","#FFFFFF","#FAC1C1","#F1606C","#EE222A"],pc=[0,.125,.25,.375,.5,2/3,5/6,1],bc=["#00004D","#0000FF","#FFFFFF","#FF0000","#800000"];function Xe(e,t,n){const s=e.map(a=>[Number.parseInt(a.slice(1,3),16),Number.parseInt(a.slice(3,5),16),Number.parseInt(a.slice(5,7),16)]),o=s.length-1,r=n??s.map((a,c)=>c/o),i=new Array(t*3);for(let a=0;a<t;a++){const c=a/(t-1);let l=0;for(;l<o-1&&c>=r[l+1];)l++;const u=r[l+1]-r[l],h=u>0?(c-r[l])/u:0;for(let f=0;f<3;f++)i[a*3+f]=Math.round(s[l][f]+(s[l+1][f]-s[l][f])*h)}return i}Xe(dc,Ke),Xe(mc,Ke),Xe(gc,Ke),Xe(wc,Ke,pc),Xe(bc,Ke);const yc=["exact","case","decorated","prefix","padded","roman","organelle","accession","version"],Po=new Set(["gi","gb","ref","emb","dbj","tpg","tpe","tpd","lcl","pir","prf","sp","tr","pdb","ena","bbs"]);function fo(e){let t=e.trim().split(/\s+/)[0]??"";if(t=t.replace(/[,;]+$/,""),t.includes("|")){const n=t.split("|").filter(s=>s!=="");if(n.some(s=>Po.has(s.toLowerCase()))){const s=n.filter((o,r)=>Po.has(o.toLowerCase())?!1:!(/^[0-9]+$/.test(o)&&r>0&&n[r-1].toLowerCase()==="gi"));s.length>0&&(t=s[s.length-1])}}return t}const Si=/^(?:chromosome|chrom|chr)[ _.-]?/i;function Ii(e){const t=e.replace(Si,"");if(t===""||t===e)return null;const n=t.toLowerCase();return/^[0-9]/.test(t)||Xn.has(n)||Kn.has(n)||cs(t)>0||/^un[_.-]/i.test(t)||/^[A-Za-z]{1,2}[0-9]/.test(t)||vi.test(t)||Ci.test(t.replace(/\.[0-9]+$/,""))?t:null}const Ac=/^(?:lg|linkage_?group|group)[ _.-]?(?=[0-9])/i,Ei=/_(random|alt|fix|hap\d+|maternal|paternal)$/i,Mc=/(?:^|[_.-])([A-Z]{2}[0-9]{5,6})v([0-9]+)(?:$|[_.-])/,vi=/^(N[CGTWZ]|AC)_([0-9]{5,})$/i,Ci=/^[A-Z]{1,6}[0-9]{5,8}$/,xc=[["mito",["m","mt","mtdna","mito","mitochondrion","mitochondria","mitochondrial","mitochondrion_genome","dmel_mitochondrion_genome","mitochondrial_genome","mitochondrion_dna","chrmt","nc_012920","j01415","nc_001224","nc_005089"]],["plastid",["c","pt","cp","chloroplast","plastid","chloroplast_genome","chrc","nc_000932"]],["2micron",["2-micron","2micron","2u","2-micron_plasmid","nc_001398"]]],Kn=new Map;for(const[e,t]of xc)for(const n of t)Kn.set(n,e);const Xn=new Set(["x","y","z","w"]),Sc=/^(XL|L|X{0,3})(IX|IV|V?I{0,3})$/i,Ic={"":0,x:10,xx:20,xxx:30,xl:40,l:50},Ec={"":0,i:1,ii:2,iii:3,iv:4,v:5,vi:6,vii:7,viii:8,ix:9};function cs(e){const t=Sc.exec(e);if(t===null)return 0;const n=Ic[t[1].toLowerCase()],s=Ec[t[2].toLowerCase()];return n===void 0||s===void 0?0:n+s}const vc=[{from:1,to:22,first:1,tail:["x","y"]},{from:67,to:85,first:1,tail:["x","y"]}];function Cc(e){for(const t of vc){if(e>=t.from&&e<=t.to)return String(t.first+(e-t.from));const n=e-t.to-1;if(n>=0&&n<t.tail.length)return t.tail[n]}return null}const Hs=200;function $c(e){return e.length<2||Xn.has(e.toLowerCase())?!1:cs(e)>0}function $i(e){const t=e.map(c=>Ni(c)),s=t.filter(c=>$c(c)).length>=2,o=t.filter(c=>/^[0-9]+$/.test(c)&&Number(c)>=1&&Number(c)<=Hs),r=o.length<Hs,i=c=>t.some(l=>l.toLowerCase()===c),a=r&&o.length>=2;return{roman:s,ordinals:r,xIsTen:s&&!a&&(i("ix")||i("xi"))}}function Ni(e){const t=fo(e);return(Ii(t)??t).replace(Ei,"")}function Gn(e,t){const n=[],s=fo(e);s!==e.trim()&&n.push("decorated");const o=Ii(s),r=o??s;o!==null&&n.push("prefix");const i=Ei.exec(r),a=i===null?r:r.slice(0,i.index),c=i===null?"":`+${i[1].toLowerCase()}`,l=a.toLowerCase(),u=Mc.exec(r);if(u!==null)return n.push("accession"),{key:`acc:${u[1].toLowerCase()}`,via:n,version:u[2],opaque:!1};const h=/^(.*?)\.([0-9]+)$/.exec(a),f=h===null?a:h[1],d=h===null?null:h[2],m=Kn.get(l)??Kn.get(f.toLowerCase());if(m!==void 0)return m!==l&&n.push("organelle"),{key:`org:${m}`,via:n,version:d,opaque:!1};const g=vi.exec(f);if(g!==null){n.push("accession");const b=g[1].toLowerCase()==="nc"?Cc(Number(g[2])):null;return b!==null?{key:Xn.has(b)?`sex:${b}${c}`:`num:${b}${c}`,via:n,version:d,opaque:!1}:{key:`acc:${f.toLowerCase()}${c}`,via:n,version:d,opaque:!1}}if(Ci.test(f))return n.push("accession"),{key:`acc:${f.toLowerCase()}${c}`,via:n,version:d,opaque:!1};if(/^[0-9]+$/.test(a)&&t.ordinals&&Number(a)<=Hs)return/^0[0-9]/.test(a)&&n.push("padded"),{key:`num:${Number(a)}${c}`,via:n,version:null,opaque:!1};const w=/^([0-9]{1,2})([a-z]{1,2})$/i.exec(a);if(w!==null&&t.ordinals)return w[1].startsWith("0")&&n.push("padded"),{key:`num:${Number(w[1])}${w[2].toLowerCase()}${c}`,via:n,version:null,opaque:!1};const p=Ac.exec(a);if(p!==null){const b=a.slice(p[0].length);if(/^[0-9]+$/.test(b))return/^0[0-9]/.test(b)&&n.push("padded"),{key:`lg:${Number(b)}${c}`,via:n,version:null,opaque:!1}}if(Xn.has(l)&&!(l==="x"&&t.xIsTen))return{key:`sex:${l}${c}`,via:n,version:null,opaque:!1};if(t.roman){const b=cs(a);if(b>0)return n.push("roman"),{key:`num:${b}${c}`,via:n,version:null,opaque:!1}}return{key:`raw:${l}${c}`,via:n,version:null,opaque:!0}}function Zn(e){return yc.indexOf(e)}function Nc(e,t){let n="case";for(const s of[...e.via,...t.via])Zn(s)>Zn(n)&&(n=s);return n}function bs(e,t){return e===void 0||t===void 0||e<=0||t<=0?"unknown":e===t?"agree":"differ"}const Lo=new WeakMap;class ie{names;context;styleCache=null;get style(){return this.styleCache??=Oc(this.names,this.context),this.styleCache}exact=new Map;folded=new Map;keyed=new Map;constructor(t){this.names=t.map(n=>n.name),this.context=$i(this.names);for(const n of t){this.exact.has(n.name)||this.exact.set(n.name,n),Do(this.folded,n.name.toLowerCase(),n);const s=Gn(n.name,this.context);Do(this.keyed,s.key,{sequence:n,canon:s})}}static of(t){return new ie(t)}static ofNames(t){return new ie(t.map(n=>({name:n})))}static for(t){const n=Lo.get(t);if(n!==void 0)return n;const s=typeof t[0]=="string"?ie.ofNames(t):ie.of(t);return Lo.set(t,s),s}has(t){return this.exact.has(t)}find(t,n={}){const{length:s}=n,o=this.exact.get(t);if(o!==void 0)return{name:o.name,asked:t,tier:"exact",lengths:bs(s,o.length)};const r=this.folded.get(t.toLowerCase());if(r!==void 0&&r.length===1)return{name:r[0].name,asked:t,tier:"case",lengths:bs(s,r[0].length)};const i=n.from??this.context,a=this.byKey(t,Gn(t,i),s);if(a!==null)return a;if(!i.roman){const c=Ni(t).toLowerCase();if(c!=="x"&&c!=="l"&&cs(c)>0)return this.byKey(t,Gn(t,{...i,roman:!0,xIsTen:!1}),s)}return null}byKey(t,n,s){const o=this.keyed.get(n.key);if(o===void 0||o.length===0)return null;const r=Bc(o,s);if(r===null)return null;const i=Nc(n,r.canon),a=n.version!==null&&r.canon.version!==null&&n.version!==r.canon.version;return{name:r.sequence.name,asked:t,tier:a&&Zn(i)<Zn("version")?"version":i,lengths:bs(s,r.sequence.length)}}}function Bc(e,t){if(e.length===1)return e[0];if(t===void 0||t<=0)return null;const n=e.filter(s=>s.sequence.length===t);return n.length===1?n[0]:null}function Do(e,t,n){const s=e.get(t);s===void 0?e.set(t,[n]):s.push(n)}function Oc(e,t=$i(e)){if(e.length===0)return"empty";let n=0,s=0,o=0,r=0;for(const a of e){const c=Gn(a,t);if(c.opaque){r++;continue}c.via.includes("accession")?o++:Si.test(fo(a))?n++:s++}const i=n+s+o;return i===0||r>i*4?"assembly":t.roman&&n<=s?"roman":o>n&&o>s?"accession":n>0&&s>0?"mixed":n>0?t.roman?"roman":"ucsc":t.roman?"roman":"ensembl"}function kc(e,t){const n=_c(e),s=n.get(t);if(s!==void 0)return s;const o=ie.for(e).find(t);return o===null?-1:n.get(o.name)??-1}const Uo=new WeakMap;function _c(e){const t=Uo.get(e);if(t!==void 0)return t;const n=new Map;return e.forEach((s,o)=>{const r=typeof s=="string"?s:s.name;n.has(r)||n.set(r,o)}),Uo.set(e,n),n}function Jn(e){return e.strand??1}function Hn(e,t){const n=(t-e.unitStart)*e.bpPerUnit;return Jn(e)===1?e.bpStart+n:e.bpStart-n}function qs(e,t){const n=(Jn(e)===1?t-e.bpStart:e.bpStart-t)/e.bpPerUnit;return e.unitStart+n}function Ze(e){return[e.bpFrom??0,e.bpTo??e.contigLength]}class Tc{segments;byContig=new Map;names;spelled=new Map;constructor(t){this.segments=t;for(const n of t)this.byContig.has(n.contig)||this.byContig.set(n.contig,n);this.names=[...this.byContig.keys()]}ownName(t){if(this.byContig.has(t))return t;const n=this.spelled.get(t);if(n!==void 0)return n;const s=kc(this.names,t),o=s<0?null:this.names[s];return this.spelled.set(t,o),o}get length(){return this.segments.length}contigs(){return this.segments.map(t=>t.contig)}get unitEnd(){return this.segments.length===0?0:this.segments[this.segments.length-1].unitEnd}get uniformBpPerUnit(){if(this.segments.length===0)return null;const t=this.segments[0].bpPerUnit;return this.segments.every(n=>n.bpPerUnit===t)?t:null}segmentOf(t){const n=this.ownName(t);return n===null?null:this.byContig.get(n)??null}segmentsOf(t){const n=this.ownName(t);return n===null?[]:this.segments.filter(s=>s.contig===n)}like(t){let n=null;for(const s of this.segments)if(s.contig===t.contig){if(s.bpStart===t.bpStart&&Jn(s)===Jn(t))return s;n===null&&(n=s)}return n}segmentAt(t){let n=0,s=this.segments.length-1;for(;n<=s;){const o=n+s>>1,r=this.segments[o];if(t<r.unitStart)s=o-1;else if(t>=r.unitEnd)n=o+1;else return r}return null}unitToLocus(t){const n=this.segmentAt(t);if(n===null)return null;const[s,o]=Ze(n);return{contig:n.contig,bp:Fc(Hn(n,t),s,o)}}locusToUnit(t,n){const s=this.ownName(t);if(s===null)return null;const o=this.holding(s,n)??this.byContig.get(s);return o===void 0||o.bpPerUnit<=0?null:qs(o,n)}holding(t,n){for(const s of this.segments){if(s.contig!==t)continue;const[o,r]=Ze(s);if(n>=o&&n<=r)return s}}locusToUnits(t,n){const s=[],o=this.ownName(t);if(o===null)return s;for(const r of this.segments){if(r.contig!==o||!(r.bpPerUnit>0))continue;const[i,a]=Ze(r);if(n<i||n>a)continue;const c=qs(r,n);c>=r.unitStart-.5&&c<=r.unitEnd+.5&&s.push(c)}return s}windows(t,n=0){const s=[],[o,r]=t;for(const i of this.segments){const a=Math.max(i.unitStart,o),c=Math.min(i.unitEnd,r);if(!(c>a))continue;const l=Hn(i,a),u=Hn(i,c),h=Math.min(l,u),f=Math.max(l,u),d=(f-h)*n,[m,g]=Ze(i);s.push({contig:i.contig,start:Math.max(m,Math.floor(h-d)),end:Math.min(g,Math.ceil(f+d)),unitFrom:a,unitTo:c,segment:i})}return s}fullWindows(){return this.segments.map(t=>{const[n,s]=Ze(t);return{contig:t.contig,start:n,end:s,unitFrom:t.unitStart,unitTo:t.unitEnd,segment:t}})}}function Fc(e,t,n){return e<t?t:e>n?n:e}const Bi=16384;function Go(e,t=Bi){return e<=t?1:Math.ceil(e/t)}const zc="bhilnpq",Rc="BHILNPQu",Pc="defg";function Oi(e){const t=e.trim(),n=()=>{throw new st(`cannot interpret the HDF5 dtype ${JSON.stringify(e)} as a numpy kind`,{dtype:e})};t===""&&n();const s="<>|=".includes(t[0])?t[0]:"",o=s===""?t:t.slice(1);o===""&&n();const r=o[0],i=o.slice(1);switch(i!==""&&!/^\d+$/.test(i)&&n(),r){case"A":case"S":return i===""?"O":"S";case"U":return"U";case"O":return"O";case"?":return"b";case"b":return s==="|"?"b":"i";default:return zc.includes(r)?"i":Rc.includes(r)?"u":Pc.includes(r)?"f":n()}}const Ws=new Uint8Array(new Uint32Array([1]).buffer)[0]===1?0:1;function js(e){const t=new Float64Array(e.length);if(e instanceof BigInt64Array||e instanceof BigUint64Array){const n=e.length,s=new Uint32Array(e.buffer,e.byteOffset,n*2),o=e instanceof BigInt64Array?new Int32Array(e.buffer,e.byteOffset,n*2):s,r=Ws,i=1-Ws;for(let a=0;a<n;a++)t[a]=o[2*a+i]*4294967296+s[2*a+r];return t}return t.set(e),t}function ki(e){const t=e.length,n=new Int32Array(e.buffer,e.byteOffset,t*2),s=new Int32Array(t),o=Ws;for(let r=0;r<t;r++)s[r]=n[2*r+o];return s}const Ne="weight",ee="count",Lc=new Set(["bin1_id","bin2_id"]);function Dc(e){const t=e.keys("pixels").filter(n=>!Lc.has(n));return[...t.filter(n=>n===ee),...t.filter(n=>n!==ee).sort()]}const un={range:"Use a narrower --range/--range2.",binSelection:"Use --range to select a smaller region, or --level contig."};function Uc(e,t,n){if(e*t>5e4**2){const s=e*t*8/1e9;throw new C("dense-too-large",`Refusing to allocate a ${e}×${t} dense matrix (${s.toFixed(1)} GB). ${n}`,{nRows:e,nCols:t,limit:5e4})}}function Gc(e,t){const n=e*t,s=Math.ceil(e/Go(e))*Math.ceil(t/Go(t));return n*4+s*12+_i}function wn(){const e=globalThis.navigator?.deviceMemory;return qc(typeof e=="number"&&e>0?e:8)}function Hc(e=wn()){const t=Math.floor(Math.sqrt(Math.max(0,e-_i)/16));return Math.max(1,Math.min(Bi,t))}function qc(e){const t=e*1073741824*.75;return e>=2?Math.max(1e9,t):t}function Wc(e,t,n,s={}){const o=e*t;if(o*4>=2147483648){const a=Math.floor(Math.sqrt(536870912));throw new C("dense-too-large",`Refusing to load a ${e}×${t} block: its ${Qs(o)} values are ${At.bytes(o*4)} and a browser serves at most ${At.bytes(2147483648)} in a single array — a limit of the tab, not of this machine, so more memory and more patience will not lift it. The largest square block is about ${a}×${a} bins.`+(n===""?"":` ${n}`),{nRows:e,nCols:t,cells:o,bytes:o*4,limit:2147483648,where:"array-limit"})}const r=s.budgetBytes??wn(),i=Gc(e,t);if(!(i<=r))throw new C("dense-too-large",`Refusing to load a ${e}×${t} block in a browser tab: ${Qs(o)} cells needs about ${At.bytes(i)}, and this tab is budgeting ${At.bytes(r)}. ${n}`,{nRows:e,nCols:t,cells:o,bytes:i,budget:r,where:"browser"})}function Qs(e){return e>=1e9?`${(e/1e9).toFixed(1)} billion`:e>=1e6?`${(e/1e6).toFixed(0)} million`:String(e)}function Ho(e){const t=Oi(e);if(t==="i"||t==="u"||t==="f")return t;throw new C("format",`/pixels/count is stored as ${e} (kind '${t}'); expected one of the kinds ['i', 'u', 'f']. A non-numeric count column cannot be rendered.`,{dtype:e,kind:t})}const ls=1e6,_i=ls*36;class mo{constructor(t,n){this.offsets=t,this.firstBin=n}row=0;bin1(t,n){const s=new Int32Array(Math.max(0,n-t)),o=this.offsets,r=o.length-2;if(r<0)return s;t<o[this.row]&&this.seek(t);let i=this.row;for(let a=t;a<n;){for(;i<r&&o[i+1]<=a;)i++;const c=i<r?Math.min(n,o[i+1]):n,l=c>a?c:n;s.fill(this.firstBin+i,a-t,l-t),a=l}return this.row=i,s}seek(t){const n=this.offsets;let s=0,o=Math.max(0,n.length-2);for(;s<o;){const r=s+o+1>>1;n[r]<=t?s=r:o=r-1}this.row=s}}function jc(e,t,n){if(n<=t)return null;const s=e.readNumeric("indexes/bin1_offset",t,n+1),o=s[0],r=s[s.length-1];return r<=o?null:{p0:o,p1:r,rows:new mo(s,t)}}function go(e,t,n,s=ee,o=null){const r=e.readInt32("pixels/bin2_id",t,n),i=e.readNumeric(`pixels/${s}`,t,n);return{bin1:o===null?e.readInt32("pixels/bin1_id",t,n):o.bin1(t,t+i.length),bin2:r,count:i,length:i.length}}async function Qc(e,t,n,s,o={}){const r=jc(e,t,n);if(r===null)return!0;const{p0:i,p1:a,rows:c}=r,l=Math.max(1,Math.trunc(o.chunkSize??ls)),u=a-i,h=o.value??ee;for(let f=i;f<a;f+=l){if(o.cancelled?.()===!0)return!1;const d=Math.min(f+l,a);s(go(e,f,d,h,c)),o.onProgress?.(d-i,u),await St()}return!0}const Ti=65536;async function Yc(e,t,n,s={},o=null){const r=Math.max(1,Math.trunc(s.chunkSize??ls)),i=t.reduce((u,[h,f])=>u+Math.max(0,f-h),0),a=s.value??ee,c=o===null?null:new mo(o,0);let l=0;for(const[u,h]of t){c?.seek(u);for(let f=u;f<h;f+=r){if(s.cancelled?.()===!0)return!1;const d=Math.min(f+r,h);n(go(e,f,d,a,c)),l+=d-f,s.onProgress?.(l,i),await St()}}return!0}function Te(e,t,n){return n!=="symmetric-upper"?{span:e,mode:"direct"}:t[1]<=e[0]?{span:t,mode:"transpose"}:e[1]<=t[0]?{span:e,mode:"direct"}:{span:[Math.min(e[0],t[0]),Math.min(e[1],t[1])],mode:"symmetric"}}function Vc(e,t,n,s,o){const[r,i]=t,[a,c]=n,l=c-a,{bin1:u,bin2:h,count:f,length:d}=e,m=s.mode!=="transpose",g=s.mode!=="direct",w=s.mode==="symmetric";for(let p=0;p<d;p++){const b=u[p],y=h[p],A=f[p];m&&b>=r&&b<i&&y>=a&&y<c&&(o[(b-r)*l+(y-a)]+=A),g&&!(w&&b===y)&&y>=r&&y<i&&b>=a&&b<c&&(o[(y-r)*l+(b-a)]+=A)}}async function Kc(e,t,n){const s=qo(t.rows,e.nBins,"rows"),o=qo(t.cols??t.rows,e.nBins,"cols"),r=s[1]-s[0],i=o[1]-o[0];Uc(r,i,n),Wc(r,i,n,{...t.budgetBytes===void 0?{}:{budgetBytes:t.budgetBytes}});const a=Xc(r,i,n);if(r>0&&i>0){const c=Te(s,o,e.storageMode);await e.store.forEachWindow(s,o,c,l=>{Vc(l,s,o,c,a)},{chunkSize:ls,value:t.value??ee}),t.balance===!0&&Zc(e.handle,s,o,a)}return{nrows:r,ncols:i,values:a,rowExtent:s,colExtent:o}}function Xc(e,t,n){try{return new Float32Array(e*t)}catch(s){const o=e*t;throw new C("dense-too-large",`This machine could not allocate the ${e}×${t} block: ${Qs(o)} cells is ${At.bytes(o*4)} in one array, and the request was refused. ${n}`,{nRows:e,nCols:t,cells:o,bytes:o*4,where:"allocation",cause:String(s)})}}function Zc(e,t,n,s){const o=Ne,r=`bins/${o}`;if(!e.has(r))throw new C("unsupported",`This file has no /bins/${o} column, so there are no weights to balance with. Run \`cooler balance\` on it, or view the raw counts.`,{column:o});const i=e.readNumeric(r,t[0],t[1]),a=n[0]===t[0]&&n[1]===t[1]?i:e.readNumeric(r,n[0],n[1]),c=n[1]-n[0];for(let l=0;l<t[1]-t[0];l++){const u=i[l],h=l*c;for(let f=0;f<c;f++)s[h+f]=s[h+f]*u*a[f]}}function qo(e,t,n){const[s,o]=e;if(!Number.isInteger(s)||!Number.isInteger(o)||s<0||o<s||o>t)throw new C("bad-range",`Bin range for ${n} is [${s}, ${o}); it must be a half-open integer interval inside [0, ${t}).`,{extent:e,nBins:t,which:n});return[s,o]}const Jc=new TextDecoder("utf-8");function Ys(e,t){const n=e.Module.H5T_class_t;return t.type===n.H5T_STRING.value?"string":t.type===n.H5T_INTEGER.value||t.type===n.H5T_FLOAT.value||t.type===n.H5T_ENUM.value?"number":"other"}function tl(e,t,n,s,o){const r=o-s;if(r<=0)return new Uint8Array(0);const a=n.metadata.size*r,c=wo(e,a);try{return e.Module.get_dataset_data(t.file_id,n.path,[BigInt(r)],[BigInt(s)],[1n],BigInt(c)),e.Module.HEAPU8.slice(c,c+a)}finally{e.Module._free(c)}}function el(e,t,n){const s=new Array(n);for(let o=0;o<n;o++){let r=e.subarray(o*t,(o+1)*t);const i=r.indexOf(0);i>-1&&(r=r.subarray(0,i)),s[o]=Jc.decode(r)}return s}function Fi(e,t,n,s,o){const r=o-s;if(r<=0)return[];const i=n.metadata;if(!i.vlen)return el(tl(e,t,n,s,o),i.size,r);const a=i.size*r,c=wo(e,a);try{e.Module.get_dataset_data(t.file_id,n.path,[BigInt(r)],[BigInt(s)],[1n],BigInt(c));const l=new Uint32Array(e.Module.HEAPU8.slice(c,c+a).buffer),u=new Array(r);for(let h=0;h<r;h++)u[h]=e.Module.UTF8ToString(l[h]);return u}finally{e.Module.reclaim_vlen_memory_count(t.file_id,n.path,"",BigInt(c),[BigInt(r)]),e.Module._free(c)}}function nl(e,t){if(t.littleEndian===!1||t.vlen)return null;const n=e.Module.H5T_class_t;if(t.type===n.H5T_INTEGER.value)return t.size===8?t.signed?"i64":"u64":t.size===4?t.signed?"i32":"u32":null;if(t.type===n.H5T_FLOAT.value){if(t.size===8)return"f64";if(t.size===4)return"f32"}return null}function zi(e,t,n,s,o){const r=t.metadata,i=nl(e.h5,r);if(i===null)return null;const a=s-n,{Module:c}=e.h5,l=wo(e.h5,r.size*a);try{return c.get_dataset_data(e.file.file_id,t.path,[BigInt(a)],[BigInt(n)],[1n],BigInt(l)),o(c.HEAPU8.buffer,l,a,i)}finally{c._free(l)}}function sl(e,t,n,s){switch(s){case"f64":return new Float64Array(e,t,n).slice();case"i64":case"u64":return js(s==="i64"?new BigInt64Array(e,t,n):new BigUint64Array(e,t,n));default:{const o=new Float64Array(n);return o.set(s==="i32"?new Int32Array(e,t,n):s==="u32"?new Uint32Array(e,t,n):new Float32Array(e,t,n)),o}}}function ol(e,t,n,s){switch(s){case"i32":return new Int32Array(e,t,n).slice();case"i64":case"u64":return ki(s==="i64"?new BigInt64Array(e,t,n):new BigUint64Array(e,t,n));default:{const o=new Int32Array(n);return o.set(s==="u32"?new Uint32Array(e,t,n):s==="f64"?new Float64Array(e,t,n):new Float32Array(e,t,n)),o}}}function Ri(e,t,n,s){if(n-t<=0)return new Float64Array(0);if(s!==void 0){const i=zi(s,e,t,n,sl);if(i!==null)return i}const r=e.slice([[t,n]]);if(r instanceof Float64Array)return r;if(r instanceof BigInt64Array||r instanceof BigUint64Array||ArrayBuffer.isView(r)&&!(r instanceof DataView))return js(r);throw new st(`/${e.path.replace(/^\//,"")} did not read back as a numeric array`,{path:e.path})}function rl(e,t,n,s){const o=n-t;if(o<=0)return new Int32Array(0);if(s!==void 0){const i=zi(s,e,t,n,ol);if(i!==null)return i}const r=e.slice([[t,n]]);if(r instanceof Int32Array)return r;if(r instanceof BigInt64Array||r instanceof BigUint64Array)return ki(r);if(ArrayBuffer.isView(r)&&!(r instanceof DataView)){const i=new Int32Array(o);return i.set(r),i}throw new st(`/${e.path.replace(/^\//,"")} did not read back as a numeric array`,{path:e.path})}function De(e,t,n){return{length:e,columns:t,data:n,get(s,o){const r=n[s];if(r===void 0||o<0||o>=e)return;const i=r[o];if(typeof i=="bigint")return Number(i);if(typeof i=="string"||typeof i=="number")return i},strings(s){const o=n[s];if(o===void 0)throw new st(`no such column: ${s}`,{column:s});if(Array.isArray(o)&&(o.length===0||typeof o[0]=="string"))return o;throw new st(`column ${s} is not a string column`,{column:s})},numbers(s){const o=n[s];if(o===void 0)throw new st(`no such column: ${s}`,{column:s});if(o instanceof BigInt64Array)return Array.from(o,Number);if(Array.isArray(o)&&o.length>0&&typeof o[0]=="string")throw new st(`column ${s} is not a numeric column`,{column:s});return Array.from(o)}}}function il(e,t,n,s,o,r,i){const a=[];for(const g of n.keys()){const w=n.get(g);if(!(w instanceof e.Dataset))continue;const p=w.metadata,b=p.shape;!b||b.length!==1||a.push({name:g,ds:w,md:p,length:b[0]})}if(new Set(a.map(g=>g.length)).size>1){const g=a.map(w=>`${w.name}=${w.length}`).sort().join(", ");throw new st(`/${s} columns have unequal lengths (${g}); every column of a table must have one row per record`,{table:s})}const l=a.length===0?0:a[0].length,u=Wo(o??0,0,l),h=Wo(r??l,u,l),f=i===void 0?null:new Set(i),d=[],m={};for(const{name:g,ds:w,md:p}of a)if(!(f!==null&&!f.has(g)))switch(Ys(e,p)){case"string":d.push(g),m[g]=Fi(e,t,w,u,h);break;case"number":d.push(g),m[g]=Ri(w,u,h,{h5:e,file:t});break}return De(h-u,d,m)}function Wo(e,t,n){return Math.min(Math.max(Math.trunc(e),t),n)}function wo(e,t){if(t>e.Module.MAXIMUM_MEMORY)throw new st(`a ${t} byte read exceeds the wasm heap limit of ${e.Module.MAXIMUM_MEMORY} bytes`,{nbytes:t,limit:e.Module.MAXIMUM_MEMORY});const n=e.Module._malloc(t);if(n===0)throw new st(`allocation of ${t} bytes in the wasm heap failed`,{nbytes:t});return n}function Mt(e){const t=e.indexOf("::");let n,s;if(t!==-1){n=e.slice(0,t).trim();const o=e.slice(t+2).trim();!o||o==="/"?s="/":s=o.startsWith("/")?o:`/${o}`}else n=e.trim(),s="/";if(!n)throw new C("bad-uri",`URI has an empty file path: ${V(e)}`,{uri:e});return{path:n,group:s}}const al=["genomes","contigs","bins","pixels","indexes"],cl=["bin-size","format-version","nbins","nnz","sum","ngenomes","ncontigs"];function kt(e,t){const n=e[t];return typeof n=="string"?n:null}function qn(e,t){const n=e[t];if(n==null)return null;const s=()=>{throw new st(`attrs[${V(t)}] must be an integer, got ${V(n)}`,{key:t,value:n})};if(typeof n=="string"){if(ic.includes(n.trim().toLowerCase()))return null;const o=xi(n);return o===null?s():o}return typeof n=="boolean"?s():typeof n=="number"&&Number.isInteger(n)?n:s()}function Pi(e){const t=e["storage-mode"];if(t==null)return"symmetric-upper";if(typeof t=="string"&&zo.includes(t))return t;throw new st(`attrs['storage-mode'] must be one of ${Dt([...zo].sort())}, got ${V(t)}`,{"storage-mode":t})}function Li(e){return e.has("entries")?e.keys("entries"):[]}function ll(e,t){return ho.some(n=>!e.has(`${t}/${n}`))?!1:kt(e.attrsAt(t),"format")===uo}function ul(e,t){if(kt(t,"format")===ln)return e.has(Un);if(kt(t,"metacooler-format")===Vn)return!1;const n=kt(t,"format");return n!==null&&n!==uo||ho.some(s=>e.has(s))||e.has("chroms")?!1:!e.has("resolutions")&&!e.has("entries")}function hl(e,t){if(kt(t,"format")===ln){const s=e.keys(Un);if(s.length>0)return{names:s,group:Un};throw new C("not-a-cooler",`${e.uri} declares format ${V(ln)} but has no cells under /${Un}. Top-level keys: ${Dt(e.keys("").slice(0,20))}.`,{format:ln,group:e.group})}if(ho.some(s=>e.has(s)))return null;const n=e.keys("");return n.length===0?null:ll(e,n[0])?{names:n,group:""}:null}function fl(e,t,n={}){const s=t??e.attrs(),o=kt(s,"format");if(n.metacool===!1&&dl(e,s,o)&&jo(e),o===Mi&&e.has("entries"))return{kind:"mmetacool",group:e.group,entries:Li(e)};if(kt(s,"metacooler-format")===Vn){const a=al.filter(c=>!e.has(c));if(a.length===0)return{kind:"metacool",group:e.group};throw new C("not-a-cooler",`${e.uri} declares metacooler-format ${V(Vn)} but is missing ${Dt(a.map(c=>`/${c}`))}. It cannot be read as a metacool, and reading it as the plain cooler it also is would drop the genome layer it says it has. If this came out of \`cooler zoomify\`, re-derive the resolutions with \`metacooler zoomify\` instead.`,{missing:[...a]})}const r=e.keys("resolutions");if(r.length>0)return{kind:"mcool",group:e.group,entries:Di(r)};const i=hl(e,s);if(i!==null)return{kind:"scool",group:e.group,entries:i.names,cellGroup:i.group};if(o===uo)return{kind:"cool",group:e.group};throw n.metacool===!1&&jo(e),new C("not-a-cooler",`${e.uri} is HDF5 but not a cooler or metacool file: its 'format' attribute is ${V(o)} and 'metacooler-format' is ${V(kt(s,"metacooler-format"))}. Top-level keys: ${Dt(e.keys("").slice(0,20))}. Convert a plain cooler with \`metacooler create cool\`.`,{format:o,group:e.group})}function dl(e,t,n){return n===Mi&&e.has("entries")||kt(t,"metacooler-format")===Vn}function jo(e){throw new C("not-a-cooler",`${e.uri} is an HDF5 file, but not a contact map this viewer reads: it is not a cooler, an .mcool or an .scool. Top-level keys: ${Dt(e.keys("").slice(0,20))}.`,{group:e.group})}function ml(e){const{path:t}=Mt(e.uri),n=Li(e),s=n.map(r=>`/entries/${r}`),o=s.length>0?s[0]:"/entries/<name>";throw new C("mmetacool-root",`No metacool entry at root of ${t}. Metacool entries found: ${Dt(s)}. Use '::' to specify a group path, e.g. ${t}::${o}.`,{path:t,entries:n})}function Di(e){return e.length>0&&e.every(n=>/^\d+$/.test(n)&&Number(n)>0)?[...e].sort((n,s)=>Number(n)-Number(s)):e}function gl(e){const t=[...e].sort((n,s)=>n-s);return t[Math.floor(t.length/3)]}function wl(e,t){const{path:n}=Mt(e.uri),s=t.map(r=>`/resolutions/${r}`),o=s.length>0?s[0]:"/resolutions/<binsize>";throw new C("mcool-root",`No cooler at root of ${n}: an .mcool is a collection of resolutions, each a complete cooler. Resolutions found: ${Dt(s)}. Use '::' to pick one, e.g. ${n}::${o}.`,{path:n,entries:t,group:"resolutions"})}function ts(e,t){const n=e.cellGroup??"";return n===""?t:`${n}/${t}`}function Ui(e,t,n){if(qn(n,"bin-size")!==null)return{attrs:n,from:null};const s=t.entries?.[0];if(s===void 0)return{attrs:n,from:null};const o=ts(t,s);return{attrs:e.attrsAt(o),from:o}}function pl(e,t){if(!((t.entries??[]).length>0))throw new C("not-a-cooler",`${Mt(e.uri).path} is a single-cell cooler container with no cells in it.`,{path:Mt(e.uri).path})}function bl(e,t,n,s={}){t.kind==="mmetacool"&&ml(e),t.kind==="mcool"&&wl(e,t.entries??[]);const o=n??e.attrs();if(t.kind==="metacool"){const c=qn(o,"metacooler-format-version");if(c!==null&&c!==1)throw new C("bad-format-version",`This file declares metacooler-format-version ${c}; the viewer only understands version 1. Re-create it with a matching metacooler release, or open it with the version of the viewer that reads ${c}.`,{found:c,expected:1});const l=kt(o,"contig-ordering");if(l!==Sn)throw new C("bad-ordering",`This file's contig-ordering is ${V(l)}; the viewer requires ${V(Sn)}. Only a genome-grouped layout puts every genome in one contiguous block of bins, which is what makes a genome or a genome pair a single bounded read. Re-create the file with \`metacooler create pairs --contig-order ${Sn}\`.`,{found:l,expected:Sn})}const r=t.kind==="scool"?Ui(e,t,o):{attrs:o};if(t.kind==="scool"){pl(e,t);const c=qn(o,"format-version");if(kt(o,"format")===ln&&c!==null&&c!==1)throw new C("bad-format-version",`This file declares scool format-version ${c}; the viewer understands version 1. Open it with a viewer that reads ${c}, or re-create it with \`cooler.create_scool\`.`,{found:c,expected:1})}const i=kt(r.attrs,"bin-type"),a=qn(r.attrs,"bin-size");if(i==="variable"||a===null||a<=0)throw new C("variable-bins",s.metacool===!1?`The viewer supports fixed-bin files only; this file's bin-type is ${V(i)} and its bin-size is ${V(a)}. Bin its contacts at a fixed size — \`cooler cload pairs\` does, from the pairs it was made from — and open that.`:`The viewer supports fixed-bin files only; this file's bin-type is ${V(i)} and its bin-size is ${V(a)}. Fragment-level and contig-level metacools are variable-bin by construction. Produce a fixed-bin file with \`metacooler binnify --binsize <bp>\` and open that.`,{"bin-type":i,"bin-size":a});Pi(r.attrs)}function Gi(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function yl(e){if(typeof e=="number")return Number.isFinite(e)?Math.trunc(e):e;if(typeof e=="string"){const t=xi(e);return t===null?e:t}return e}function le(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Je(e){return typeof e=="string"?e:null}function Al(e){const t={};for(const[p,b]of Object.entries(e))t[p]=Gi(b);const n=p=>{const b=t[p];return delete t[p],b},s=n("metacooler-format"),o=n("metacooler-format-url"),r=n("metacooler-format-version"),i=s!=null,a=i?s:t.format,c=i?o:t["format-url"],l=i?r:t["format-version"],u=n("contig-ordering"),h=n("nchroms"),f=n("assembly-name"),d=n("assembly"),m=n("genome-assembly");let g=m!==void 0?m:d;(g==null||g===""||g==="unknown")&&f!==void 0&&f!==null&&(g=f),n("metadata");const w={"bin-size":t["bin-size"],"format-version":l,nbins:t.nbins,nnz:t.nnz,sum:t.sum,ngenomes:t.ngenomes,ncontigs:h};for(const p of cl)w[p]!==void 0&&(w[p]=yl(w[p]));return{...t,format:Je(a),"format-url":Je(c),"format-version":le(w["format-version"]),"bin-size":le(w["bin-size"]),"bin-type":Je(t["bin-type"]),ordering:Je(u),assembly:Je(g),"storage-mode":Pi(e),nbins:le(w.nbins),nnz:le(w.nnz),sum:le(w.sum),ngenomes:le(w.ngenomes),ncontigs:le(w.ncontigs)}}function Ml(e){const t=Gi(e.metadata);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}const xl=new TextDecoder("utf-8");async function Sl(e,t,n){const s=await ae(),o=await t.mount();let r;try{r=new s.File(o,"r")}catch(l){throw t.close(),new C("not-hdf5",`${e} could not be opened as an HDF5 file: ${Il(l)}`,{uri:e,source:t.id})}const i=Hi(n);try{if(i!=="/"){const l=r.get(i);if(l===null)throw new C("entry-not-found",`Group '${i}' not found in ${t.id}. Top-level keys: ${_e(r.keys())}`,{uri:e,group:i,available:r.keys()});if(!(l instanceof s.Group))throw new st(`'${i}' in ${t.id} is not an HDF5 group`,{uri:e,group:i},"entry-not-found")}}catch(l){throw r.close(),t.close(),l}let a=[],c="";try{for(const l of["entries","resolutions"]){if(r.get_type(`/${l}`)<0)continue;const u=r.get(l);if(u instanceof s.Group){a=Di(u.keys()),c=l;break}}}catch{}return new po(e,i,s,r,t,a,c)}class po{uri;group;rootEntries;rootEntryGroup;h5;file;heap;source;closed=!1;borrowed;constructor(t,n,s,o,r,i=[],a="",c=!1){this.uri=t,this.group=n,this.rootEntries=i,this.rootEntryGroup=a,this.borrowed=c,this.h5=s,this.file=o,this.heap={h5:s,file:o},this.source=r}attrs(){return this.attrsAt("")}attrsAt(t){const n=this.entity(t),s=n instanceof this.h5.Group||n instanceof this.h5.Dataset;if(n===null||!s)throw new st(`${this.describe(t)} does not exist, or carries no attributes`,{uri:this.uri,path:this.resolve(t)});const o={};for(const[r,i]of Object.entries(n.attrs))o[r]=this.decodeAttr(n.path,r,i.metadata,i.json_value);return o}has(t){return this.assertOpen(),this.file.get_type(this.resolve(t))>=0}keys(t){const n=this.entity(t);return n===null||!(n instanceof this.h5.Group)?[]:n.keys()}isSoftLink(t){if(!this.has(t))return!1;const n=this.file.get_link(this.resolve(t));return typeof n=="string"&&n.length>0}datasetLength(t){const n=this.dataset(t).metadata.shape;return n&&n.length>0?n[0]:0}dtype(t){const n=this.dataset(t).dtype;if(typeof n!="string")throw new st(`${this.describe(t)} has a compound datatype, which this reader does not read`,{uri:this.uri,path:this.resolve(t)});return n}readNumeric(t,n,s){const[o,r,i]=this.numericRange(t,n,s);return Ri(o,r,i,this.heap)}readInt32(t,n,s){const[o,r,i]=this.numericRange(t,n,s);return rl(o,r,i,this.heap)}numericRange(t,n,s){const o=this.dataset(t);if(Ys(this.h5,o.metadata)!=="number")throw new st(`${this.describe(t)} is ${String(o.dtype)}, not a numeric dataset`,{uri:this.uri,path:this.resolve(t),dtype:String(o.dtype)});const[r,i]=this.range(o,n,s);return[o,r,i]}readStrings(t,n,s){const o=this.dataset(t),r=o.metadata;if(Ys(this.h5,r)!=="string")throw new st(`${this.describe(t)} is ${String(o.dtype)}, not a string dataset`,{uri:this.uri,path:this.resolve(t),dtype:String(o.dtype)});const[i,a]=this.range(o,n,s);return Fi(this.h5,this.file,o,i,a)}readTable(t,n,s,o){const r=this.entity(t);if(r===null||!(r instanceof this.h5.Group))throw new st(`${this.describe(t)} is not a table group`,{uri:this.uri,path:this.resolve(t)});const i=this.resolve(t).slice(this.group==="/"?1:this.group.length+1);return il(this.h5,this.file,r,i,n,s,o)}at(t){const n=this.resolve(t);return new po(this.uri,n,this.h5,this.file,this.source,this.rootEntries,this.rootEntryGroup,!0)}close(){if(!(this.closed||this.borrowed)){this.closed=!0;try{this.file.close()}finally{this.source.close()}}}resolve(t){const n=t.replace(/^\/+/,"");return n===""?this.group:Hi(this.group==="/"?`/${n}`:`${this.group}/${n}`)}describe(t){return`${this.uri} :: ${this.resolve(t)}`}entity(t){this.assertOpen();const n=this.resolve(t);return n==="/"?this.file:this.file.get(n)}dataset(t){const n=this.entity(t);if(n===null)throw new st(`${this.describe(t)} does not exist`,{uri:this.uri,path:this.resolve(t)});if(!(n instanceof this.h5.Dataset))throw new st(`${this.describe(t)} is not a dataset`,{uri:this.uri,path:this.resolve(t)});return n}range(t,n,s){const o=t.metadata.shape;if(!o||o.length!==1)throw new st(`/${t.path.replace(/^\//,"")} is ${o?`${o.length}-D`:"scalar"}; this reader only slices 1-D columns`,{path:t.path,shape:o});const r=o[0],i=Math.min(Math.max(Math.trunc(n??0),0),r),a=Math.min(Math.max(Math.trunc(s??r),i),r);return[i,a]}decodeAttr(t,n,s,o){if(s.type===this.h5.Module.H5T_class_t.H5T_STRING.value&&!s.vlen){const r=this.readFixedStringAttr(t,n,s);if(r!==null)return r}return El(o)}readFixedStringAttr(t,n,s){const o=s.total_size,r=s.size*o;if(r<=0)return null;const i=this.h5.Module,a=i._malloc(r);if(a===0)return null;let c;try{i.get_attribute_data(this.file.file_id,t,n,BigInt(a)),c=i.HEAPU8.slice(a,a+r)}finally{i._free(a)}const l=[];for(let h=0;h<o;h++){let f=c.subarray(h*s.size,(h+1)*s.size);const d=f.indexOf(0);d>-1&&(f=f.subarray(0,d)),l.push(xl.decode(f))}const u=s.shape;return u&&u.length>0?l:l[0]??""}assertOpen(){if(this.closed)throw new st(`${this.uri} is closed`,{uri:this.uri})}}function Il(e){return e instanceof Error?e.message:String(e)}function Hi(e){const t=`/${e}`.replace(/\/+/g,"/").replace(/(.)\/$/,"$1");return t===""?"/":t}function El(e){if(e==null)return null;if(typeof e=="bigint")return Number(e);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e)){if(e.every(n=>typeof n=="string"))return e;const t=n=>typeof n=="number"||typeof n=="boolean"||typeof n=="bigint";return e.every(t)?e.map(n=>Number(n)):e.map(n=>String(n))}return null}const qt=4096,es={binsPerCell:1,contigsPerCell:1};function qi(e,t,n,s=es,o){const r=Math.max(0,Math.trunc(e));if(r===0)return{slot:new Int32Array(0),cellStart:new Int32Array(1),cellSegments:new Int32Array(0),cells:0,plan:es};const i=t.length>0?t.length:1,a=Math.max(1,Math.trunc(n)),c=h=>t.length>0?t[h]:0,l=h=>(h+1<i?c(h+1):r)-c(h),u=Math.max(s.binsPerCell,Wi(i,l,a,o));return Cl(r,i,c,l,u,o)}function vl(e,t,n,s){let o=0,r=0,i=-1;for(let a=0;a<e;a++){const c=t(a);if(c>=n){o+=Math.ceil(c/n),r=0,i=-1;continue}const l=s===void 0?0:s[a];r===0||r+c>n||l!==i?(o++,r=c,i=l):r+=c}return o}function Wi(e,t,n,s){let o=s;const r=c=>vl(e,t,c,o)<=n;let i=1;for(;!r(i);)if(i>=Number.MAX_SAFE_INTEGER/2){if(o===void 0)return i;o=void 0,i=1}else i*=2;let a=1;for(;a<i;){const c=a+i>>1;r(c)?i=c:a=c+1}return a}function Cl(e,t,n,s,o,r){const i=new Int32Array(e),a=[],c=[];let l=0,u=0,h=-1;for(let d=0;d<t;d++){const m=n(d),g=s(d),w=m+g;if(g>=o){u=0,h=-1;for(let b=m;b<w;b++)(b-m)%o===0&&(a.push(b),c.push(1),l++),i[b]=l-1;continue}const p=r===void 0?0:r[d];u===0||u+g>o||p!==h?(a.push(m),c.push(1),l++,u=g,h=p):(u+=g,c[l-1]++);for(let b=m;b<w;b++)i[b]=l-1}a.push(e);let f=1;for(const d of c)f=Math.max(f,d);return{slot:i,cellStart:Int32Array.from(a),cellSegments:Int32Array.from(c),cells:l,plan:{binsPerCell:o,contigsPerCell:f}}}function $l(e){const t=[];for(let n=0;n<e.length;n++)(n===0||e[n]!==e[n-1])&&t.push(n);return Int32Array.from(t)}function Qo(e,t,n,s=es,o=qt,r){const i=Math.max(0,n-t);if(i===0)return{slot:new Int32Array(0),ids:new Int32Array(0),stride:1,contigsPerCell:1,cellStart:new Int32Array(1),members:new Int32Array(0),memberStart:new Int32Array(1)};const a=e.contigsOfBins(t,n),c=$l(a),l=r===void 0||r.length===0?void 0:Int32Array.from(c,m=>r[a[m]]??-1),u=qi(i,c,o,s,l),h=new Int32Array(u.cells),f=[],d=new Int32Array(u.cells+1);for(let m=0;m<u.cells;m++){d[m]=f.length;const g=u.cellStart[m],w=u.cellStart[m+1];h[m]=a[g];for(let p=g;p<w;p++)(p===g||a[p]!==a[p-1])&&f.push(a[p])}return d[u.cells]=f.length,{slot:u.slot,ids:h,stride:u.plan.binsPerCell,contigsPerCell:u.plan.contigsPerCell,cellStart:u.cellStart,members:Int32Array.from(f),memberStart:d}}function Nl(e,t,n,s=qt,o){const r=t.map(({extent:y})=>Math.max(0,y[1]-y[0])),i=r.reduce((y,A)=>y+A,0),a=o===void 0?void 0:Int32Array.from(t,({id:y})=>o[y]??-1),c=Math.max(n.binsPerCell,Wi(r.length,y=>r[y],Math.max(1,Math.trunc(s)),a)),l=new Int32Array(e).fill(-1),u=[],h=[],f=[],d=[];let m=0,g=0,w=-1,p=1,b=0;for(let y=0;y<t.length;y++){const{id:A,extent:x}=t[y],[E,S]=x,v=r[y];if(v===0)continue;const I=a===void 0?0:a[y],N=v>=c;for(let B=E;B<S;B++){const z=B-E;(N?z%c===0:z===0&&(g===0||g+v>c||I!==w))?(u.push(A),h.push(m),d.push(f.length),f.push(A),g=0,w=I,b=0):z===0&&f.push(A),l[B]=u.length-1,m++}N?(g=0,w=-1,b=0):(g+=v,b++,p=Math.max(p,b))}return h.push(m),d.push(f.length),{slot:l,ids:Int32Array.from(u),stride:c,contigsPerCell:p,cellStart:Int32Array.from(h),members:Int32Array.from(f),memberStart:Int32Array.from(d),bins:i}}function ji(e){const t=new Int32Array(e.length),n=new Map,s=[];for(let o=0;o<e.length;o++){const r=e[o];let i=n.get(r);i===void 0&&(i=s.length,n.set(r,i),s.push(r)),t[o]=i}return{slot:t,ids:Int32Array.from(s)}}function Bl(e,t,n,s,o=!1){const r=t.ids.length,i=n.ids.length,a=new Float64Array(r*i),c=o&&e.nrows===e.ncols;for(let l=0;l<e.nrows;l++){const u=t.slot[l],h=l*e.ncols;for(let f=c?l:0;f<e.ncols;f++){const d=n.slot[f],m=c&&u>d?d*i+u:u*i+d,g=e.values[h+f];Number.isNaN(g)||(a[m]+=g)}}if(c)for(let l=0;l<r;l++)for(let u=l+1;u<i;u++)a[u*i+l]=a[l*i+u];return{nrows:r,ncols:i,values:a,rowIds:t.ids,colIds:n.ids,level:s}}function Qi(e,t,n){return ji(e.contigsOfBins(t,n))}function Yi(e,t,n,s){const o=e.contigsOfBins(n,s),r=new Int32Array(o.length);for(let i=0;i<o.length;i++)r[i]=t[o[i]];return ji(r)}function Yo(e,t,n){const s=e.ids.length;if(s<=t)return{grouping:e,perCell:1};const o=Int32Array.from({length:s},(l,u)=>u),r=n===void 0?void 0:Int32Array.from(e.ids,n),i=qi(s,o,t,es,r),a=new Int32Array(e.slot.length);for(let l=0;l<a.length;l++){const u=e.slot[l];a[l]=u<0?-1:i.slot[u]}const c=new Int32Array(i.cells);for(let l=0;l<i.cells;l++)c[l]=e.ids[i.cellStart[l]];return{grouping:{slot:a,ids:c},perCell:i.plan.contigsPerCell}}function Ol(e,t,n,s,o,r,i=!0,a=Number.POSITIVE_INFINITY){const c=m=>o==="contig"?Qi(n,m[0],m[1]):Yi(n,s,m[0],m[1]),l=e[0]===t[0]&&e[1]===t[1],u=o==="contig"&&s.length>0?m=>s[m]??-1:void 0,h=Yo(c(e),a,u),f=l?h:Yo(c(t),a,u),d=Vs(e,t,h.grouping,f.grouping,r,i);return{place:d.place,finish:()=>({...d.finish(),level:o}),perCell:Math.max(h.perCell,f.perCell)}}function Vs(e,t,n,s,o,r=!0,i=!1){const c=e[0]===t[0]&&e[1]===t[1]&&r,l=n.ids.length,u=s.ids.length,h=i&&c&&l===u,f=new Float64Array(h?l*(l+1)/2:l*u),[d,m]=e,[g,w]=t,p=o!=="transpose",b=o!=="direct"&&!c,y=o==="symmetric",A=(x,E,S)=>{const v=n.slot[x],I=s.slot[E];if(!(v<0||I<0)){if(h){const N=v<I?v:I,B=v<I?I:v;f[N*l-N*(N-1)/2+(B-N)]+=S;return}f[c&&v>I?I*u+v:v*u+I]+=S}};return{place(x,E,S){Number.isNaN(S)||(p&&x>=d&&x<m&&E>=g&&E<w&&A(x-d,E-g,S),b&&!(y&&x===E)&&E>=d&&E<m&&x>=g&&x<w&&A(E-d,x-g,S))},finish(){if(h){const x=new Float32Array(l*l);let E=0;for(let S=0;S<l;S++)for(let v=S;v<l;v++,E++){const I=f[E];x[S*l+v]=I,x[v*l+S]=I}return{nrows:l,ncols:u,values:x,rowIds:n.ids,colIds:s.ids}}if(c)for(let x=0;x<l;x++)for(let E=x+1;E<u;E++)f[E*u+x]=f[x*u+E];return{nrows:l,ncols:u,values:f,rowIds:n.ids,colIds:s.ids}}}}function kl(e,t,n,s,o=!0){const r=l=>s==="contig"?Qi(t,l[0],l[1]):Yi(t,n,l[0],l[1]),i=e.rowExtent[0]===e.colExtent[0]&&e.rowExtent[1]===e.colExtent[1],a=r(e.rowExtent),c=i?a:r(e.colExtent);return Bl(e,a,c,s,i&&o)}function _l(e,t){let n=0,s=e.length-1;for(;n<s;){const o=n+s+1>>1;e[o]<=t?n=o:s=o-1}return n}class Tl{binsize;chromOffset;contigLengths;constructor(t,n,s){this.binsize=t,this.chromOffset=n,this.contigLengths=s}get nContigs(){return this.contigLengths.length}get nBins(){return this.chromOffset.length>0?this.chromOffset[this.chromOffset.length-1]:0}binsInContig(t){return Math.ceil(this.contigLengths[t]/this.binsize)}contigStartBin(t){return this.chromOffset[t]}contigBinExtent(t){return[this.chromOffset[t],this.chromOffset[t+1]]}binIndex(t,n){return this.chromOffset[t]+Math.floor(n/this.binsize)}contigOfBin(t){return _l(this.chromOffset,t)}binStart(t){const n=this.contigOfBin(t);return(t-this.chromOffset[n])*this.binsize}binEnd(t){const n=this.contigOfBin(t),s=(t-this.chromOffset[n])*this.binsize;return Math.min(s+this.binsize,this.contigLengths[n])}contigsOfBins(t,n){const s=new Int32Array(Math.max(0,n-t));if(s.length===0)return s;let o=this.contigOfBin(t),r=this.chromOffset[o+1];for(let i=t;i<n;i++){for(;i>=r&&o+1<this.nContigs;)o+=1,r=this.chromOffset[o+1];s[i-t]=o}return s}}function Fl(e,t,n){if(e===t||e.binsize===t.binsize)return[n[0],n[1]];if(n[1]<=n[0]){const g=Math.min(Math.max(n[0],0),t.nBins);return[g,g]}const s=g=>Math.min(Math.max(g,0),Math.max(0,e.nBins-1)),o=e.contigOfBin(s(n[0])),[r]=e.contigBinExtent(o),[i,a]=t.contigBinExtent(o),c=n[0]<=r?i:Math.min(Math.max(i,a-1),i+Math.floor((n[0]-r)*e.binsize/t.binsize)),l=e.contigOfBin(s(n[1]-1)),[u,h]=e.contigBinExtent(l),[f,d]=t.contigBinExtent(l),m=n[1]>=h?d:Math.min(d,f+Math.ceil((n[1]-u)*e.binsize/t.binsize));return[Math.min(c,Math.max(0,m-1)),Math.min(t.nBins,Math.max(c+1,m))]}class Vi{constructor(t,n,s){this.handle=t,this.nBins=n,this.countKind=s}offsets=null;get nnz(){return this.handle.datasetLength("pixels/bin1_id")}scoreColumns(){return Dc(this.handle)}binOffsets(){return this.offsets??=this.handle.readNumeric("indexes/bin1_offset"),this.offsets}async forEachWindow(t,n,s,o,r={}){return Qc(this.handle,s.span[0],s.span[1],o,r)}async forEachBands(t,n,s={}){return Yc(this.handle,this.pixelBandsOf(t),n,s,this.binOffsets())}async scanAll(t){const n=t.chunkSize??1e6,s=this.nnz,o=t.storedRows===!0?null:new mo(this.binOffsets(),0);for(let r=0;r<s;r+=n){const i=Math.min(r+n,s),a=t.onChunk(go(this.handle,r,i,ee,o));if(t.onProgress?.(i,s),a===!1)return;await(t.pause?.()??St())}}pixelBandsOf(t){const n=this.binOffsets(),s=[];for(const[r,i]of t){if(i<=r)continue;const a=n[Math.max(0,r)],c=n[Math.min(this.nBins,i)];c>a&&s.push([a,c])}s.sort((r,i)=>r[0]-i[0]);const o=[];for(const r of s){const i=o[o.length-1];i!==void 0&&r[0]<=i[1]+Ti?i[1]=Math.max(i[1],r[1]):o.push([r[0],r[1]])}return o}}const Ks=16384,zl=64*1024*1024,Rl=256;function Pl(e,t,n){const s=Math.max(1,Math.trunc(t)),o=n??null,r=o===null?e.nContigs:o.length,i=new Int32Array(r+1),a=new Int32Array(e.nBins);o!==null&&a.fill(-1);let c=0;for(let l=0;l<r;l++){const u=o===null?l:o[l];i[l]=c;const[h,f]=e.contigBinExtent(u);for(let d=h;d<f;d++)a[d]=c+Math.floor((d-h)/s);c+=Math.ceil((f-h)/s)}return i[r]=c,{stride:s,n:c,slot:a,offsets:i,...o===null?{}:{contigs:Int32Array.from(o)}}}function Ll(e,t,n){let s=0;const o=n===void 0?e.nContigs:n.length;for(let r=0;r<o;r++){const[i,a]=e.contigBinExtent(n===void 0?r:n[r]);s+=Math.ceil((a-i)/t)}return s}function Dl(e,t=Ks,n){if((n===void 0?e.nContigs:n.length)>t)return null;const s=i=>Ll(e,i,n);if(s(1)<=t)return 1;let o=2;for(;s(o)>t;)o*=2;let r=o>>1;for(;r+1<o;){const i=r+o>>1;s(i)<=t?o=i:r=i}return o}const Ki=64;function Ul(e,t,n,s=Ki){if(t===null)return 1;let o=0,r=0;const i=n===void 0?e.nContigs:n.length;for(let a=0;a<i;a++){const[c,l]=e.contigBinExtent(n===void 0?a:n[a]);o+=t[l]-t[c],r+=l-c}return!(r>0)||!(o>0)?1:Math.max(1,Math.ceil(s/(o/r)))}function Gl(e,t,n,s,o=Ki){if(t===null)return n;let r=0,i=0;const a=s===void 0?e.nContigs:s.length;for(let l=0;l<a;l++){const[u,h]=e.contigBinExtent(s===void 0?l:s[l]);r+=t[h]-t[u],i+=h-u}if(!(i>0)||!(r>0))return n;const c=r/i;return c<o?n*Math.ceil(o/c):n/Math.floor(c/o)}function vt(e,t,n){return e*n-e*(e-1)/2+(t-e)}function ns(e){return e*(e+1)/2}function Xi(e,t){if(!(e>0))return 0;const n=(Math.log10(e)-t.low)*(254/(t.high-t.low)),s=1+Math.round(n);return s<1?1:s>255?255:s}function Zi(e,t){return e===0?Number.NEGATIVE_INFINITY:t.low+(e-1)*(t.high-t.low)/254}function Hl(e){const t=new Float64Array(256);for(let n=1;n<256;n++)t[n]=10**Zi(n,e);return t}function ql(e){const s=new Uint32Array(4e3);let o=0,r=Number.NEGATIVE_INFINITY;for(let h=0;h<e.length;h++){const f=e[h];if(!(f>0))continue;const d=Math.log10(f);d>r&&(r=d);const m=Math.floor((d- -20)*100);s[m<0?0:m>=4e3?3999:m]++,o++}if(o<1e3)return null;const i=o*.001;let a=0,c=-20;for(let h=0;h<4e3;h++)if(a+=s[h],a>=i){c=-20+h/100;break}const l=c-1,u=Math.max(r+.5,l+1);return{low:l,high:u}}const Vo={low:-12,high:8};function Wl(e,t,n){let s=e.rowStart[t],o=e.rowStart[t+1]-1;const r=e.cols;for(;s<=o;){const i=s+o>>1,a=r[i];if(a<n)s=i+1;else if(a>n)o=i-1;else return e.values[i]}}const jl=4e6;function Ql(e,t){const n=i=>{let a=0;for(let c=0;c+1<e.length;c++)a+=Math.ceil((e[c+1]-e[c])/i);return a};let s=1;for(let i=0;i+1<e.length;i++)s=Math.max(s,e[i+1]-e[i]);if(n(1)<=t)return 1;if(n(s)>t)return s;let o=1,r=s;for(;o+1<r;){const i=o+r>>1;n(i)<=t?r=i:o=i}return r}async function Yl(e){const{store:t,layout:n,weights:s}=e,o=n.n,r=n.slot,i=r.length,a=new Uint8Array(ns(o)),c=new Float64Array(256),l=e.gather===void 0?null:Vl(n,s,e.gather),u=new Int32Array(o).fill(-1),h=new Int32Array(o);for(let x=0;x<i;x++){const E=r[x];E<0||(u[E]<0&&(u[E]=x),h[E]=x+1)}const f=(x,E)=>{const S=[];for(let v=x;v<E;v++){if(u[v]<0)continue;const I=S[S.length-1];I!==void 0&&I[1]===u[v]?I[1]=h[v]:S.push([u[v],h[v]])}return S},d=Math.max(1,Math.floor((e.bandBytes??zl)/(4*Math.max(1,o)))),m=new Float32Array(Math.min(o,d)*o);let g=null;try{g=t.binOffsets()}catch{g=null}const w=x=>g===null?0:x.reduce((E,[S,v])=>E+(g[v]-g[S]),0),p=g!==null?w(f(0,o)):o;let b=0,y=null,A=0;for(let x=0;x<o;x+=d){if(e.cancelled?.()===!0)return null;const E=Math.min(o,x+d),S=f(x,E),v=(E-x)*o;m.fill(0,0,v);const I=b;if(!await t.forEachBands(S,B=>{for(let z=0;z<B.length;z++){const R=B.bin1[z],P=B.bin2[z];if(P<R)continue;const L=r[R],j=r[P];if(L<0||j<0)continue;let W=B.count[z];s!==null&&(W*=s[R]*s[P]),W>0&&(m[(L-x)*o+j]+=L===j&&R!==P?2*W:W)}A+=B.length},{...e.cancelled===void 0?{}:{cancelled:e.cancelled},...e.value===void 0?{}:{value:e.value},onProgress:B=>{g!==null&&e.onProgress?.(I+B,p)}}))return null;y??=ql(m.subarray(0,v))??Vo;for(let B=x;B<E;B++){const z=(B-x)*o;let R=vt(B,B,o);for(let P=B;P<o;P++,R++){const L=Xi(m[z+P],y);a[R]=L,c[L]++}l?.row(B,m,z)}b=g!==null?I+w(S):E,e.onProgress?.(b,p),await St()}return{cells:a,quantizer:y??Vo,histogram:c,pixels:A,...l===null?{}:{contacts:l.finish()}}}function Vl(e,t,n){const s=e.n,o=Math.max(1,Math.trunc(n.width)),r=new Uint16Array(s);for(let S=0;S<e.slot.length;S++)e.slot[S]>=0&&(t===null||t[S]>0)&&r[e.slot[S]]++;const i=new Int32Array(s);for(let S=0;S+1<e.offsets.length;S++)i.fill(S,e.offsets[S],e.offsets[S+1]);const a=Ql(e.offsets,Math.max(1,n.coarseCells)),c=new Int32Array(s);let l=0;for(let S=0;S+1<e.offsets.length;S++){const v=e.offsets[S];for(let I=v;I<e.offsets[S+1];I++)c[I]=l+Math.floor((I-v)/a);l+=Math.ceil((e.offsets[S+1]-v)/a)}const u=new Float32Array(s*o).fill(Number.NaN),h=new Float64Array(ns(l)),f=new Uint32Array(ns(l)),d=new Float64Array(s),m=Math.max(0,Math.trunc(n.endDepth??0)),g=new Int32Array(s).fill(-1);if(m>0)for(let S=0;S+1<e.offsets.length;S++){const v=e.offsets[S],I=e.offsets[S+1],N=I-v;g.fill(2*S,v,v+Math.min(m,Math.ceil(N/2))),g.fill(2*S+1,I-Math.min(m,Math.floor(N/2)),I)}const w=Math.max(0,Math.trunc(n.endBudget??jl)),p=new Int32Array(m>0?s+1:0);let b=new Int32Array(m>0?1024:0),y=new Float32Array(b.length),A=0,x=!0;const E=(S,v)=>{if(A>=w){x=!1;return}if(A===b.length){const I=Math.min(w,b.length*2),N=new Int32Array(I),B=new Float32Array(I);N.set(b),B.set(y),b=N,y=B}b[A]=S,y[A]=v,A++};return{row(S,v,I){m>0&&(p[S]=A);const N=r[S];if(N===0)return;const B=i[S],z=c[S],R=vt(z,z,l)-z,P=g[S]>=0;for(let L=S;L<s;L++){const j=r[L];if(j===0)continue;const W=v[I+L]/(N*j);L-S<o&&i[L]===B?u[S*o+(L-S)]=W:P&&W>0&&g[L]>=0&&E(L,W);const Z=R+c[L];h[Z]+=W,f[Z]++,d[S]+=W,L!==S&&(d[L]+=W)}},finish(){const S=new Float32Array(h.length);for(let v=0;v<h.length;v++)S[v]=f[v]===0?Number.NaN:h[v]/f[v];return{n:s,sequenceOf:i,width:o,band:u,coarse:{n:l,factor:a,of:c,values:S},marginal:d,kept:r,...m>0?{ends:{depth:m,zone:g,rowStart:Kl(p,A),cols:b.slice(0,A),values:y.slice(0,A),complete:x}}:{}}}}}function Kl(e,t){return e[e.length-1]=t,e}function Xl(e,t,n=Rl){const s=Hl(t),o=[e];let r=e;for(;r.n>n;){const i=r.n,a=r.cells,c=Math.ceil(i/2),l=new Uint8Array(ns(c));let u=0;for(let h=0;h<c;h++){const f=2*h,d=f+1;for(let m=h;m<c;m++,u++){const g=2*m,w=g+1;let p=s[a[vt(f,g,i)]],b=1;w<i&&(p+=s[a[vt(f,w,i)]],b++),d<i&&(p+=s[a[d<=g?vt(d,g,i):vt(g,d,i)]],b++,w<i&&(p+=s[a[vt(d,w,i)]],b++)),l[u]=Xi(p/b,t)}}r={n:c,cells:l},o.push(r)}return o}function Zl(e,t){let n=0;for(let i=1;i<256;i++)n+=e[i];if(n===0)return{vmin:t.low,vmax:t.high};const s=i=>{const a=n*i;let c=0;for(let l=1;l<256;l++)if(c+=e[l],c>=a)return Zi(l,t);return t.high},o=s(.01),r=s(.99);return r>o?{vmin:o,vmax:r}:{vmin:o,vmax:o+1}}function at(e){return e.gap!==void 0}const Jl=["debris","contaminant","haplotig","unplaced"];function us(e){const t=new Map(e.names.map((n,s)=>[n,e.lengths[s]]));for(const n of e.elsewhere??[])t.has(n.name)||t.set(n.name,n.length);return t}function Xt(e,t){for(let n=1;;n++){const s=`${e}_e${n}`;if(!t.has(s))return s}}function hs(e){return at(e)?e.gap:e.end-e.start}function Ce(e){let t=0;for(const n of e)t+=hs(n);return t}function Zt(e,t,n){return e<t?t:e>n?n:e}function tu(e,t,n){return at(e)?[{gap:t},{gap:e.gap-t}]:e.strand===1?[{...e,id:n.next(e.id),end:e.start+t},{...e,id:n.next(e.id),start:e.start+t}]:[{...e,id:n.next(e.id),start:e.end-t},{...e,id:n.next(e.id),end:e.end-t}]}function Be(e,t,n){const s=[],o=[];let r=0;for(const i of e){const a=hs(i);if(r+a<=t)s.push(i);else if(r>=t)o.push(i);else{const[c,l]=tu(i,t-r,n);s.push(c),o.push(l)}r+=a}return[s,o]}function In(e,t,n,s){const[o,r]=Be(e,t,s),[i,a]=Be(r,n-t,s);return[o,i,a]}function tn(e){const t=[];for(let n=e.length-1;n>=0;n--){const s=e[n];t.push(at(s)?{gap:s.gap}:{...s,strand:s.strand===1?-1:1})}return t}function Pt(e){const t=[];for(const n of e){if(hs(n)===0)continue;const s=t[t.length-1];if(s!==void 0&&at(s)&&at(n)){t[t.length-1]={gap:s.gap+n.gap};continue}if(s!==void 0&&!at(s)&&!at(n)&&s.sequence===n.sequence&&s.strand===n.strand){if(n.strand===1&&s.end===n.start){t[t.length-1]={...s,end:n.end};continue}if(n.strand===-1&&s.start===n.end){t[t.length-1]={...s,start:n.start};continue}}t.push(n)}return t}class eu{counter=0;next(t){return this.counter+=1,`${t.split("~")[0]}~${this.counter}`}}function nu(e){return{sequences:e.names.map((t,n)=>({name:t,parts:[{id:t,sequence:t,start:0,end:e.lengths[n],strand:1}]})),aside:[]}}function Rt(e,t){return e.sequences.find(n=>n.name===t)??null}function En(e,t,n){const s=Ce(e.parts),o=Zt(Math.round(t),0,s),r=Zt(Math.round(n),0,s);return o<=r?[o,r]:[r,o]}function su(e,t,n,s){const o=e.sequences.map(c=>({...c,parts:[...c.parts]})),r={sequences:o,aside:[...e.aside]},i=new Set(o.map(c=>c.name)),a=new Set(us(n).keys());switch(t.op){case"cut":{const c=Rt(r,t.sequence);if(c===null)return e;const l=Zt(Math.round(t.at),0,Ce(c.parts)),[u,h]=Be(c.parts,l,s);return c.parts=[...u,...h],r}case"invert":{const c=Rt(r,t.sequence);if(c===null)return e;const[l,u]=En(c,t.from,t.to);if(u===l)return e;const[h,f,d]=In(c.parts,l,u,s);return c.parts=Pt([...h,...tn(f),...d]),r}case"move":case"duplicate":{const c=Rt(r,t.sequence),l=Rt(r,t.into);if(c===null||l===null)return e;const[u,h]=En(c,t.from,t.to);if(h===u)return e;const[f,d,m]=In(c.parts,u,h,s),g=t.strand===1?d:tn(d);t.op==="move"?c.parts=Pt([...f,...m]):g.forEach((y,A)=>{at(y)||(g[A]={...y,id:s.next(y.id)})});const w=Zt(Math.round(t.at),0,Ce(l.parts)),[p,b]=Be(l.parts,w,s);return l.parts=Pt([...p,...g,...b]),c!==l&&c.parts.length===0&&(r.sequences=r.sequences.filter(y=>y!==c)),r}case"join":{const c=Rt(r,t.a),l=Rt(r,t.b);if(c===null||l===null||c===l)return e;const u=t.aEnd==="end"?c.parts:tn(c.parts),h=t.bEnd==="start"?l.parts:tn(l.parts),f=t.gap>0?[{gap:Math.round(t.gap)}]:[];return c.parts=Pt([...u,...f,...h]),a.has(c.name)&&!fs(c,n)&&(i.delete(c.name),c.name=Xt(c.name,i)),t.place==="b"?(r.sequences=r.sequences.filter(d=>d!==c),r.sequences.splice(r.sequences.indexOf(l),1,c)):r.sequences=r.sequences.filter(d=>d!==l),r}case"split":{const c=Rt(r,t.sequence);if(c===null)return e;const l=Zt(Math.round(t.at),0,Ce(c.parts));if(l===0||l===Ce(c.parts))return e;const[u,h]=Be(c.parts,l,s);c.parts=Pt(u);const f=on(c.name);a.has(c.name)&&(i.delete(c.name),c.name=Xt(f,i),i.add(c.name));const d=t.name!==void 0&&!i.has(t.name)?t.name:Xt(f,i);i.add(d);const m=r.sequences.indexOf(c);return r.sequences.splice(m+1,0,{name:d,parts:Pt(h)}),r}case"aside":{const c=Rt(r,t.sequence);if(c===null)return e;const[l,u]=En(c,t.from,t.to);if(u===l)return e;const[h,f,d]=In(c.parts,l,u,s),m=typeof t.genome=="string"&&t.genome!==""?t.genome:void 0;for(const g of f)at(g)||r.aside.push({piece:g,why:t.why,...m===void 0?{}:{genome:m}});return c.parts=Pt([...h,...d]),c.parts.length===0&&(r.sequences=r.sequences.filter(g=>g!==c)),r}case"restore":{const c=r.aside.findIndex(({piece:h})=>h.sequence===t.sequence&&h.start===t.start&&h.end===t.end);if(c<0)return e;const[l]=r.aside.splice(c,1),u=Xt(on(t.sequence),i);return r.sequences.push({name:u,parts:[{...l.piece,strand:1}]}),r}case"bring":{const c=n.elsewhere?.find(h=>h.name===t.sequence);if(c===void 0||!(c.length>0))return e;const l=h=>h.sequence===c.name;if(r.sequences.some(h=>h.parts.some(f=>!at(f)&&l(f)))||r.aside.some(h=>l(h.piece)))return e;const u=i.has(c.name)?Xt(c.name,i):c.name;return r.sequences.push({name:u,parts:[{id:s.next(c.name),sequence:c.name,start:0,end:c.length,strand:1}]}),r}case"rotate":{const c=Rt(r,t.sequence);if(c===null)return e;const l=Zt(Math.round(t.at),0,Ce(c.parts)),[u,h]=Be(c.parts,l,s);return c.parts=Pt([...h,...u]),r}case"rename":{const c=Rt(r,t.sequence);return c===null||t.name===""||i.has(t.name)&&t.name!==c.name||a.has(t.name)&&Ji(c,n)!==t.name?e:(c.name=t.name,c.named=!0,r)}case"reorder":{const c=new Map(t.names.map((l,u)=>[l,u]));return r.sequences.sort((l,u)=>(c.get(l.name)??1/0)-(c.get(u.name)??1/0)),r}case"place":{const c=Rt(r,t.sequence);if(c===null)return e;const[l,u]=En(c,t.from,t.to);if(u===l)return e;const h=r.sequences,f=h.indexOf(c),d=t.before===null?h.length:h.findIndex(A=>A.name===t.before),[m,g,w]=In(c.parts,l,u,s),p=Pt(t.strand===1?g:tn(g)),b=Pt([...m,...w]);if(b.every(A=>at(A))){c.parts=p,h.splice(f,1);const A=d<0?h.length:d>f?d-1:d;return h.splice(A,0,c),r}c.parts=b,a.has(c.name)&&(i.delete(c.name),c.name=Xt(on(c.name),i),i.add(c.name));const y=Xt(on(c.name),i);return i.add(y),h.splice(d<0?h.length:d,0,{name:y,parts:p}),r}case"layout":return ou(t,n,s)}}function ou(e,t,n){const s=us(t),o=new Map,r=(u,h,f)=>{const d=o.get(u)??[];d.push([h,f]),o.set(u,d)},i=(u,h,f)=>{const d=s.get(u);if(d===void 0)return null;const m=Zt(Math.round(h),0,d),g=Zt(Math.round(f),0,d);return g>m?[m,g]:null},a=new Set,c=[];for(const u of Array.isArray(e.sequences)?e.sequences:[]){if(u===null||typeof u!="object"||!Array.isArray(u.parts))continue;const h=[];for(const m of u.parts){if(m===null||typeof m!="object")continue;if("gap"in m){typeof m.gap=="number"&&m.gap>0&&h.push({gap:Math.round(m.gap)});continue}if(typeof m.sequence!="string"||typeof m.start!="number"||typeof m.end!="number"||m.strand!==1&&m.strand!==-1)continue;const g=i(m.sequence,m.start,m.end);g!==null&&(r(m.sequence,g[0],g[1]),h.push({id:n.next(m.sequence),sequence:m.sequence,start:g[0],end:g[1],strand:m.strand}))}for(;h.length>0&&at(h[0]);)h.shift();for(;h.length>0&&at(h[h.length-1]);)h.pop();if(h.length===0)continue;const f=typeof u.name=="string"?u.name:"",d=f!==""&&!a.has(f)?f:Xt(f===""?"seq":f,a);a.add(d),c.push({name:d,parts:Pt(h),...u.circular===!0?{circular:!0}:{}})}const l=[];for(const u of Array.isArray(e.aside)?e.aside:[]){if(u===null||typeof u!="object"||typeof u.sequence!="string"||!Jl.includes(u.why))continue;const h=i(u.sequence,u.start,u.end);if(h===null)continue;r(u.sequence,h[0],h[1]);const f=typeof u.genome=="string"&&u.genome!==""?u.genome:void 0;l.push({piece:{id:n.next(u.sequence),sequence:u.sequence,start:h[0],end:h[1],strand:1},why:u.why,...f===void 0?{}:{genome:f}})}for(let u=0;u<t.names.length;u++){const h=t.names[u],f=(o.get(h)??[]).sort((m,g)=>m[0]-g[0]);let d=0;for(const[m,g]of f)m>d&&l.push({piece:{id:n.next(h),sequence:h,start:d,end:m,strand:1},why:"unplaced"}),d=Math.max(d,g);d<t.lengths[u]&&l.push({piece:{id:n.next(h),sequence:h,start:d,end:t.lengths[u],strand:1},why:"unplaced"})}return{sequences:c,aside:l}}function on(e){return e.replace(/_e\d+$/,"")}function fs(e,t){let n=0,s=null;for(const i of e.parts){if(at(i)||i.strand!==1||i.start!==n||s!==null&&i.sequence!==s)return!1;s=i.sequence,n=i.end}if(s===null)return!1;const o=t.names.indexOf(s);if(o>=0)return n===t.lengths[o];const r=t.elsewhere?.find(i=>i.name===s);return r!==void 0&&n===r.length}function ru(e,t){const n=new Set(us(t).keys()),s=new Set(e.sequences.map(o=>o.name));for(const o of e.sequences)n.has(o.name)&&!fs(o,t)&&(s.delete(o.name),o.name=Xt(on(o.name),s),s.add(o.name));for(const o of e.sequences){if(o.named===!0)continue;const r=Ji(o,t);r!==null&&o.name!==r&&!s.has(r)&&(s.delete(o.name),o.name=r,s.add(r))}return e}function Ji(e,t){if(!fs(e,t))return null;const n=e.parts[0];return at(n)?null:n.sequence}class pn{original;sequences;aside;offsets=new Map;byOriginal=new Map;constructor(t,n){this.original=t,this.sequences=n.sequences,this.aside=n.aside;for(const s of n.sequences){const o=[];let r=0;for(const i of s.parts){if(o.push(r),!at(i)){const a=this.byOriginal.get(i.sequence)??[];a.push({sequence:s.name,offset:r,piece:i}),this.byOriginal.set(i.sequence,a)}r+=hs(i)}o.push(r),this.offsets.set(s.name,o)}for(const s of this.byOriginal.values())s.sort((o,r)=>o.piece.start-r.piece.start)}static of(t){const n=new eu;let s=nu(t.original);const o=Zt(t.cursor,0,t.history.length);for(let r=0;r<o;r++)s=ru(su(s,t.history[r].step,t.original,n),t.original);return new pn(t.original,s)}get isIdentity(){return this.aside.length===0&&this.sequences.length===this.original.names.length&&this.sequences.every((t,n)=>t.name===this.original.names[n]&&fs(t,this.original))}sequence(t){return this.sequences.find(n=>n.name===t)??null}lengthOf(t){const n=this.offsets.get(t);return n===void 0?null:n[n.length-1]}contigs(){return this.sequences.map(t=>({name:t.name,length:this.lengthOf(t.name)??0}))}toOriginal(t,n){const s=this.sequence(t),o=this.offsets.get(t);if(s===null||o===void 0)return null;const r=iu(o,n);if(r<0)return null;const i=s.parts[r];if(at(i))return null;const a=n-o[r];return i.strand===1?{sequence:i.sequence,bp:i.start+a,strand:1}:{sequence:i.sequence,bp:i.end-1-a,strand:-1}}toEdited(t,n){const s=[];for(const o of this.landings(t)){const r=o.piece;n<r.start||n>=r.end||s.push(r.strand===1?{sequence:o.sequence,bp:o.offset+(n-r.start),strand:1}:{sequence:o.sequence,bp:o.offset+(r.end-1-n),strand:-1})}return s}landings(t){return this.byOriginal.get(t)??[]}piecesIn(t,n,s){const o=this.sequence(t),r=this.offsets.get(t);if(o===null||r===void 0)return[];const i=[];for(let a=0;a<o.parts.length;a++){const c=o.parts[a],l=r[a],u=r[a+1];if(at(c)||u<=n||l>=s)continue;const h=Math.max(n,l)-l,f=Math.min(s,u)-l,d=c.strand===1?{...c,start:c.start+h,end:c.start+f}:{...c,start:c.end-f,end:c.end-h};i.push({offset:l+h,piece:d})}return i}junctions(){const t=[];for(const n of this.sequences){const s=this.offsets.get(n.name)??[];for(let o=1;o<n.parts.length;o++)t.push({sequence:n.name,at:s[o]})}return t}}function iu(e,t){if(t<0||t>=e[e.length-1])return-1;let n=0,s=e.length-2;for(;n<=s;){const o=n+s>>1;if(t<e[o])s=o-1;else if(t>=e[o+1])n=o+1;else return o}return-1}function au(e){const t=JSON.stringify(e.history.slice(0,e.cursor).map(s=>s.step));let n=2166136261;for(let s=0;s<t.length;s++)n^=t.charCodeAt(s),n=Math.imul(n,16777619);return`${e.cursor}:${(n>>>0).toString(36)}`}function cu(e,t,n){const s=e.original;if(s.genome!==void 0){const o=new Map(t.map((r,i)=>[r,n[i]]));for(const[r,i]of us(s)){const a=o.get(r);if(a===void 0)return`the edit names ${r}, which this file does not have`;if(a!==i)return`${r} is ${i} bp in the edit and ${a} bp here`}return null}if(s.names.length!==t.length)return`the edit was made on ${s.names.length} sequences and this file has ${t.length}`;for(let o=0;o<t.length;o++){if(s.names[o]!==t[o])return`sequence ${o+1} is ${s.names[o]} in the edit and ${t[o]} here`;if(s.lengths[o]!==n[o])return`${t[o]} is ${s.lengths[o]} bp in the edit and ${n[o]} bp here`}return null}const lu=64;class bo{names;lengths;chromOffset;toOriginal;landingStart;landings;originalBins;constructor(t){this.names=t.names,this.lengths=t.lengths,this.chromOffset=t.chromOffset,this.toOriginal=t.toOriginal,this.originalBins=t.originalBins;const n=new Int32Array(t.originalBins+1);for(const r of t.toOriginal)r>=0&&n[r+1]++;for(let r=0;r<t.originalBins;r++)n[r+1]+=n[r];const s=n.slice(0,t.originalBins),o=new Int32Array(n[t.originalBins]);t.toOriginal.forEach((r,i)=>{r>=0&&(o[s[r]++]=i)}),this.landingStart=n,this.landings=o}get nBins(){return this.toOriginal.length}static of(t,n,s){const o=t.binsize,r=new Map(n.map((u,h)=>[u,h])),i=[],a=[],c=[],l=[0];for(const u of s.sequences){const h=s.lengthOf(u.name)??0,f=Math.ceil(h/o);let d=0;u.parts.forEach((m,g)=>{const w=at(m)?m.gap:m.end-m.start,p=Math.min(f,Math.round(d/o));d+=w;const b=g===u.parts.length-1?f:Math.min(f,Math.round(d/o)),y=Math.max(0,b-p),A=at(m)?void 0:r.get(m.sequence);if(at(m)||A===void 0){for(let R=0;R<y;R++)i.push(-1);return}const[x,E]=t.contigBinExtent(A),S=E-x,v=t.contigLengths[A],I=R=>R>=v?S:Math.max(0,Math.min(S,Math.round(R/o)));let N=I(m.start),B=I(m.end);B<=N&&(N=Math.max(0,Math.min(S-1,Math.floor((m.start+m.end)/2/o))),B=N+1);const z=B-N;for(let R=0;R<y;R++){const P=Math.min(z-1,Math.floor((R+.5)*z/y));i.push(x+(m.strand===1?N+P:B-1-P))}}),a.push(u.name),c.push(h),l.push(i.length)}return new bo({names:a,lengths:Float64Array.from(c),chromOffset:Float64Array.from(l),toOriginal:Int32Array.from(i),originalBins:t.nBins})}originalBands(t){const n=new Uint8Array(this.originalBins);for(const[s,o]of t)for(let r=Math.max(0,s);r<Math.min(this.nBins,o);r++){const i=this.toOriginal[r];i>=0&&(n[i]=1)}return this.bandsOf(n)}windowBands(t,n){const s=([r,i])=>{let a=-1;for(let c=Math.max(0,r);c<Math.min(this.nBins,i);c++)a=Math.max(a,this.toOriginal[c]);return a},o=new Uint8Array(this.originalBins);for(const[[r,i],a]of[[t,s(n)],[n,s(t)]])for(let c=Math.max(0,r);c<Math.min(this.nBins,i);c++){const l=this.toOriginal[c];l>=0&&l<=a&&(o[l]=1)}return this.bandsOf(o)}bandsOf(t){const n=[];let s=-1;for(let o=0;o<=this.originalBins;o++){const r=o<this.originalBins&&t[o]===1;r&&s<0&&(s=o),!r&&s>=0&&(n.push([s,o]),s=-1)}return n}originalRectangles(t,n,s){const o=new Uint8Array(this.originalBins);for(const[[l,u],h]of[[t,1],[n,2]])for(let f=Math.max(0,l);f<Math.min(this.nBins,u);f++){const d=this.toOriginal[f];d>=0&&(o[d]|=h)}const r=[];let i=-1,a=0;for(let l=0;l<=this.originalBins;l++){const u=l<this.originalBins?o[l]:0;u!==0?(i<0&&(i=l,a=0),a|=u):i>=0&&(r.push({extent:[i,l],bits:a}),i=-1)}const c=[];for(let l=0;l<r.length;l++)for(let u=l;u<r.length;u++){const h=r[l].bits,f=r[u].bits;if(h&1&&f&2||h&2&&f&1){if(c.length===s)return null;c.push([r[l].extent,r[u].extent])}}return c}translate(t,n,s,o){s.reset();const{landingStart:r,landings:i}=this,[[a,c],[l,u]]=o??[[0,this.originalBins],[0,this.originalBins]];for(let h=0;h<t.length;h++){const f=t.bin1[h],d=t.bin2[h];if(o!==void 0&&!(f>=a&&f<c&&d>=l&&d<u)&&!(f>=l&&f<u&&d>=a&&d<c))continue;const m=r[f],g=r[f+1];if(m===g)continue;const w=r[d],p=r[d+1];if(w===p)continue;const b=t.count[h];if(f===d&&n){for(let y=m;y<g;y++)for(let A=y;A<g;A++)s.push(i[y],i[A],b,n);continue}for(let y=m;y<g;y++)for(let A=w;A<p;A++)s.push(i[y],i[A],b,n)}return s.chunk()}gather(t,n=0,s=this.nBins){const o=new Float64Array(Math.max(0,s-n));for(let r=n;r<s;r++){const i=this.toOriginal[r];o[r-n]=i>=0&&i<t.length?t[i]:Number.NaN}return o}gatherText(t,n=0,s=this.nBins){const o=[];for(let r=n;r<s;r++){const i=this.toOriginal[r];o.push(i>=0&&i<t.length?t[i]:"")}return o}}class ta{bin1=new Int32Array(1024);bin2=new Int32Array(1024);count=new Float64Array(1024);length=0;reset(){this.length=0}push(t,n,s,o){this.length===this.bin1.length&&this.grow();const r=o&&t>n;this.bin1[this.length]=r?n:t,this.bin2[this.length]=r?t:n,this.count[this.length]=s,this.length++}chunk(){return{bin1:this.bin1,bin2:this.bin2,count:this.count,length:this.length}}grow(){const t=this.bin1.length*2,n=new Int32Array(t);n.set(this.bin1);const s=new Int32Array(t);s.set(this.bin2);const o=new Float64Array(t);o.set(this.count),this.bin1=n,this.bin2=s,this.count=o}}class uu{constructor(t,n,s){this.inner=t,this.lens=n,this.upper=s}buffer=new ta;get nnz(){return this.inner.nnz}get countKind(){return this.inner.countKind}scoreColumns(){return this.inner.scoreColumns()}binOffsets(){const t=this.inner.binOffsets(),n=new Float64Array(this.lens.nBins+1);for(let s=0;s<this.lens.nBins;s++){const o=this.lens.toOriginal[s];n[s+1]=n[s]+(o>=0?t[o+1]-t[o]:0)}return n}async forEachWindow(t,n,s,o,r){const i=this.inner.rectangular===!0?this.lens.originalRectangles(t,n,lu):null;if(i===null){const c=this.upper?this.lens.windowBands(t,n):this.lens.originalBands([t]);return c.length===0?!0:this.inner.forEachBands(c,l=>o(this.lens.translate(l,this.upper,this.buffer)),r)}const a=this.upper?"symmetric-upper":"square";for(const c of i){const[l,u]=c;if(!await this.inner.forEachWindow(l,u,Te(l,u,a),f=>o(this.lens.translate(f,this.upper,this.buffer,c)),r))return!1}return!0}forEachBands(t,n,s){const o=this.lens.originalBands(t);return o.length===0?Promise.resolve(!0):this.inner.forEachBands(o,r=>n(this.lens.translate(r,this.upper,this.buffer)),s)}scanAll(t){return this.inner.scanAll({...t,onChunk:n=>t.onChunk(this.lens.translate(n,this.upper,this.buffer))})}}function hu(e,t,n,s){const o=new Map,r=new Map,i=c=>c.startsWith("bins/"),a=c=>c==="chroms"||c==="contigs";return new Proxy(e,{get(c,l){switch(l){case"attrs":return()=>s;case"datasetLength":return u=>i(u)?t.nBins:u.startsWith("chroms/")||u.startsWith("contigs/")?n.length:c.datasetLength(u);case"readNumeric":return(u,h,f)=>{if(!i(u))return c.readNumeric(u,h,f);let d=o.get(u);return d===void 0&&(d=c.readNumeric(u),o.set(u,d)),t.gather(d,h??0,f??t.nBins)};case"readStrings":return(u,h,f)=>{if(!i(u))return c.readStrings(u,h,f);let d=r.get(u);return d===void 0&&(d=c.readStrings(u),r.set(u,d)),t.gatherText(d,h??0,f??t.nBins)};case"readTable":return(u,h,f,d)=>a(u)?n:c.readTable(u,h,f,d);default:{const u=Reflect.get(c,l,c);return typeof u=="function"?u.bind(c):u}}}})}function fu(e){return De(e.names.length,["name","length"],{name:e.names,length:e.lengths})}function du(e,t,n,s={}){const o=cu(e,t,Array.from(n));if(o!==null)return{refusal:`The edit was made on another assembly: ${o}.`};const r=pn.of(e);return r.isIdentity&&s.always!==!0?null:{assembly:r}}class yo{constructor(t,n,s){this.factor=t,this.fineOffset=n,this.chromOffset=s}static of(t,n){const s=Float64Array.from(t),o=new Float64Array(s.length);for(let r=0;r+1<s.length;r++)o[r+1]=o[r]+Math.ceil((s[r+1]-s[r])/n);return new yo(n,s,o)}get nBins(){return this.chromOffset[this.chromOffset.length-1]??0}get fineBins(){return this.fineOffset[this.fineOffset.length-1]??0}coarseBin(t){if(t>=this.fineBins)return this.nBins;const n=Ko(this.fineOffset,t);return this.chromOffset[n]+Math.floor((t-this.fineOffset[n])/this.factor)}fineBin(t){if(t>=this.nBins)return this.fineBins;const n=Ko(this.chromOffset,t);return this.fineOffset[n]+(t-this.chromOffset[n])*this.factor}toFine(t){return[this.fineBin(t[0]),this.fineBin(t[1])]}toCoarse(t){const n=this.coarseBin(t[0]);return t[1]<=t[0]?[n,n]:[n,this.coarseBin(t[1]-1)+1]}coarseIndex(){const t=new Int32Array(this.fineBins);for(let n=0;n+1<this.fineOffset.length;n++){const s=this.chromOffset[n],o=this.fineOffset[n];for(let r=o;r<this.fineOffset[n+1];r++)t[r]=s+Math.floor((r-o)/this.factor)}return t}}function Ko(e,t){let n=0,s=e.length-1;for(;n<s;){const o=n+s>>>1;e[o]<=t?n=o+1:s=o}return Math.max(0,n-1)}const mu="weight",gu=65536;class wu{constructor(t,n,s){this.inner=t,this.grid=n,this.storageMode=s}index=null;get nnz(){return null}get countKind(){return this.inner.countKind}get rectangular(){return this.inner.rectangular}scoreColumns(){return this.inner.scoreColumns()}binOffsets(){const t=this.inner.binOffsets(),n=new Float64Array(this.grid.nBins+1);for(let s=0;s<=this.grid.nBins;s++)n[s]=t[this.grid.fineBin(s)]??0;return n}async forEachWindow(t,n,s,o,r){const i=this.grid.toFine(t),a=this.grid.toFine(n),c=Te(i,a,this.storageMode),l=new ys(this.coarseIndex(),{rows:t,cols:n,mode:c.mode},o),u=await this.inner.forEachWindow(i,a,c,h=>l.add(h),r);return u&&l.finish(),u}forEachBands(t,n,s){const o=t.map(i=>this.grid.toFine(i)).filter(([i,a])=>a>i);if(o.length===0)return Promise.resolve(!0);const r=new ys(this.coarseIndex(),this.grid.nBins,n);return this.inner.forEachBands(o,i=>r.add(i),s).then(i=>(i&&r.finish(),i))}async scanAll(t){let n=!1;const s=new ys(this.coarseIndex(),this.grid.nBins,o=>{n||t.onChunk(o)===!1&&(n=!0)});await this.inner.scanAll({...t,onChunk:o=>(s.add(o),!n)}),n||s.finish()}coarseIndex(){return this.index??=this.grid.coarseIndex(),this.index}}class ys{constructor(t,n,s){this.coarseOf=t,this.reach=n,this.emit=s,typeof n=="number"?(this.colLo=0,this.colSpan=n,this.rowLo=0,this.sums=new Float64Array(n)):(this.colLo=n.cols[0],this.colSpan=n.cols[1]-n.cols[0],this.rowLo=n.rows[0],this.sums=new Float64Array(this.colSpan+(n.rows[1]-n.rows[0]))),this.stamp=new Int32Array(this.sums.length)}sums;stamp;touched=new Int32Array(256);nTouched=0;row=-1;generation=0;out=new ta;held=0;colLo;colSpan;rowLo;add(t){const{bin1:n,bin2:s,count:o,length:r}=t,i=this.coarseOf,a=typeof this.reach=="number"?null:this.reach;for(let c=0;c<r;c++){const l=i[n[c]],u=i[s[c]];if(l===void 0||u===void 0||a!==null&&!pu(a,l,u))continue;l!==this.row&&this.startRow(l);let h=u-this.colLo;if((h<0||h>=this.colSpan)&&(h=this.colSpan+(u-this.rowLo)),!(h<0||h>=this.sums.length))if(this.stamp[h]!==this.generation){if(this.stamp[h]=this.generation,this.sums[h]=o[c],this.nTouched===this.touched.length){const f=new Int32Array(this.touched.length*2);f.set(this.touched),this.touched=f}this.touched[this.nTouched++]=u}else this.sums[h]+=o[c]}this.held>0&&this.handOn()}finish(){this.closeRow(),this.row=-1,this.held>0&&this.handOn()}startRow(t){this.closeRow(),this.row=t,this.generation++}closeRow(){if(this.nTouched===0)return;const t=this.touched.subarray(0,this.nTouched).sort();for(const n of t){let s=n-this.colLo;(s<0||s>=this.colSpan)&&(s=this.colSpan+(n-this.rowLo)),this.out.push(this.row,n,this.sums[s],!1),this.held++}this.nTouched=0,this.held>=gu&&this.handOn()}handOn(){this.emit(this.out.chunk()),this.out.reset(),this.held=0}}function pu(e,t,n){const{rows:s,cols:o,mode:r}=e;return r!=="transpose"&&t>=s[0]&&t<s[1]&&n>=o[0]&&n<o[1]?!0:r!=="direct"&&n>=s[0]&&n<s[1]&&t>=o[0]&&t<o[1]}function bu(e,t,n){const s=new Map,o=new Map,r=c=>c.startsWith("bins/"),i=c=>{let l=s.get(c);return l===void 0&&(l=yu(c.slice(5),e.readNumeric(c),t),s.set(c,l)),l},a=c=>{let l=o.get(c);if(l===void 0){const u=e.readStrings(c);l=[];for(let h=0;h<t.nBins;h++)l.push(u[t.fineBin(h)]??"");o.set(c,l)}return l};return new Proxy(e,{get(c,l){switch(l){case"attrs":return()=>n;case"datasetLength":return u=>r(u)?t.nBins:c.datasetLength(u);case"readNumeric":return(u,h,f)=>r(u)?i(u).slice(h??0,f??t.nBins):c.readNumeric(u,h,f);case"readStrings":return(u,h,f)=>r(u)?a(u).slice(h??0,f??t.nBins):c.readStrings(u,h,f);default:{const u=Reflect.get(c,l,c);return typeof u=="function"?u.bind(c):u}}}})}function yu(e,t,n){const s=new Float64Array(n.nBins);for(let o=0;o<n.nBins;o++){const r=n.fineBin(o),i=n.fineBin(o+1);if(e==="chrom"||e==="start")s[o]=t[r];else if(e==="end")s[o]=t[i-1];else if(e===mu){let a=0,c=0;for(let l=r;l<i;l++){const u=t[l];Number.isFinite(u)&&u>0&&(a++,c+=1/u)}s[o]=a===0?Number.NaN:a/c}else{let a=0,c=0;for(let l=r;l<i;l++){const u=t[l];Number.isFinite(u)&&(a++,c+=u)}s[o]=a===0?Number.NaN:c/a}}return s}const Au="AGFzbQEAAAABCAFgBH9/f38AAg8BA2VudgZtZW1vcnkCAAIDAgEABAUBcAEBAQYIAX8BQYCIBAsHCQEFZmxveWQAAAq5CQG2CQQJfwJ8FH8EewJAIAIgA04NACABQQFIDQACQCABQQdLDQAgAkEDdCEEIAFBA3QhBSABQQJGIQYgAUEERiEHIAFBBUYhCCABQQZGIQkDQCAAIAIgAWxBA3RqIQogACELIAEhDANAAkAgCyAEaisDACINRAAAAAAAAPB/YQ0AAkAgDSAKKwMAoCIOIAsrAwBjRQ0AIAsgDjkDAAsgAUEBRg0AAkAgDSAKKwMIoCIOIAtBCGoiDysDAGNFDQAgDyAOOQMACyAGDQACQCANIAorAxCgIg4gC0EQaiIPKwMAY0UNACAPIA45AwALIAFBA0YNAAJAIA0gCisDGKAiDiALQRhqIg8rAwBjRQ0AIA8gDjkDAAsgBw0AAkAgDSAKKwMgoCIOIAtBIGoiDysDAGNFDQAgDyAOOQMACyAIDQACQCANIAorAyigIg4gC0EoaiIPKwMAY0UNACAPIA45AwALIAkNACANIAorAzCgIg0gC0EwaiIPKwMAY0UNACAPIA05AwALIAsgBWohCyAMQX9qIgwNAAsgBEEIaiEEIAJBAWoiAiADRw0ADAILCyABIAFBDyABQQ9KGyIEQfj///8HcSILQQFyIgwgASAMShsiDCALayIFIAxBAXEiEGshESALIBByIAxrIRIgACABIARBeGoiC0F4cUEJaiIMIAEgDEobQQN0IgwgC0EDdEFAcSILa2ohEyAAIAIgAWxBA3QiBCAMaiALa2ohFCAAQcAAaiEVIAFBA3QhFkEAIRcgBUEGSSEYIAAgBGoiGUHAAGoiGiEbA0AgFCAWIBdsIgtqIRwgGiALaiEdIAAgAiABbEEDdGohHiAAIR8gFSEgQQAhIQNAAkAgACAhIAFsQQN0aiIIIAJBA3RqKwMAIg5EAAAAAAAA8H9hDQAgFiAhbCEiIA79FCEjQQghBEEAIQUgGyEKICAhD0EAIQwDQCAeIAxBA3QiC2oiDP0AADAhJCAM/QAAICElIAz9AAAQISYgCCALaiILIAv9AAAAICMgDP0AAAD98AH99gH9CwAAIAsgC/0AABAgIyAm/fAB/fYB/QsAECALIAv9AAAgICMgJf3wAf32Af0LACAgCyAL/QAAMCAjICT98AH99gH9CwAwIAoiB0HAAGohCiAPIgZBwABqIQ8gBSIJQQFqIQUgBCILIQwgC0EIaiIEIAFMDQALIAsgAU4NAAJAIBgNAAJAIAAgCUEGdCIMaiAiakHAAGogHCAMak8NACAdIAxqIBMgDGogImpJDQELIAsgEWohCyASIQwDQAJAICMgB/0AAwD98AEiJCAG/QADAP1JIiX9GwBBAXFFDQAgBiAk/SEAOQMACwJAICX9GwJBAXFFDQAgBkEIaiAk/SEBOQMACyAHQRBqIQcgBkEQaiEGIAxBAmoiDA0ACyAQRQ0BCyAZIAtBA3QiDGohBCAfIAxqIQwDQAJAIA4gBCsDAKAiDSAMKwMAY0UNACAMIA05AwALIARBCGohBCAMQQhqIQwgC0EBaiILIAFIDQALCyAfIBZqIR8gICAWaiEgICFBAWoiISABRw0ACyAZIBZqIRkgGyAWaiEbIBdBAWohFyACQQFqIgIgA0cNAAsLCwAwBG5hbWUACwpmbG95ZC53YXNtAQgBAAVmbG95ZAcSAQAPX19zdGFja19wb2ludGVyADgJcHJvZHVjZXJzAQxwcm9jZXNzZWQtYnkBDFVidW50dSBjbGFuZxExOC4xLjMgKDF1YnVudHUxKQA1D3RhcmdldF9mZWF0dXJlcwMrD211dGFibGUtZ2xvYmFscysIc2lnbi1leHQrB3NpbWQxMjg=",Ao=.2,As=3e3,Mu=.05,xu=.995,Su=2e3,Iu=10;function Eu(e,t,n=Ao,s){if(t<2)return null;const o=new Float64Array(t);for(let m=0;m<t;m++){const g=m*t;for(let w=0;w<t;w++)o[w]+=e[g+w]}const r=Tu(o);let i=0;for(let m=0;m<t;m++)r[m]===0&&i++;if(i<2)return null;const a=new Int32Array(i);for(let m=0,g=0;m<t;m++)r[m]===0&&(a[g++]=m);const c=new Float64Array(i*i);for(let m=0;m<i;m++){const g=a[m]*t,w=m*i;for(let p=0;p<i;p++)c[w+p]=e[g+a[p]]}const{rows:l,cols:u}=Cu(c,i),h=new Float64Array(i*i);for(let m=0;m<h.length;m++){const g=c[m];h[m]=g>0?1/Math.pow(g,n):Number.POSITIVE_INFINITY}$u(h,i);const f=-1/n;for(let m=0;m<h.length;m++){const g=h[m];h[m]=Number.isFinite(g)?Math.pow(g,f):0}const d=_u(c,h,i);return{kept:a,scn:c,boosted:d,rows:l,cols:u}}function vu(e,t,n=Ao,s){const o=Eu(e,t,n);if(o===null)return null;const{kept:r,boosted:i,rows:a,cols:c}=o,l=r.length;for(let u=0;u<l;u++){const h=u*l;for(let f=0;f<l;f++){const d=(a[u]*c[f]+a[f]*c[u])/2;i[h+f]=d>0?i[h+f]/d:0}}return{kept:r,counts:i}}function Cu(e,t,n=Iu){const s=new Float64Array(t).fill(1),o=new Float64Array(t).fill(1),r=new Float64Array(t);for(let i=0;i<n;i++){r.fill(0);for(let a=0;a<t;a++){const c=a*t;for(let l=0;l<t;l++)r[l]+=e[c+l]}for(let a=0;a<t;a++){const c=Math.max(1,r[a]);r[a]=c,o[a]/=c}for(let a=0;a<t;a++){const c=a*t;for(let l=0;l<t;l++)e[c+l]/=r[l]}for(let a=0;a<t;a++){const c=a*t;let l=0;for(let h=0;h<t;h++)l+=e[c+h];const u=Math.max(1,l);s[a]/=u;for(let h=0;h<t;h++)e[c+h]/=u}}for(let i=0;i<t;i++)for(let a=i+1;a<t;a++){const c=(e[i*t+a]+e[a*t+i])/2;e[i*t+a]=c,e[a*t+i]=c}return{rows:s,cols:o}}function $u(e,t,n,s="auto"){if(s!=="js"&&Ou(e,t))return"wasm";for(let o=0;o<t;o++){const r=o*t;for(let i=0;i<t;i++){const a=i*t,c=e[a+o];if(c!==Number.POSITIVE_INFINITY)for(let l=0;l<t;l++){const u=c+e[r+l];u<e[a+l]&&(e[a+l]=u)}}}return"js"}let Se;const Ms=131072,Nu=65536,Xo=64;function Bu(){if(Se!==void 0)return Se;Se=null;try{if(typeof WebAssembly>"u")return null;const e=atob(Au),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);WebAssembly.validate(t)&&(Se=new WebAssembly.Module(t))}catch{Se=null}return Se}function Ou(e,t,n){const s=Bu();if(s===null)return!1;let o,r;try{const i=new WebAssembly.Memory({initial:Math.ceil((Ms+e.length*8)/Nu)});o=new WebAssembly.Instance(s,{env:{memory:i}}).exports.floyd,r=new Float64Array(i.buffer,Ms,e.length)}catch{return!1}r.set(e);for(let i=0;i<t;i+=Xo){const a=Math.min(t,i+Xo);o(Ms,t,i,a)}return e.set(r),!0}function ku(e){const t=new Float64Array(e);t[0]=1;for(let a=1;a<e;a++)t[a]=t[a-1]*1.01;const n=[];let s=0;for(let a=0;a<e&&s<e;a++){const c=Math.floor(t[a]);n.push(c),s+=c}const o=n.length-1;n[o]-=s-e,n[o-1]+=n[o],n.length=o;const r=new Int32Array(e);let i=0;for(let a=0;a<n.length;a++)for(let c=0;c<n[a];c++)r[i++]=a;return{window:r,sizes:n}}function Zo(e,t,n){const s=new Float64Array(n.length);let o=0;for(let r=0;r<n.length;r++){let i=0,a=0;for(let c=0;c<n[r];c++,o++){for(let l=0;l+o<t;l++)i+=e[l*t+l+o];a+=t-o}s[r]=a>0?i/a:0}return s}function _u(e,t,n){const{window:s,sizes:o}=ku(n),r=Zo(e,n,o),i=Zo(t,n,o),a=new Float64Array(t);for(let c=0;c<n;c++){const l=s[c],u=i[l]>0?r[l]/i[l]:0;for(let h=c;h<n;h++){const f=(h-c)*n+h,d=h*n+(h-c);a[f]=t[f]*u,a[d]=t[d]*u}}return a}function Tu(e,t=Mu,n=xu,s=Su){const o=e.length,r=new Uint8Array(o),i=[];let a=0;for(let p=0;p<o;p++){const b=e[p];b>0&&i.push(b),b>a&&(a=b)}if(i.length===0)return r.fill(1),r;const c=Math.floor(a)+1,l=c>1?a/(c-1):0,u=p=>{const b=p*l+l/2;let y=0;for(const A of i)y+=Fu((b-A)/s);return y},h=u(-1),f=u(c-1)-h,d=p=>f>0?(u(p)-h)/f:1,m=p=>{let b=0,y=c-1;for(;b<y;){const A=b+y>>>1;d(A)>=p?y=A:b=A+1}return b>0&&Math.abs(d(b-1)-p)<=Math.abs(d(b)-p)?b-1:b},g=m(t),w=m(n);for(let p=0;p<o;p++)(e[p]<g||e[p]>w)&&(r[p]=1);return r}function Fu(e){return .5*zu(-e/Math.SQRT2)}function zu(e){const t=Math.abs(e);let n;if(t<2){let s=t,o=t;for(let r=1;r<200&&(s*=2*t*t/(2*r+1),o+=s,!(s<Math.abs(o)*1e-17));r++);n=1-2/Math.sqrt(Math.PI)*Math.exp(-t*t)*o}else if(t>27)n=0;else{let o=1/t,r=1e300,i=o;for(let a=1;a<300;a++){const c=a/2;o=t+c*o,o===0&&(o=1e-300),r=t+c/r,r===0&&(r=1e-300),o=1/o;const l=r*o;if(i*=l,Math.abs(l-1)<1e-16)break}n=Math.exp(-t*t)/Math.sqrt(Math.PI)*i}return e>=0?n:2-n}const Ru=9007199254740992;function Jo(e,t){return e<<t|e>>>32-t}function tr(e){return e=Math.imul(e^e>>>16,2246822507),e=Math.imul(e^e>>>13,3266489909),(e^e>>>16)>>>0}function ea(...e){let t=2166136261;for(const n of e){const s=Number.isFinite(n)?Math.trunc(n):0,o=s>>>0,r=Math.floor(s/4294967296)>>>0;t=tr((t^o)+2654435769),t=tr((t^r)+2135587861)}return t}class na{s0;s1;s2;s3;constructor(t){let n=t|0;const s=()=>{n=n+2654435769|0;let o=n^n>>>16;return o=Math.imul(o,569420461),o^=o>>>15,o=Math.imul(o,1935289751),(o^o>>>15)>>>0};this.s0=s(),this.s1=s(),this.s2=s(),this.s3=s(),(this.s0|this.s1|this.s2|this.s3)===0&&(this.s0=1)}nextUint32(){let t=this.s0,n=this.s1,s=this.s2,o=this.s3;const r=Math.imul(Jo(Math.imul(n,5),7),9)>>>0,i=n<<9;return s^=t,o^=n,n^=s,t^=o,s^=i,o=Jo(o,11),this.s0=t,this.s1=n,this.s2=s,this.s3=o,r}nextDouble(){const t=this.nextUint32()>>>5,n=this.nextUint32()>>>6;return(t*67108864+n)/Ru}interval(t){if(t<=0)return 0;if(t<=4294967295){let n=t;for(n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16;;){const s=(this.nextUint32()&n)>>>0;if(s<=t)return s}}return Math.floor(this.nextDouble()*(t+1))}}function sa(e,t,n){if(!(t>0)||!(n>0))return 0;if(n>=1)return t;if(n<=.5)return n*t<=30?er(e,t,n):nr(e,t,n);const s=1-n;return t-(s*t<=30?er(e,t,s):nr(e,t,s))}function er(e,t,n){const s=1-n,o=Math.exp(t*Math.log1p(-n)),r=t*n,i=Math.min(t,Math.floor(r+10*Math.sqrt(r*s+1)));let a=0,c=o,l=e.nextDouble();for(;l>c;)a++,a>i?(a=0,c=o,l=e.nextDouble()):(l-=c,c=(t-a+1)*n*c/(a*s));return a}function vn(e){const t=e*e;return(13680-(462-(132-(99-140/t)/t)/t)/t)/e/166320}function nr(e,t,n){const s=Math.min(n,1-n),o=1-s,r=t*s+s,i=Math.floor(r),a=Math.floor(2.195*Math.sqrt(t*s*o)-4.6*o)+.5,c=i+.5,l=c-a,u=c+a,h=.134+20.5/(15.3+i);let f=(r-l)/(r-l*s);const d=f*(1+f/2);f=(u-r)/(u*o);const m=f*(1+f/2),g=a*(1+2*h),w=g+h/d,p=w+h/m,b=t*s*o,y=A=>n>.5?t-A:A;for(;;){const A=e.nextDouble()*p;let x=e.nextDouble(),E;if(A<=a)return y(Math.floor(c-a*x+A));if(A<=g){const j=l+(A-a)/h;if(x=x*h+1-Math.abs(i-j+.5)/a,x>1)continue;E=Math.floor(j)}else if(A<=w){if(E=Math.floor(l+Math.log(x)/d),E<0||x===0)continue;x=x*(A-g)*d}else{if(E=Math.floor(u-Math.log(x)/m),E>t||x===0)continue;x=x*(A-w)*m}const S=Math.abs(E-i);if(!(S>20&&S<b/2-1)){const j=s/o,W=j*(t+1);let J=1;if(i<E)for(let Z=i+1;Z<=E;Z++)J*=W/Z-j;else if(i>E)for(let Z=E+1;Z<=i;Z++)J/=W/Z-j;if(x>J)continue;return y(E)}const v=S/b*((S*(S/3+.625)+.16666666666666666)/b+.5),I=-S*S/(2*b),N=Math.log(x);if(N<I-v)return y(E);if(N>I+v)continue;const B=E+1,z=i+1,R=t+1-i,P=t-E+1,L=c*Math.log(z/B)+(t-i+.5)*Math.log(R/P)+(E-i)*Math.log(P*s/(B*o))+vn(z)+vn(R)+vn(B)+vn(P);if(!(N>L))return y(E)}}const Pu=(()=>{const e=new Float64Array(126);for(let t=2;t<126;t++)e[t]=e[t-1]+Math.log(t);return e})(),Lu=.9189385332046728;function oe(e){return e<126?Pu[e]:(e+.5)*Math.log(e)-e+(Lu+1/e*(1/12-1/(360*e*e)))}function oa(e,t,n,s){if(!(s>0)||!(t>0))return 0;if(!(n>0))return Math.min(s,t);const o=t+n;return s>=o?t:s>=10&&s<=o-10?Hu(e,t,n,s):Du(e,t,n,s)}function Du(e,t,n,s){const o=t+n,r=Math.floor(o/2);let i=s>r?o-s:s,a=o,c=t;for(;i>0&&c>0&&a>c;)a--,e.interval(a)<c&&c--,i--;return a===c&&(c-=i),s>r?c:t-c}const Uu=1.7155277699214135,Gu=.8989161620588988;function Hu(e,t,n,s){const o=t+n,r=Math.min(s,o-s),i=Math.min(t,n),a=Math.max(t,n),c=i/o,l=a/o,h=r*c+.5,f=(o-r)*r*c*l/(o-1),d=Math.sqrt(f+.5),m=Uu*d+Gu,g=Math.floor((r+1)*(i+1)/(o+2)),w=oe(g)+oe(i-g)+oe(r-g)+oe(a-r+g),p=Math.min(Math.min(r,i)+1,Math.floor(h+16*d));let b;for(;;){const y=e.nextDouble(),A=e.nextDouble();if(y===0)continue;const x=h+m*(A-.5)/y;if(x<0||x>=p)continue;b=Math.floor(x);const E=oe(b)+oe(i-b)+oe(r-b)+oe(a-r+b),S=w-E;if(y*(4-y)-3<=S)break;if(!(y*(y-S)>=1)&&2*Math.log(y)<=S)break}return t>n&&(b=r-b),r<s&&(b=t-b),b}const qu=1;function Wu(e,t){return t===e?"none":t<e?"sub":"over"}const ju=81,ra=91,ia=14,Qu=192*1024*1024,Yu=4096,Vu=32,Ku=1e6;function Jt(e,t={}){return new C("unsupported",e,{...t,resample:!0})}function Xu(e){return e>=0&&Number.isInteger(e)}class Wn{constructor(t){this.starts=t}last=0;get count(){return this.starts.length-1}of(t){const n=this.starts,s=this.last;if(t>=n[s]&&t<n[s+1])return s;let o=0,r=n.length-2;for(;o<r;){const i=o+r+1>>>1;n[i]<=t?o=i:r=i-1}return this.last=o,o}touching(t,n){const s=[];if(n<=t)return s;const o=this.of(Math.max(0,t));for(let r=o;r<this.count&&this.starts[r]<n;r++)this.starts[r+1]>this.starts[r]&&s.push(r);return s}}async function sr(e,t,n={}){const s=new Wn(t),o=s.count,r=t[o],i=o<=512?new Float64Array(o*o):null,a=i===null?new Map:null;let c=0,l=null,u=!1;if(await e.scanAll({chunkSize:Ku,...n.pause===void 0?{}:{pause:n.pause},onChunk:w=>{if(n.cancelled?.()===!0)return u=!0,!1;const{bin1:p,bin2:b,count:y,length:A}=w;for(let x=0;x<A;x++){const E=y[x];if(!Xu(E))return l=Jt(`This map stores ${E} where a number of contacts would be, so there are no contacts to draw from it. Resampling reads raw counts — whole numbers, one per contact.`,{value:E}),!1;if(E===0)continue;const S=p[x],v=b[x];if(v<S)return l=Jt("This map stores pixels below its diagonal, so each contact would be drawn twice. Resampling reads upper-triangular files — cooler’s default."),!1;const I=s.of(S),N=v<t[I+1]?I:s.of(v);c++,i!==null?i[I*o+N]+=E:a.set(I*o+N,(a.get(I*o+N)??0)+E)}return!0},onProgress:n.onProgress}),l!==null)throw l;if(u)throw new DOMException("The census was cancelled.","AbortError");const h=[];if(i!==null)for(let w=0;w<i.length;w++)i[w]>0&&h.push(w);else{for(const w of a.keys())h.push(w);h.sort((w,p)=>w-p)}const f=new Int32Array(h.length),d=new Int32Array(h.length),m=new Float64Array(h.length);let g=0;for(let w=0;w<h.length;w++){const p=h[w];f[w]=Math.floor(p/o),d[w]=p-f[w]*o,m[w]=i!==null?i[p]:a.get(p),g+=m[w]}return{total:g,nnz:c,sequences:o,nBins:r,a:f,b:d,sum:m}}function Zu(e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw Jt(`${e} is not a number of contacts: it must be a positive whole number.`,{contacts:e});if(e>Number.MAX_SAFE_INTEGER)throw Jt(`${e} contacts is past what can be counted exactly here (2⁵³).`,{contacts:e});return e}function Ju(e,t,n,s){const o=Zu(t.contacts),r=e.total;if(!(r>0))throw Jt("This map holds no contacts, so there is nothing to draw from it.",{total:r});const i=t.seed??qu,a=t.alpha??Ao,c=Wu(r,o),l=new Map,u={mode:c,contacts:o,total:r,seed:i,alpha:a,shares:l,weightScale:Math.sqrt(r/o)};if(c==="none")return u;const h=new na(ea(i,ju,c==="sub"?ra:ia)),f=e.sum.length;if(c==="sub"){let g=o,w=r;for(let p=0;p<f&&g>0;p++){const b=e.sum[p],y=oa(h,b,w-b,g);y>0&&l.set(e.a[p]*e.sequences+e.b[p],y),g-=y,w-=b}return u}if(!(a>0))throw Jt(`Boost-HiC’s alpha must be above zero; ${a} was given.`,{alpha:a});for(let g=0;g<f;g++){const w=e.a[g];if(e.b[g]!==w)continue;const p=n[w+1]-n[w];if(p>As){const b=s?.[w]??`sequence ${w+1}`;throw Jt(`${b} is ${p.toLocaleString("en-US")} bins at this resolution, and Boost-HiC — which oversamples it — walks every path between them: at most ${As.toLocaleString("en-US")}. Open a coarser resolution to oversample this map.`,{sequence:b,bins:p,limit:As})}}let d=o-r,m=r;for(let g=0;g<f&&d>0;g++){const w=e.sum[g],p=g===f-1?d:sa(h,d,Math.min(1,w/m));p>0&&l.set(e.a[g]*e.sequences+e.b[g],p),d-=p,m-=w}return u}class or{bin1;bin2;count;length=0;constructor(t=1024){this.bin1=new Int32Array(t),this.bin2=new Int32Array(t),this.count=new Float64Array(t)}push(t,n,s){this.length===this.bin1.length&&this.grow(this.length*2),this.bin1[this.length]=t,this.bin2[this.length]=n,this.count[this.length]=s,this.length++}grow(t){const n=new Int32Array(t),s=new Int32Array(t),o=new Float64Array(t);n.set(this.bin1.subarray(0,this.length)),s.set(this.bin2.subarray(0,this.length)),o.set(this.count.subarray(0,this.length)),this.bin1=n,this.bin2=s,this.count=o}}function th(e,t,n,s,o){let r=t,i=n;const{bin1:a,bin2:c,count:l}=e;for(let u=0;u<l.length&&r>0;u++){const h=l[u];if(h===0)continue;let f;if(r===i)f=h,i-=h;else if(h<=Vu){f=0;for(let d=0;d<h;d++)s.nextDouble()*i<r-f&&f++,i--}else f=oa(s,h,i-h,r),i-=h;r-=f,f>0&&o.push(a[u],c[u],f)}}function aa(e,t,n){const s=e.length,o=new Float64Array(s);if(t<=0||s===0)return o;const r=new Float64Array(s+1);let i=-1;for(let c=s-1;c>=0;c--){const l=e[c]>0?e[c]:0;r[c]=r[c+1]+l,l>0&&i<0&&(i=c)}if(i<0)return o;let a=t;for(let c=0;c<s&&a>0;c++){const l=e[c];if(!(l>0))continue;const u=c===i?a:sa(n,a,Math.min(1,l/r[c]));o[c]=u,a-=u}return o}function eh(e,t,n,s){const o=aa(e.count,t,n),{bin1:r,bin2:i,count:a}=e;for(let c=0;c<a.length;c++){const l=a[c]+o[c];l>0&&s.push(r[c],i[c],l)}}function nh(e,t,n){const s=new Float64Array(n*n),{bin1:o,bin2:r,count:i}=e;for(let a=0;a<i.length;a++){const c=o[a]-t,l=r[a]-t;s[c*n+l]+=i[a],c!==l&&(s[l*n+c]+=i[a])}return s}function sh(e,t,n,s,o,r,i){const a=nh(e,t,n),c=vu(new Float64Array(a),n,o),l=n*(n+1)/2,u=new Float64Array(l);let h=0;for(let d=0;d<n;d++)for(let m=d;m<n;m++)u[h++]=a[d*n+m];if(c!==null){const{kept:d,counts:m}=c,g=d.length;let w=0,p=0;for(let y=0;y<g;y++)for(let A=y;A<g;A++)w+=a[d[y]*n+d[A]],p+=m[y*g+A];const b=p>0?w/p:0;for(let y=0;y<g;y++){const A=d[y],x=A*n-A*(A-1)/2-A;for(let E=y;E<g;E++)u[x+d[E]]=m[y*g+E]*b}}const f=aa(u,s,r);h=0;for(let d=0;d<n;d++)for(let m=d;m<n;m++,h++){const g=a[d*n+m]+f[h];g>0&&i.push(t+d,t+m,g)}}class oh{constructor(t,n,s,o){this.inner=t,this.geometry=n,this.spec=s,this.index=new Wn(n.starts),this.census=o}countKind="i";index;census;planned=null;plan=null;bands=new Map;bytes=0;get nnz(){return this.inner.nnz}get weightScale(){return this.plan?.weightScale??1}ready(){return this.planned??=this.census.then(t=>{if(t.nBins!==this.geometry.starts[this.index.count])throw Jt("This census was taken over another map.",{bins:t.nBins,nBins:this.geometry.starts[this.index.count]});const n=Ju(t,this.spec,this.geometry.starts,this.geometry.names);return this.plan=n,n}),this.planned}scoreColumns(){return["count"]}binOffsets(){return this.inner.binOffsets()}async forEachWindow(t,n,s,o,r={}){return(await this.ready()).mode==="none"?this.inner.forEachWindow(t,n,s,o,r):this.walk([[s.span[0],s.span[1]]],o,r)}async forEachBands(t,n,s={}){return(await this.ready()).mode==="none"?this.inner.forEachBands(t,n,s):this.walk(t,n,s)}async scanAll(t){if((await this.ready()).mode==="none")return this.inner.scanAll(t);const n=this.geometry.starts[this.index.count];let s=!1;await this.walk([[0,n]],o=>{s||t.onChunk(o)===!1&&(s=!0)},{cancelled:()=>s,onProgress:(o,r)=>t.onProgress?.(o,r)})}async walk(t,n,s){if(s.value!==void 0&&s.value!=="count")throw Jt(`A resampled map is drawn from its contacts, and “${s.value}” is not a count of them. Read the counts, or balance them, while the map is resampled.`,{value:s.value});const o=await this.ready(),r=rh(t),i=[];for(const[l,u]of r)for(const h of this.index.touching(l,u))i[i.length-1]!==h&&i.push(h);const a=[...new Set(i)].sort((l,u)=>l-u);let c=0;for(let l=0;l<a.length;){if(s.cancelled?.()===!0)return!1;const u=[];let h=0;for(;l<a.length;){const d=a[l],m=this.geometry.starts[d+1]-this.geometry.starts[d];if(u.length>0&&h+m>Yu)break;u.push(d),h+=m,l++}const f=u.filter(d=>!this.bands.has(d));if(f.length>0&&await this.draw(f,o,s)===null)return!1;for(const d of u){const m=this.bands.get(d);this.touch(d);for(const[g,w]of r){const p=Math.max(g,m.from)-m.from,b=Math.min(w,m.from+m.rows.length-1)-m.from;if(b<=p)continue;const y=m.rows[p],A=m.rows[b];A>y&&n({bin1:m.bin1.subarray(y,A),bin2:m.bin2.subarray(y,A),count:m.count.subarray(y,A),length:A-y})}c++,s.onProgress?.(c,a.length)}this.evict(new Set(u)),await St()}return!0}async draw(t,n,s){const o=this.geometry.starts,r=new Map;for(const u of t)r.set(u,new or);const i=new Wn(o);let a=-1,c;if(!await this.inner.forEachBands(t.map(u=>[o[u],o[u+1]]),u=>{const{bin1:h,bin2:f,count:d,length:m}=u;for(let g=0;g<m;g++){if(d[g]===0)continue;const w=i.of(h[g]);w!==a&&(a=w,c=r.get(w)),c?.push(h[g],f[g],d[g])}},...s.cancelled===void 0?[]:[{cancelled:s.cancelled}]))return null;for(const u of t){if(this.store(this.drawBand(u,r.get(u),n)),r.delete(u),s.cancelled?.()===!0)return null;await St()}return!0}drawBand(t,n,s){const o=this.geometry.starts,r=o[t],i=o[t+1],a=this.index.count,c=n.length,l=ih(n),u=new Wn(o),h=new Int32Array(c),f=new Map,d=[];let m=-1,g=-1;for(let S=0;S<c;S++){const v=u.of(n.bin2[l[S]]);if(v!==m){let I=f.get(v);I===void 0&&(I=d.length,f.set(v,I),d.push(v)),m=v,g=I}h[S]=g}const w=new Int32Array(d.length+1);for(let S=0;S<c;S++)w[h[S]+1]++;for(let S=0;S<d.length;S++)w[S+1]+=w[S];const p=w.slice(0,d.length),b=new Int32Array(c),y=new Int32Array(c),A=new Float64Array(c);for(let S=0;S<c;S++){const v=l[S],I=p[h[S]]++;b[I]=n.bin1[v],y[I]=n.bin2[v],A[I]=n.count[v]}const x=new or(Math.max(1024,s.mode==="sub"?Math.ceil(c/2):c)),E=d.map((S,v)=>({b:S,local:v})).sort((S,v)=>S.b-v.b);for(const{b:S,local:v}of E){const I=w[v],N=w[v+1],B={bin1:b.subarray(I,N),bin2:y.subarray(I,N),count:A.subarray(I,N)};if(s.mode==="none"){for(let P=0;P<B.count.length;P++)x.push(B.bin1[P],B.bin2[P],B.count[P]);continue}const z=s.shares.get(t*a+S)??0,R=new na(ea(s.seed,s.mode==="sub"?ra:ia,t,S));if(s.mode==="sub"){let P=0;for(let L=0;L<B.count.length;L++)P+=B.count[L];th(B,z,P,R,x)}else S===t?sh(B,r,i-r,z,s.alpha,R,x):eh(B,z,R,x)}return ah(t,r,i,x)}store(t){this.bands.set(t.sequence,t),this.bytes+=t.bytes}touch(t){const n=this.bands.get(t);n!==void 0&&(this.bands.delete(t),this.bands.set(t,n))}evict(t){for(const[n,s]of this.bands){if(this.bytes<=Qu)return;t.has(n)||(this.bands.delete(n),this.bytes-=s.bytes)}}}function rh(e){const t=e.filter(([s,o])=>o>s).map(([s,o])=>[s,o]);t.sort((s,o)=>s[0]-o[0]);const n=[];for(const s of t){const o=n[n.length-1];o!==void 0&&s[0]<=o[1]?o[1]=Math.max(o[1],s[1]):n.push(s)}return n}function ih(e){const t=e.length,n=new Int32Array(t);let s=!0;for(let i=0;i<t;i++)n[i]=i,i>0&&(e.bin1[i]<e.bin1[i-1]||e.bin1[i]===e.bin1[i-1]&&e.bin2[i]<e.bin2[i-1])&&(s=!1);if(s)return n;const{bin1:o,bin2:r}=e;return n.sort((i,a)=>o[i]-o[a]||r[i]-r[a])}function ah(e,t,n,s){const o=n-t,r=new Int32Array(o+1);for(let u=0;u<s.length;u++)r[s.bin1[u]-t+1]++;for(let u=0;u<o;u++)r[u+1]+=r[u];const i=r.slice(0,o),a=new Int32Array(s.length),c=new Int32Array(s.length),l=new Float64Array(s.length);for(let u=0;u<s.length;u++){const h=i[s.bin1[u]-t]++;a[h]=s.bin1[u],c[h]=s.bin2[u],l[h]=s.count[u]}return{sequence:e,from:t,bin1:a,bin2:c,count:l,rows:r,bytes:s.length*16+r.length*4}}class rn{constructor(t,n,s,o,r){this.nBins=o,this.countKind=r,this.cells=s.map(i=>({name:i,store:new Vi(t.at(ts(n,i)),o,r)}))}countKind;cells;offsets=null;onCells=null;get names(){return this.cells.map(t=>t.name)}get nnz(){let t=0;for(const n of this.cells)t+=n.store.nnz;return t}scoreColumns(){const[t,...n]=this.cells;if(t===void 0)return[ee];let s=t.store.scoreColumns();for(const o of n){const r=new Set(o.store.scoreColumns());s=s.filter(i=>r.has(i))}return s.length>0?s:[ee]}binOffsets(){if(this.offsets!==null)return this.offsets;const t=new Float64Array(this.nBins+1);for(const n of this.cells){const s=n.store.binOffsets(),o=Math.min(t.length,s.length);for(let r=0;r<o;r++)t[r]+=s[r]}return this.offsets=t,t}async forEachWindow(t,n,s,o,r={}){let i=0;for(const a of this.cells){if(!await a.store.forEachWindow(t,n,s,o,r))return!1;await St(),this.onCells?.(++i,this.cells.length)}return!0}async forEachBands(t,n,s={}){let o=0;for(const r of this.cells){if(!await r.store.forEachBands(t,n,s))return!1;await St(),this.onCells?.(++o,this.cells.length)}return!0}async scanAll(t){const n=this.nnz;let s=0,o=!1;for(const r of this.cells){if(o)return;const i=s;await r.store.scanAll({...t.chunkSize===void 0?{}:{chunkSize:t.chunkSize},...t.storedRows===void 0?{}:{storedRows:t.storedRows},onChunk:a=>{const c=t.onChunk(a);return c===!1&&(o=!0),c},onProgress:a=>{s=i+a,t.onProgress?.(s,n)}}),s=i+r.store.nnz,t.onProgress?.(Math.min(s,n),n)}}async scanPerCell(t){const n=this.nnz;let s=0;for(let o=0;o<this.cells.length;o++){const r=this.cells[o];t.onCell?.(o,r.name);const i=s;let a=!1;if(await r.store.scanAll({...t.chunkSize===void 0?{}:{chunkSize:t.chunkSize},onChunk:c=>{const l=t.onChunk(o,c);return l===!1&&(a=!0),l},onProgress:c=>{s=i+c,t.onProgress?.(s,n)}}),a)return;s=i+r.store.nnz,t.onProgress?.(Math.min(s,n),n),await St()}}}function rr(e,t){if(t===null||t.length===0)return[...e];const n=new Set(e),s=t.filter(r=>!n.has(r));if(s.length>0)throw new C("cell-not-found",`This file has no ${s.length===1?"cell":"cells"} ${Dt(s.slice(0,8))}. It carries ${e.length} ${e.length===1?"cell":"cells"}, starting ${Dt(e.slice(0,3))}.`,{missing:s,available:e.length});const o=new Set(t);return e.filter(r=>o.has(r))}function xt(e,t){const n=ua(e),s=ha(n,t);if(s===null)return n;throw new C("format",`The ${t.field} of this ${t.format} reads ${Zs(e)}, ${s.reason}. `+Fe,{format:t.format,field:t.field,value:typeof e=="bigint"?e.toString():e,ceiling:t.ceiling,...t.available===void 0?{}:{available:t.available},...s.most===void 0?{}:{most:s.most}})}function ch(e,t){return ha(ua(e),t)===null}function ds(e,t,n){const s={format:n.format,field:n.field,offset:e,length:t,size:n.size};if(!Xs(e)||!Xs(t))throw new C("format",`The ${n.field} of this ${n.format} points at ${Zs(t)} bytes from byte ${Zs(e)}, which is not a place in a file. ${Fe}`,s);if(n.ceiling!==void 0&&t>n.ceiling)throw new C("format",`The ${n.field} of this ${n.format} is ${At.int(t)} bytes long, more than the ${At.int(n.ceiling)} any real one holds. ${Fe}`,{...s,ceiling:n.ceiling});if(e+t>n.size)throw new C("format",`The ${n.field} of this ${n.format} points at bytes ${At.int(e)} to ${At.int(e+t)}, past the end of a file of ${At.int(n.size)}. ${Fe}`,s)}const ir=65536,Mo=2**29;async function xo(e,t){if(typeof DecompressionStream>"u")throw new C("unsupported",`Reading a ${t.format} needs DecompressionStream, which this runtime does not have. Every browser since 2023 has it; a very old one does not.`,{format:t.format});const n=new DecompressionStream(t.encoding),s=n.writable.getWriter(),o=n.readable.getReader(),r=[];let i=0,a=!1;const c=(async()=>{for(;;){const{done:g,value:w}=await o.read();if(g)return;if(i+=w.byteLength,i>t.maxBytes){a=!0,await o.cancel();return}r.push(w)}})(),l=(async()=>{for(let g=0;g<e.byteLength;g+=ir){if(a)return;const w=e.subarray(g,Math.min(g+ir,e.byteLength));await s.write(w)}a||await s.close()})(),[u,h]=await Promise.allSettled([c,l]);if(a)throw la(t,t.maxBytes,e.byteLength);const f=u.status==="rejected"?u.reason:h.status==="rejected"?h.reason:null;if(f!==null){const g=f instanceof Error?f.message:String(f);throw new C("format",`The ${t.field} of this ${t.format} does not inflate (${g.replace(/\.$/,"")}). ${Fe}`,{format:t.format,field:t.field})}if(r.length===1)return r[0];const d=new Uint8Array(i);let m=0;for(const g of r)d.set(g,m),m+=g.length;return d}function ca(e,t){return Math.min(t.ceiling,Math.max(t.floor,Math.ceil(e*t.ratio)))}function la(e,t,n){return new C("format",`The ${e.field} of this ${e.format} inflates to more than ${At.bytes(t)}, past what any real one holds. ${Fe}`,{format:e.format,field:e.field,maxBytes:t,compressed:n})}const Fe="The file is truncated, corrupt, or not the format its first bytes claim.";function ua(e){return typeof e=="number"?e:e>=BigInt(Number.MIN_SAFE_INTEGER)&&e<=BigInt(Number.MAX_SAFE_INTEGER)?Number(e):Number.NaN}function Xs(e){return Number.isSafeInteger(e)&&e>=0}function ha(e,t){if(!Xs(e))return{reason:"which is not a count"};if(e>t.ceiling)return{reason:`more than the ${At.int(t.ceiling)} any real one declares`};if(t.available!==void 0){const n=Math.floor(Math.max(0,t.available)/Math.max(1,t.bytesPerItem??1));if(e>n){const s=Math.max(0,t.available);return{reason:`and the ${At.int(s)} byte${s===1?"":"s"} after it could hold at most ${At.int(n)}`,most:n}}}return null}function Zs(e){return typeof e=="bigint"?e.toString():Number.isSafeInteger(e)?At.int(e):String(e)}const ar=[7,8,9],ht=".hic",fa=2**31-1,lh=2**40;class jt extends RangeError{needed;constructor(t){super(`a read needs ${t} bytes of a shorter buffer`),this.name="Truncated",this.needed=t}}class Ue{constructor(t){this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}view;at=0;get position(){return this.at}set position(t){this.at=t}get remaining(){return this.bytes.byteLength-this.at}need(t){if(this.at+t>this.bytes.byteLength)throw new jt(this.at+t)}int8(){this.need(1);const t=this.view.getInt8(this.at);return this.at+=1,t}int16(){this.need(2);const t=this.view.getInt16(this.at,!0);return this.at+=2,t}int32(){this.need(4);const t=this.view.getInt32(this.at,!0);return this.at+=4,t}int64(){this.need(8);const t=this.view.getBigInt64(this.at,!0);return this.at+=8,t>BigInt(Number.MAX_SAFE_INTEGER)||t<BigInt(Number.MIN_SAFE_INTEGER)?Number.NaN:Number(t)}float32(){this.need(4);const t=this.view.getFloat32(this.at,!0);return this.at+=4,t}float64(){this.need(8);const t=this.view.getFloat64(this.at,!0);return this.at+=8,t}string(){const t=this.at,n=this.bytes.indexOf(0,t);if(n<0)throw new jt(Math.max(t,this.bytes.byteLength)+1);const s=new TextDecoder().decode(this.bytes.subarray(t,n));return this.at=n+1,s}skip(t){if(!(t>=0))throw new RangeError(`a cursor cannot skip ${t} bytes`);this.at+=t}}const uh=512*1024;function da(e){return e.length>=4&&e[0]===72&&e[1]===73&&e[2]===67&&e[3]===0}function hh(e){let t=Math.min(uh,e.size);for(;;){const n=e.readBytes(0,t);try{return fh(n,e.size)}catch(s){if(!(s instanceof jt))throw s;if(t>=e.size)throw new C("format",`This .hic ends inside its header, ${e.size.toLocaleString("en-US")} bytes in. The file is truncated, or is not the format its first four bytes claim.`,{size:e.size});t=Math.min(e.size,Math.max(t*4,s.needed))}}}function fh(e,t=e.byteLength){if(!da(e))throw new C("format","This file does not begin with the `.hic` magic bytes.",{});const n=new Ue(e);n.position=4;const s=n.int32();if(!ar.includes(s))throw new C("unsupported",`This is a version ${s} .hic file, and this reader accepts versions ${ar.join(", ")}. Versions below 7 predate the block index this reader navigates by, and a version above the list is a format this build has not seen. Convert it with \`hic2cool\` or re-run Juicer Tools \`pre\`.`,{version:s});const o=n.int64(),r=n.string();let i=null,a=null;s>=9&&(i=n.int64(),a=n.int64());const c=()=>t-n.position,l={},u=xt(n.int32(),{format:ht,field:"header attribute count",ceiling:1e6,available:c(),bytesPerItem:2});for(let g=0;g<u;g++){const w=n.string();l[w]=n.string()}const h=xt(n.int32(),{format:ht,field:"chromosome count",ceiling:1e7,available:c(),bytesPerItem:1+(s>=9?8:4)});xs(h>0,"chromosome count");const f=[];for(let g=0;g<h;g++){const w=n.string(),p=xt(s>=9?n.int64():n.int32(),{format:ht,field:`length of chromosome ${w}`,ceiling:lh});f.push({name:w,length:p})}const d=xt(n.int32(),{format:ht,field:"resolution count",ceiling:1e4,available:c(),bytesPerItem:4});xs(d>0,"resolution count");const m=[];for(let g=0;g<d;g++){const w=n.int32();xs(w>0,"bin size"),m.push(w)}return{version:s,footerPosition:o,genomeId:r,attributes:l,chroms:f,bpResolutions:m,normVectorIndexPosition:i,normVectorIndexLength:a,headerBytes:n.position}}function xs(e,t){if(!e)throw new C("format",`The ${t} in this .hic header is not a plausible number. The file is either truncated or is not the format its first four bytes claim.`,{what:t})}function Js(e,t,n,s){return`${e}/${t}/${n}/${s}`}function dh(e,t){const{version:n,footerPosition:s}=t,o=n>=9?8:4;ds(s,o+4,{format:ht,field:"footer position",size:e.size});const r=e.size-s,i=new Ue(e.readBytes(s,o)),a=xt(n>=9?i.int64():i.int32(),{format:ht,field:"footer length",ceiling:Number.MAX_SAFE_INTEGER,available:r-o}),c={fileSize:e.size,footerPosition:s};let l=Math.min(r,Math.max(a+o+(1<<20),65536));for(;;){const u=e.readBytes(s,l);try{return gh(u,n,o,c)}catch(h){if(!(h instanceof jt))throw h;if(l>=r)throw new C("format",`This .hic ends inside its footer, which begins ${s.toLocaleString("en-US")} bytes in. The file is truncated, or its header does not point at its footer.`,{footerPosition:s,size:e.size});l=Math.min(r,Math.max(l*4,h.needed))}}}const mh=13;function gh(e,t,n,s){const o=new Ue(e);o.position=n;const r=s?.fileSize??e.byteLength,i=s?.footerPosition??0,a=()=>r-(i+o.position),c=new Map,l=xt(o.int32(),{format:ht,field:"master index size",ceiling:1e8,available:a(),bytesPerItem:mh});let u=0;for(let d=0;d<l;d++){const m=o.string(),g=o.int64(),w=o.int32();if(s!==void 0&&(ds(g,w,{format:ht,field:`matrix record for ${m}`,size:s.fileSize}),u+=w,u>s.fileSize))throw new C("format",`The master index of this .hic gives its matrix records ${u.toLocaleString("en-US")} bytes between them by entry ${d+1}, more than the whole file's ${s.fileSize.toLocaleString("en-US")}. The file is corrupt, or not the format its first bytes claim.`,{entries:d+1,bytes:u,size:s.fileSize});c.set(m,{key:m,position:g,size:w})}cr(o,t,!1,a),cr(o,t,!0,a);const h=new Map,f=[];if(a()>=4){const d=o.int32(),m=18+(t>=9?8:4),g={ceiling:1e8,available:a(),bytesPerItem:m};if(ch(d,g)){let w=0;for(let p=0;p<d;p++){const b=o.string(),y=o.int32(),A=o.string(),x=o.int32(),E=o.int64(),S=t>=9?o.int64():o.int32();h.set(Js(b,y,A,x),{type:b,chromIdx:y,unit:A,binSize:x,position:E,nBytes:S}),f.includes(b)||f.push(b),w+=S}s!==void 0&&!(w<=s.fileSize)&&(h.clear(),f.length=0)}}return{masterIndex:c,normVectors:h,normTypes:f}}function cr(e,t,n,s){if(s()<4)return;const o=t>=9?4:8,r=xt(e.int32(),{format:ht,field:`${n?"normalised ":""}expected-value vector count`,ceiling:1e6,available:s(),bytesPerItem:(n?1:0)+1+4+(t>=9?8:4)+4});for(let i=0;i<r;i++){n&&e.string(),e.string(),e.int32();const a=xt(t>=9?e.int64():e.int32(),{format:ht,field:"expected-value vector length",ceiling:fa,available:s(),bytesPerItem:o});e.skip(a*o);const c=xt(e.int32(),{format:ht,field:"expected-value scale factor count",ceiling:1e7,available:s(),bytesPerItem:4+o});e.skip(c*(4+o))}if(e.remaining<0)throw new jt(e.position)}function wh(e,t,n){const s=`${n.type} normalisation vector of chromosome ${n.chromIdx}`,o=t>=9?8:4,r=t>=9?4:8;ds(n.position,n.nBytes,{format:ht,field:s,size:e.size});const i=e.readBytes(n.position,o);if(i.byteLength<o)throw new C("format",`The ${s} begins in the last ${i.byteLength} bytes of this .hic, too few for its length. The file is truncated, or its normalisation index does not point at its vectors.`,{type:n.type,chromIdx:n.chromIdx,position:n.position});const a=new Ue(i),c=xt(t>=9?a.int64():a.int32(),{format:ht,field:`length of the ${s}`,ceiling:fa,available:n.nBytes-o,bytesPerItem:r}),l=e.readBytes(n.position+o,c*r),u=new DataView(l.buffer,l.byteOffset,l.byteLength),h=new Float64Array(c);for(let f=0;f<c;f++){const d=r===4?u.getFloat32(f*4,!0):u.getFloat64(f*8,!0);h[f]=d>0&&Number.isFinite(d)?1/d:Number.NaN}return h}const lr={ratio:64,floor:16<<20,ceiling:1<<30},to=2**26,ph=37,ur=16,jn=2**31-1,Ss=4096;function ms(e,t,n,s){const o=new Ue(e),r=()=>s===void 0?void 0:s-o.position;o.int32(),o.int32();const i=xt(o.int32(),{format:ht,field:"resolution count of a matrix record",ceiling:1e4,available:r(),bytesPerItem:ph});for(let a=0;a<i;a++){const c=o.string();o.int32();const l=o.float32();o.float32(),o.float32(),o.float32();const u=o.int32(),h=o.int32(),f=o.int32(),d=xt(o.int32(),{format:ht,field:"block count of a matrix record",ceiling:jn,available:r(),bytesPerItem:ur});if(c!==t||u!==n){o.skip(d*ur);continue}if(!(h>=1)||!(f>=1))throw new C("format",`This .hic's ${u} bp matrix declares blocks of ${h} bins in ${f} columns, which no block grid has. The file is truncated, corrupt, or not the format its first bytes claim.`,{binSize:u,blockBinCount:h,blockColumnCount:f});const m=new Map;for(let g=0;g<d;g++){const w=o.int32(),p=o.int64(),b=o.int32();m.set(w,{number:w,position:p,size:b})}return{unit:c,binSize:u,blockBinCount:h,blockColumnCount:f,blocks:m,sumCounts:l}}return null}function bh(e,t,n,s,o){if(o>0&&o<t.size){try{return{zoom:ms(e(t.position,o),n,s,t.size),beyondHead:!1}}catch(r){if(!(r instanceof jt))throw r}return{zoom:Pe(e(t.position,t.size),t,n,s),beyondHead:!0}}return{zoom:Pe(e(t.position,t.size),t,n,s),beyondHead:!1}}async function yh(e,t,n,s,o){if(o>0&&o<t.size){try{return{zoom:ms(await e(t.position,o),n,s,t.size),beyondHead:!1}}catch(r){if(!(r instanceof jt))throw r}return{zoom:Pe(await e(t.position,t.size),t,n,s),beyondHead:!0}}return{zoom:Pe(await e(t.position,t.size),t,n,s),beyondHead:!1}}function Pe(e,t,n,s){try{return ms(e,n,s,t.size)}catch(o){throw o instanceof jt?new C("format",`The matrix record for ${t.key} in this .hic ends inside its block index, ${e.byteLength.toLocaleString("en-US")} bytes in. The file is truncated, or its master index does not point at its records.`,{key:t.key,position:t.position,size:t.size}):o}}function Cn(e,t,n){const s=[...e].sort((r,i)=>r.position-i.position),o=[];for(const r of s){const i=o[o.length-1],a=r.position+r.size;if(i!==void 0&&r.position-(i.position+i.length)<=t&&a-i.position<=n){i.length=Math.max(i.length,a-i.position),i.refs.push(r);continue}o.push({position:r.position,length:r.size,refs:[r]})}return o}function hr(e,t,n,s,o){const r=n&&t>=9?xh(e,s,o):Mh(e,n,s,o);let i=0;for(const c of r)i+=Math.max(0,c.r2-c.r1+1)*Math.max(0,c.c2-c.c1+1);if(i>Math.max(Ah,e.blocks.size))return Sh(e,r);const a=new Set;for(const{r1:c,r2:l,c1:u,c2:h}of r)for(let f=c;f<=l;f++)for(let d=u;d<=h;d++)a.add(f*e.blockColumnCount+d);return[...a]}const Ah=1<<20;function Mh(e,t,n,s){const{blockBinCount:o}=e,r=Math.floor(n[0]/o),i=Math.floor(Math.max(n[0],n[1]-1)/o),a=Math.floor(s[0]/o),c=Math.floor(Math.max(s[0],s[1]-1)/o),l=[{r1:a,r2:c,c1:r,c2:i}];return t&&l.push({r1:r,r2:i,c1:a,c2:c}),l}function xh(e,t,n){const{blockBinCount:s}=e,[o,r]=[t[0],Math.max(t[0],t[1]-1)],[i,a]=[n[0],Math.max(n[0],n[1]-1)],c=Math.floor((o+i)/2/s),l=Math.floor((r+a)/2/s)+1,u=Math.floor(Math.log2(1+Math.abs(o-a)/Math.SQRT2/s)),h=Math.floor(Math.log2(1+Math.abs(r-i)/Math.SQRT2/s)),d=o>a&&r<i||r>i&&o<a?0:Math.min(u,h),m=Math.max(u,h)+1;return[{r1:Math.max(0,d),r2:m,c1:Math.max(0,c),c2:l}]}function Sh(e,t){const n=e.blockColumnCount,s=[];for(const o of e.blocks.keys()){const r=Math.floor(o/n),i=o-r*n;t.some(a=>r>=a.r1&&r<=a.r2&&i>=a.c1&&i<=a.c2)&&s.push(o)}return s.sort((o,r)=>o-r)}function Ih(e,t){try{return Eh(e,t)}catch(n){throw n instanceof jt?new C("format",`A block of this .hic ends before its records do, ${e.byteLength.toLocaleString("en-US")} bytes in. The file is truncated, corrupt, or not the format its first bytes claim.`,{bytes:e.byteLength}):n}}function Eh(e,t){const n=new Ue(e),s=n.int32();if(s===0)return{x:new Int32Array(0),y:new Int32Array(0),value:new Float32Array(0),length:0};const o=n.int32(),r=n.int32(),i=n.int8()===0,a=t>8?n.int8()===0:!0,c=t>8?n.int8()===0:!0,l=n.int8();if(l!==1&&l!==2)throw new C("format",`A block of this .hic is in encoding ${l}, and the format has two: 1, a list of rows, and 2, a dense rectangle. The file is corrupt, or was written by a tool this reader has not seen.`,{type:l});const u=i?2:4,h=l===1?(a?2:4)+u:u,f=xt(s,{format:ht,field:"record count of a block",ceiling:to,available:n.remaining,bytesPerItem:h});let d=new Int32Array(f),m=new Int32Array(f),g=new Float32Array(f),w=0;const p=()=>i?n.int16():n.float32();if(l===1){const A=xt(c?n.int16():n.int32(),{format:ht,field:"row count of a block",ceiling:jn,available:n.remaining,bytesPerItem:(c?2:4)+(a?2:4)});for(let x=0;x<A;x++){const E=r+(c?n.int16():n.int32()),S=xt(a?n.int16():n.int32(),{format:ht,field:"column count of a block row",ceiling:jn,available:n.remaining,bytesPerItem:h});for(let v=0;v<S;v++){const I=o+(a?n.int16():n.int32()),N=p();(i?N===-32768:!Number.isFinite(N))||(w===d.length&&([d,m,g]=fr(d,m,g,n.remaining,h)),d[w]=I,m[w]=E,g[w]=N,w+=1)}}return{x:d,y:m,value:g,length:w}}const b=xt(n.int32(),{format:ht,field:"cell count of a dense block",ceiling:jn,available:n.remaining-2,bytesPerItem:u}),y=n.int16();if(b>0&&!(y>=1))throw new C("format",`A dense block of this .hic is ${y} bins wide, which no rectangle is. The file is truncated, corrupt, or not the format its first bytes claim.`,{width:y});for(let A=0;A<b;A++){const x=p();if(i?x===-32768:!Number.isFinite(x))continue;const E=Math.floor(A/y);w===d.length&&([d,m,g]=fr(d,m,g,n.remaining,h)),d[w]=o+(A-E*y),m[w]=r+E,g[w]=x,w+=1}return{x:d,y:m,value:g,length:w}}function fr(e,t,n,s,o){const r=e.length,i=Math.floor(Math.max(0,s)/o)+1,a=r+Math.min(Math.max(r,1024),i);if(a>to)throw new C("format",`A block of this .hic holds more than ${to.toLocaleString("en-US")} records, more than any real one. The file is corrupt, or not the format its first bytes claim.`,{records:a});const c=new Int32Array(a),l=new Int32Array(a),u=new Float32Array(a);return c.set(e),l.set(t),u.set(n),[c,l,u]}const eo=48<<20,dr=4,vh=6,Ch=64<<20,mr=28,$n=65536,Nn=16<<20,$h=4096,Nh=eo/2,Bh=1024,gr=["SCALE","KR","INTER_KR","GW_KR","VC_SQRT","VC"],ue="BP";class wr{free;waiting=[];constructor(t){this.free=Math.max(1,t)}async run(t){this.free>0?this.free-=1:await new Promise(n=>this.waiting.push(n));try{return await t()}finally{const n=this.waiting.shift();n===void 0?this.free+=1:n()}}}class So{header;footer;chroms;binSize;resolutions;chromOffset;nBins;normType;source;fileIndex;zooms=new Map;zoomsInFlight=new Map;beyondHead=!1;blockCache=new Map;blockCacheBytes=0;normCache=new Map;normFallbacks=new Map;exactSlots;backgroundSlots;constructor(t,n,s,o){this.source=t,this.header=n,this.footer=s;const r=[],i=[];n.chroms.forEach((c,l)=>{c.name.toLowerCase()!=="all"&&(r.push(c),i.push(l))}),this.chroms=r,this.fileIndex=Int32Array.from(i),this.resolutions=[...n.bpResolutions].sort((c,l)=>c-l),this.binSize=o,this.chromOffset=new Float64Array(r.length+1);for(let c=0;c<r.length;c++)this.chromOffset[c+1]=this.chromOffset[c]+Math.ceil(r[c].length/o);this.nBins=this.chromOffset[r.length];const a=this.walkAhead();this.exactSlots=new wr(a===dr?vh:a),this.backgroundSlots=new wr(a),this.normType=gr.find(c=>r.some((l,u)=>s.normVectors.has(Js(c,this.fileIndex[u],ue,o))))??null}static open(t,n={}){const s=hh(t),o=dh(t,s),r=[...s.bpResolutions].sort((a,c)=>a-c);if(r.length===0)throw new C("unsupported","This .hic carries no base-pair resolutions. Fragment-resolution matrices are variable-bin and are excluded from this viewer.",{});const i=n.binSize??gl(r);if(!r.includes(i))throw new C("unsupported",`This .hic has no ${i} bp resolution. It offers ${r.join(", ")}.`,{binSize:i,available:r});return new So(t,s,o,i)}stats(){return this.source.stats()}fileIndexOf(t){return this.fileIndex[t]}chromExtent(t){return[this.chromOffset[t],this.chromOffset[t+1]]}chromAt(t){let n=0,s=this.chroms.length-1;for(;n<s;){const o=n+s+1>>1;this.chromOffset[o]<=t?n=o:s=o-1}return n}chromsSpanning(t){const n=[];if(t[1]<=t[0])return n;const s=this.chromAt(t[0]),o=this.chromAt(Math.min(t[1]-1,this.nBins-1));for(let r=s;r<=o;r++)n.push(r);return n}totalCount(){let t=0;for(const n of this.footer.masterIndex.keys()){const s=this.zoomAt(n);s!==null&&(t+=s.sumCounts)}return t}weights(t,n){const s=new Float64Array(Math.max(0,n-t)).fill(Number.NaN);if(this.normType===null||n<=t)return s;for(const o of this.chromsSpanning([t,n])){const r=this.normVector(o);if(r===null)continue;const i=this.chromOffset[o],a=Math.max(t,i),c=Math.min(n,this.chromOffset[o+1]);for(let l=a;l<c;l++){const u=l-i;s[l-t]=u<r.length?r[u]:Number.NaN}}return s}normVector(t){if(this.normCache.has(t))return this.normCache.get(t)??null;let n=null;if(this.normType!==null){const s=this.normType,o=[s,...gr.filter(r=>r!==s)];for(const r of o){const i=this.footer.normVectors.get(Js(r,this.fileIndex[t],ue,this.binSize));if(i===void 0)continue;const a=wh(this.source,this.header.version,i);if(a.some(c=>Number.isFinite(c))){n=a,r!==s&&this.normFallbacks.set(t,r);break}}}return this.normCache.set(t,n),n}normTypeFor(t){return this.normType===null||(this.normCache.has(t)||this.normVector(t),(this.normCache.get(t)??null)===null)?null:this.normFallbacks.get(t)??this.normType}zoomAt(t){if(this.zooms.has(t))return this.zooms.get(t)??null;const n=this.footer.masterIndex.get(t);let s=null;if(n!==void 0){const o=bh((r,i)=>this.source.readBytes(r,i),n,ue,this.binSize,this.beyondHead?0:Ss);s=this.fitted(t,o.zoom),o.beyondHead&&(this.beyondHead=!0)}return this.zooms.set(t,s),s}fitted(t,n){if(n===null)return null;let s=0;for(const o of n.blocks.values())s+=Math.max(0,o.size);if(!(s<=this.source.size))throw new C("format",`The ${this.binSize} bp blocks of this .hic's ${t} matrix claim ${s.toLocaleString("en-US")} bytes between them, more than the whole file's ${this.source.size.toLocaleString("en-US")}. The file is corrupt, or not the format its first bytes claim.`,{key:t,binSize:this.binSize,bytes:s,size:this.source.size});return n}zoomAtSparse(t){if(this.zooms.has(t))return Promise.resolve(this.zooms.get(t)??null);const n=this.zoomsInFlight.get(t);if(n!==void 0)return n;const s=this.footer.masterIndex.get(t);if(s===void 0||this.source.readExact===void 0)return Promise.resolve(this.zoomAt(t));const o=yh((r,i)=>this.exactRead(r,i),s,ue,this.binSize,this.beyondHead?0:Ss).then(r=>{r.beyondHead&&(this.beyondHead=!0);const i=this.fitted(t,r.zoom);return this.zooms.set(t,i),i}).finally(()=>this.zoomsInFlight.delete(t));return this.zoomsInFlight.set(t,o),o}zoomFor(t,n){return this.zoomAt(this.pairKey(t,n))}pairKey(t,n){return`${this.fileIndex[t]}_${this.fileIndex[n]}`}walkAhead(){let t=0;for(let s=0;s<this.chroms.length;s++)t=Math.max(t,this.chromOffset[s+1]-this.chromOffset[s]);const n=Math.max(1,t*t*mr);return Math.max(1,Math.min(dr,Math.floor(Ch/n)))}walkPlans(t){const n=[];let s=[],o=0;for(const r of t){const i=this.binsOf(r[0])*this.binsOf(r[1])*mr;s.length>0&&(o+i>Nh||s.length>=Bh)&&(n.push(s),s=[],o=0),s.push(r),o+=i}return s.length>0&&n.push(s),n}async prefetchWalk(t,n={}){if(this.source.readExact===void 0)return!0;const s=[],o=new Set;for(const h of t){const f=this.pairKey(Math.min(h.a,h.b),Math.max(h.a,h.b));if(o.has(f)||this.zooms.has(f))continue;o.add(f);const d=this.footer.masterIndex.get(f);d===void 0?this.zooms.set(f,null):s.push(d)}const r=[];for(const h of s){const f=this.beyondHead?h.size:Math.min(h.size,Ss);r.push({position:h.position,size:f,entry:h,head:!0});const d=h.position+h.size,m=Math.min($h,this.source.size-d);m>0&&r.push({position:d,size:m,entry:h,head:!1})}const i=new Map,a=[];if(!await this.fetchRuns(Cn(r,$n,Nn),n,(h,f)=>{for(const d of h.refs){const m=d.position-h.position,g=f.subarray(m,m+d.size);if(!d.head){i.set(d.entry.key,{position:d.position,bytes:g.slice()});continue}const{entry:w}=d;try{const p=d.size===w.size?Pe(g,w,ue,this.binSize):ms(g,ue,this.binSize,w.size);this.zooms.set(w.key,this.fitted(w.key,p))}catch(p){if(!(p instanceof jt))throw p;this.beyondHead=!0,a.push({position:w.position,size:w.size,entry:w})}}})||a.length>0&&!await this.fetchRuns(Cn(a,$n,Nn),n,(f,d)=>{for(const m of f.refs){const g=m.position-f.position,w=Pe(d.subarray(g,g+m.size),m.entry,ue,this.binSize);this.zooms.set(m.entry.key,this.fitted(m.entry.key,w))}}))return!1;const l=[],u=new Set;for(const h of t){const f=this.windowOf(h.a,h.b,h.rows,h.cols);if(f===null)continue;const d=this.pairKey(f.low,f.high),m=this.zooms.get(d);if(m==null)continue;const g=i.get(d);for(const w of hr(m,this.header.version,f.intra,f.lowSpan,f.highSpan)){const p=m.blocks.get(w);if(p===void 0||p.size<=0)continue;const b=this.blockKey(p);if(u.has(b)||this.blockCache.has(b))continue;u.add(b),this.checkBlock(p);const y=g===void 0?-1:p.position-g.position;g!==void 0&&y>=0&&y+p.size<=g.bytes.byteLength?await this.decode(p,g.bytes.subarray(y,y+p.size)):l.push(p)}}return this.fetchRuns(Cn(l,$n,Nn),n,async(h,f)=>{for(const d of h.refs){const m=d.position-h.position;await this.decode(d,f.subarray(m,m+d.size))}})}async fetchRuns(t,n,s){let o=!1;return await Promise.all(t.map(async r=>{await n.pause?.();const i=()=>this.exactSlots.run(async()=>o||n.cancelled?.()===!0?(o=!0,null):this.readExactNow(r.position,r.length)),a=n.pause===void 0?await i():await this.backgroundSlots.run(i);a!==null&&await s(r,a)})),!o}exactRead(t,n){return this.exactSlots.run(()=>this.readExactNow(t,n))}readExactNow(t,n){const s=this.source,o=s.readExact;return o===void 0?Promise.resolve(s.readBytes(t,n)):o.call(s,t,n)}binsOf(t){return this.chromOffset[t+1]-this.chromOffset[t]}hasAnyMatrix(){for(let t=0;t<this.chroms.length;t++)if(this.zoomFor(t,t)!==null)return!0;return!1}indexedPairs(){const t=new Map;this.fileIndex.forEach((o,r)=>t.set(o,r));const n=new Set,s=[];for(const o of this.footer.masterIndex.keys()){const[r,i]=o.split("_").map(h=>Number.parseInt(h,10)),a=t.get(r),c=t.get(i);if(a===void 0||c===void 0)continue;const l=a<=c?[a,c]:[c,a],u=`${l[0]}_${l[1]}`;n.has(u)||(n.add(u),s.push(l))}return s.sort((o,r)=>o[0]-r[0]||o[1]-r[1]),s}async pairRecords(t,n,s,o,r=!1){const[i,a]=t<=n?[t,n]:[n,t],c=r?await this.zoomAtSparse(this.pairKey(i,a)):this.zoomFor(i,a);if(c===null)return null;const l=this.windowOf(t,n,s,o);if(l===null)return null;const{intra:u,lowSpan:h,highSpan:f}=l,d=hr(c,this.header.version,u,h,f),m=this.chromOffset[i],g=this.chromOffset[a];let w=0;const p=await this.blocks(c,d,r);for(const E of p)w+=E.length;if(w===0)return null;const b=new Int32Array(w),y=new Int32Array(w),A=new Float64Array(w);let x=0;for(const E of p)for(let S=0;S<E.length;S++){const v=m+E.x[S],I=g+E.y[S];v<=I?(b[x]=v,y[x]=I):(b[x]=I,y[x]=v),A[x]=E.value[S],x+=1}return{bin1:b,bin2:y,count:A,length:x}}windowOf(t,n,s,o){const[r,i]=t<=n?[t,n]:[n,t],a=r===i,[c,l]=a?[this.clipSpan(r,s),this.clipSpan(r,o)]:[this.localSpan(r,s,o),this.localSpan(i,s,o)];return c===null||l===null?null:{low:r,high:i,intra:a,lowSpan:c,highSpan:l}}clipSpan(t,n){const s=this.chromOffset[t],o=Math.max(n[0],s),r=Math.min(n[1],this.chromOffset[t+1]);return r>o?[o-s,r-s]:null}localSpan(t,n,s){const o=this.chromOffset[t],r=this.chromOffset[t+1];let i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const c of[n,s]){const l=Math.max(c[0],o),u=Math.min(c[1],r);u<=l||(i=Math.min(i,l-o),a=Math.max(a,u-o))}return Number.isFinite(i)?[i,a]:null}async blocks(t,n,s){const o=new Map,r=[];for(const a of n){const c=t.blocks.get(a);if(c===void 0||c.size<=0)continue;const l=this.held(c);if(l!==void 0){o.set(a,l);continue}this.checkBlock(c),r.push(c)}if(s&&this.source.readExact!==void 0)for(const a of Cn(r,$n,Nn)){const c=await this.exactRead(a.position,a.length);for(const l of a.refs){const u=l.position-a.position;o.set(l.number,await this.decode(l,c.subarray(u,u+l.size)))}}else for(const a of r)o.set(a.number,await this.decode(a,this.source.readBytes(a.position,a.size)));const i=[];for(const a of n){const c=o.get(a);c!==void 0&&i.push(c)}return i}checkBlock(t){ds(t.position,t.size,{format:ht,field:`block ${t.number} of the ${this.binSize} bp matrix`,size:this.source.size,ceiling:lr.ceiling})}held(t){const n=this.blockKey(t),s=this.blockCache.get(n);if(s!==void 0)return this.blockCache.delete(n),this.blockCache.set(n,s),s}async decode(t,n){const s=await xo(n,{format:ht,field:`block ${t.number} of the ${this.binSize} bp matrix`,encoding:"deflate",maxBytes:ca(n.byteLength,lr)}),o=Ih(s,this.header.version);return this.remember(this.blockKey(t),o),o}blockKey(t){return`${this.binSize}/${t.position}`}remember(t,n){const s=n.x.byteLength+n.y.byteLength+n.value.byteLength;if(!(s>eo)){this.blockCache.set(t,n),this.blockCacheBytes+=s;for(const o of this.blockCache.keys()){if(this.blockCacheBytes<=eo)break;const r=this.blockCache.get(o);r!==void 0&&(this.blockCacheBytes-=r.x.byteLength+r.y.byteLength+r.value.byteLength),this.blockCache.delete(o)}}}close(){this.zooms.clear(),this.blockCache.clear(),this.normCache.clear(),this.blockCacheBytes=0}}function pr(e){throw new C("unsupported",`A .hic has no ${e}: it is indexed per chromosome pair and per block, not as one sorted pixel table. Read pixels through PixelStore (metacooler/store.ts), which is the seam that exists for exactly this difference.`,{path:e})}function Oh(e,t){const n=()=>De(t.chroms.length,["name","length"],{name:t.chroms.map(o=>o.name),length:Float64Array.from(t.chroms,o=>o.length)}),s={format:"HIC","format-url":"https://github.com/aidenlab/juicer/wiki/Data-structure","format-version":t.header.version,"bin-size":t.binSize,"bin-type":"fixed",ordering:"genome-then-length","storage-mode":"symmetric-upper",assembly:t.header.genomeId,nbins:t.nBins,ncontigs:t.chroms.length,nnz:null,sum:null,ngenomes:null,...t.header.attributes,...t.normType===null?{}:{"hic-normalisation":t.normType}};return{uri:e,group:"/",rootEntries:t.resolutions.map(o=>String(o)),rootEntryGroup:"resolutions",attrs:()=>({...s}),attrsAt:o=>o===""||o==="/"?{...s}:{},has(o){return o==="bins/weight"?t.normType!==null:["chroms","chroms/name","chroms/length","indexes","pixels","bins"].includes(o)},keys(o){return o===""||o==="/"?["chroms","bins","pixels","indexes"]:o==="chroms"?["name","length"]:o==="pixels"?["bin1_id","bin2_id","count"]:o==="bins"?t.normType===null?[]:["weight"]:[]},isSoftLink:()=>!1,datasetLength(o){return o==="chroms/name"||o==="chroms/length"?t.chroms.length:o==="bins/weight"?t.nBins:(o.startsWith("pixels/"),0)},dtype(o){return o==="pixels/count"?"<f":o==="chroms/length"?"<i":o==="chroms/name"?"S":"<d"},readNumeric(o,r=0,i){if(o==="indexes/chrom_offset")return t.chromOffset.slice();if(o==="chroms/length"){const a=i??t.chroms.length;return Float64Array.from(t.chroms.slice(r,a),c=>c.length)}if(o==="bins/weight"){if(t.normType===null)throw new C("unsupported","This .hic carries no normalisation vectors, so there are no weights to balance with. Re-run Juicer Tools `addNorm`, or view the raw counts.",{});return t.weights(r,i??t.nBins)}throw(o==="indexes/bin1_offset"||o.startsWith("pixels/"))&&pr(o),new C("unsupported",`A .hic has no ${o}.`,{path:o})},readInt32(o){throw o.startsWith("pixels/")&&pr(o),new C("unsupported",`A .hic has no ${o}.`,{path:o})},readStrings(o,r=0,i){if(o==="chroms/name")return t.chroms.slice(r,i??t.chroms.length).map(a=>a.name);throw new C("unsupported",`A .hic has no ${o}.`,{path:o})},readTable(o){if(o==="chroms"||o==="contigs")return n();throw new C("unsupported",`A .hic has no /${o} table.`,{path:o})},at(o){throw new C("unsupported",`A .hic has no /${o} group to open.`,{path:o})},close:()=>t.close()}}function kh(e,t){return e*1e6+t}class _h{constructor(t){this.file=t}nnz=null;countKind="f";rectangular=!0;scoreColumns(){return["count"]}binOffsets(){throw new C("unsupported","A .hic has no per-bin pixel index, so the stored-pixel density column cannot be computed for one. It is a metagenome diagnostic and a .hic has no genomes, so nothing that draws asks for it.",{})}async forEachWindow(t,n,s,o,r={}){this.refuseOtherColumns(r.value);const i=this.pairsFor(t,n),a=i.length>1;return this.walk(i,(c,l)=>this.file.pairRecords(c,l,t,n,a),o,r,()=>[t,n])}async forEachBands(t,n,s={}){this.refuseOtherColumns(s.value);const o=new Set;for(const l of t)for(const u of this.file.chromsSpanning(l))o.add(u);const r=[0,this.file.nBins],i=this.file.indexedPairs().filter(([l])=>o.has(l)),a=i.length>1,c=l=>{const u=this.clipTo(l,t);return u===null?null:[u,r]};return this.walk(i,(l,u)=>{const h=c(l);return h===null?Promise.resolve(null):this.file.pairRecords(l,u,h[0],h[1],a)},n,s,c)}async scanAll(t){const n=[0,this.file.nBins],s=this.file.indexedPairs(),o=s.length>1;await this.inOrder(s,(r,i)=>this.file.pairRecords(r,i,n,n,o),(r,i)=>{const a=r!==null&&t.onChunk(r)===!1;return t.onProgress?.(i,s.length),!a},void 0,t.pause,()=>[n,n])}pairsFor(t,n){const s=this.file.chromsSpanning(t),o=this.file.chromsSpanning(n),r=new Set,i=[];for(const a of s)for(const c of o){const l=a<=c?[a,c]:[c,a],u=kh(l[0],l[1]);r.has(u)||(r.add(u),i.push(l))}return i}clipTo(t,n){const[s,o]=this.file.chromExtent(t);let r=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const a of n){const c=Math.max(a[0],s),l=Math.min(a[1],o);l<=c||(r=Math.min(r,c),i=Math.max(i,l))}return Number.isFinite(r)?[r,i]:null}walk(t,n,s,o,r){return this.inOrder(t,n,(i,a)=>(i!==null&&i.length>0&&s(i),o.onProgress?.(a,t.length),!0),()=>o.cancelled?.()===!0,void 0,r)}async inOrder(t,n,s,o,r,i){const a=t.length>1?this.file.walkAhead():1,c=this.planned(t,o,r,i),l=[];let u=0,h=0;for(;h<t.length;){if(await(r?.()??St()),o?.()===!0)return!1;for(;l.length<a&&u<t.length;){const[d,m]=t[u],g=c(u).then(w=>w?n(d,m):null);u+=1,g.catch(()=>{}),l.push(g)}const f=await l.shift();if(h+=1,!s(f,h))return!1}return!0}planned(t,n,s,o){if(t.length<2||o===void 0)return()=>Promise.resolve(!0);const r=this.file.walkPlans(t),i=[];r.forEach((c,l)=>c.forEach(()=>i.push(l)));const a=new Map;return c=>{const l=i[c];let u=a.get(l);if(u===void 0){const h=r[l].flatMap(([f,d])=>{const m=o(f,d);return m===null?[]:[{a:f,b:d,rows:m[0],cols:m[1]}]});u=this.file.prefetchWalk(h,{pause:s,cancelled:n}),a.set(l,u)}return u}}refuseOtherColumns(t){if(!(t===void 0||t==="count"))throw new C("unsupported",`A .hic stores one value per record, so there is no '${t}' column to draw. Extra per-pixel columns are a cooler feature.`,{value:t})}}const Io=4<<20,Eo=12,Th=65536;function ma(e){return e.length>=2&&e[0]===31&&e[1]===139}function ga(e,t=0){return e.length<t+Eo||e[t]!==31||e[t+1]!==139||e[t+2]!==8||(e[t+3]&4)===0?!1:vo(e,t)!==null}function vo(e,t=0){if(e.length<t+Eo)return null;const n=new DataView(e.buffer,e.byteOffset,e.byteLength),s=n.getUint16(t+10,!0);let o=t+12;const r=Math.min(o+s,e.length);for(;o+4<=r;){const i=e[o],a=e[o+1],c=n.getUint16(o+2,!0);if(i===66&&a===67&&c===2)return n.getUint16(o+4,!0)+1;o+=4+c}return null}async function wa(e){return e.length===0?e:xo(e,{format:"BGZF file",field:"member",encoding:"deflate-raw",maxBytes:Th})}function Fh(e,t,n){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t+n-4,!0)}function zh(e,t,n){const o=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t+10,!0);return e.subarray(t+12+o,t+n-8)}function Co(e,t={}){const n=e.readBytes(0,Math.min(e.size,64));return ga(n)?Ph(e,t):ma(n)?br(e,t,Rh).pipeThrough(new DecompressionStream("gzip")):br(e,t,Io)}const Rh=65536;function br(e,t,n){const s=t.from??0,o=Math.min(t.to??e.size,e.size),r=Math.max(0,o-s);let i=s,a=0;return new ReadableStream({pull(c){if(t.cancelled?.()===!0||i>=o){c.close();return}const l=e.readBytes(i,Math.min(Io,o-i));if(l.length===0){c.close();return}i+=l.length,a+=l.length;for(let u=0;u<l.length;u+=n)c.enqueue(l.subarray(u,Math.min(u+n,l.length)));t.onProgress?.(a,r)}})}function Ph(e,t){const n=t.from??0,s=Math.min(t.to??e.size,e.size),o=Math.max(0,s-n);let r=n,i=0,a=new Uint8Array(0),c=!1;const l=u=>{t.onFraming?.({partialMember:a.length>0,endedOnEofMarker:c}),u.close()};return new ReadableStream({async pull(u){for(;;){if(t.cancelled?.()===!0){u.close();return}const h=a.length>=Eo?vo(a):null;if(h!==null&&a.length>=h){const d=zh(a,0,h),m=Fh(a,0,h);if(a=a.subarray(h),c=m===0,m>0){u.enqueue(await wa(d));return}continue}if(r>=s){l(u);return}const f=e.readBytes(r,Math.min(Io,s-r));if(f.length===0){l(u);return}if(r+=f.length,i+=f.length,t.onProgress?.(i,o),a.length===0)a=f.slice();else{const d=new Uint8Array(a.length+f.length);d.set(a),d.set(f,a.length),a=d}}}})}async function $o(e,t,n){const s=e.getReader();let o=[],r=0;const i=a=>{if(r===0)return a;const c=new Uint8Array(r+a.length);let l=0;for(const u of o)c.set(u,l),l+=u.length;return c.set(a,l),o=[],r=0,c};try{for(;;){if(n?.()===!0)return!1;const{done:a,value:c}=await s.read();if(a)break;let l=0;for(let u=c.indexOf(10);u>=0;u=c.indexOf(10,l)){const h=i(c.subarray(l,u)),f=h.length>0&&h[h.length-1]===13?h.length-1:h.length;t(h.subarray(0,f)),l=u+1}if(l<c.length&&(o.push(c.slice(l)),r+=c.length-l,r>Is))throw new C("format",`A line of this .pairs file runs past ${Is>>20} MiB without ending, and no pairs line is that long. The file is corrupt, or is not a .pairs file.`,{maxLineBytes:Is})}return r>0&&t(i(new Uint8Array(0))),!0}finally{s.releaseLock()}}const Is=64<<20,Lh=["readID","chr1","pos1","chr2","pos2","strand1","strand2"],Bn={chrom1:["chr1","chrom1","chromosome1"],pos1:["pos1","position1"],chrom2:["chr2","chrom2","chromosome2"],pos2:["pos2","position2"]},yr={strand1:["strand1","strand_1"],strand2:["strand2","strand_2"]},Dh=["pair_type","pairtype"],Uh=64<<20,Gh=64,Hh=65536;function pa(e){return/^##\s*pairs\s+format/i.test(e)}async function qh(e){let t=null;try{await $o(Co(e,{to:Wh(e)}),n=>{t??=new TextDecoder().decode(n)},()=>t!==null)}catch{}return t!==null&&pa(t)}function Wh(e){const t=e.readBytes(0,Math.min(e.size,Gh));if(ga(t)){const n=vo(t);if(n!==null)return Math.min(e.size,n)}return Math.min(e.size,Hh)}async function ba(e){const t=[],n=new Set,s=[];let o=null,r=null,i=null,a=null,c=null,l=0,u=!1;const h=new TextDecoder,f=Co(e,{to:Math.min(e.size,Uh)});if(await $o(f,d=>{if(u)return;if(l+=d.length+1,d.length===0||d[0]!==35){u=!0;return}const m=h.decode(d);if(s.push(m),o===null&&pa(m)){o=m.replace(/^##\s*/,"").trim();return}const g=m.indexOf(":");if(g<0)return;const w=m.slice(1,g).trim().toLowerCase(),p=m.slice(g+1).trim();if(w==="chromsize"||w==="chromosome"){const b=p.split(/\s+/);b.length>=2&&Ar(t,n,b[0],Number(b[1]))}else if(w==="samheader"){const b=/^@SQ\s.*\bSN:(\S+).*\bLN:(\d+)/.exec(p);b!==null&&Ar(t,n,b[1],Number(b[2]))}else w==="genome_assembly"?r=p:w==="sorted"?i=p:w==="shape"?a=p:w==="columns"&&(c=p.split(/\s+/).filter(b=>b!==""))},()=>u).catch(()=>!1),o===null)throw new C("format","This file does not begin with a `## pairs format` line, so it is not a 4DN pairs file. If it is a headerless contact list, add a header with `pairtools header generate`, or bin it with `cooler cload pairs` and open the cooler.",{bytesRead:l});if(t.length===0)throw new C("format","This .pairs file declares no `#chromsize:` lines, so there is no bin table to build. Chromosome sizes cannot be inferred from the records — a grid guessed from the largest coordinate seen would differ between two subsamples of the same library. Add them with `pairtools header generate --chroms-path <chrom.sizes>`.",{contigs:0});return{version:o,assembly:r,sorted:i,shape:a,contigs:t,columns:jh(c??Lh,c!==null),text:s.join(`
2
+ `)}}function Ar(e,t,n,s){t.has(n)||!Number.isFinite(s)||s<=0||(t.add(n),e.push({name:n,length:s}))}function jh(e,t){const n=e.map(i=>i.toLowerCase()),s=i=>{for(const a of i){const c=n.indexOf(a);if(c>=0)return c}return-1},o={chrom1:s(Bn.chrom1),pos1:s(Bn.pos1),chrom2:s(Bn.chrom2),pos2:s(Bn.pos2),strand1:s(yr.strand1),strand2:s(yr.strand2),pairType:s(Dh)},r=["chrom1","pos1","chrom2","pos2"].filter(i=>o[i]<0);if(r.length>0)throw new C("unsupported",`This .pairs file's ${t?"`#columns:` line":"assumed column layout"} has no ${r.join(", ")} column. It declares ${e.join(", ")}. The importer needs two chromosome columns and two position columns.`,{missing:r,columns:[...e]});return o}function No(e,t){const n=new Float64Array(e.length+1);let s=0;for(let o=0;o<e.length;o++)n[o]=s,s+=Math.ceil(e[o].length/t);return n[e.length]=s,n}function ya(e,t){let n=0;for(const s of e)n+=Math.ceil(s.length/t);return n}function Mr(e){throw new C("unsupported",`A map binned from a .pairs file serves ${e} through PixelStore (metacooler/store.ts), not through the handle. Reaching for the column by name bypasses the chunking and the cancellation every other read has.`,{path:e})}function Qh(e){const{header:t,pixels:n}=e,s=()=>De(n.contigs.length,["name","length"],{name:n.contigs.map(r=>r.name),length:Float64Array.from(n.contigs,r=>r.length)}),o={format:"PAIRS","format-url":"https://github.com/4dn-dcic/pairix/blob/master/pairs_format_specification.md","format-version":Yh(t.version),"bin-size":n.binSize,"bin-type":"fixed","contig-ordering":"genome-then-length","storage-mode":"symmetric-upper","genome-assembly":t.assembly,nbins:n.nBins,nchroms:n.contigs.length,nnz:n.nnz,sum:n.sum,ngenomes:null,"pairs-source":e.uri,"pairs-header":t.text,"pairs-sorted":t.sorted,"pairs-shape":t.shape,"pairs-indexed":e.indexed,"pairs-records":n.sum,...e.declaredRecords==null?{}:{"pairs-declared-records":e.declaredRecords},...n.skippedUnknownContig===0?{}:{"pairs-skipped-unknown-contig":n.skippedUnknownContig},...n.skippedBadPosition===0?{}:{"pairs-skipped-bad-position":n.skippedBadPosition},...n.clampedPosition===0?{}:{"pairs-clamped-positions":n.clampedPosition},...n.wasUnsorted?{"pairs-required-merge":!0}:{},...n.truncated?{"pairs-truncated":!0}:{},...n.contigsWithoutCisContacts.length===0?{}:{"pairs-sequences-without-cis-contacts":n.contigsWithoutCisContacts.join(", ")}};return{uri:e.uri,group:"/",rootEntries:e.rungs.map(r=>String(r)),rootEntryGroup:"resolutions",attrs:()=>({...o}),attrsAt:r=>r===""||r==="/"?{...o}:{},has(r){return["chroms","chroms/name","chroms/length","contigs","indexes","indexes/chrom_offset","pixels","pixels/count","bins"].includes(r)},keys(r){return r===""||r==="/"?["chroms","bins","pixels","indexes"]:r==="chroms"||r==="contigs"?["name","length"]:r==="pixels"?["bin1_id","bin2_id","count"]:r==="indexes"?["chrom_offset"]:r==="bins"?[]:[]},isSoftLink:()=>!1,datasetLength(r){return r==="chroms/name"||r==="chroms/length"?n.contigs.length:r==="indexes/chrom_offset"?n.contigs.length+1:r.startsWith("pixels/")?n.nnz:0},dtype(r){return r==="pixels/count"||r==="pixels/bin1_id"||r==="pixels/bin2_id"||r==="chroms/length"?"<i":r==="chroms/name"?"S":"<d"},readNumeric(r,i=0,a){if(r==="indexes/chrom_offset")return n.chromOffset.slice();if(r==="chroms/length"){const c=a??n.contigs.length;return Float64Array.from(n.contigs.slice(i,c),l=>l.length)}throw r==="bins/weight"?new C("unsupported","A map binned from a .pairs file carries raw counts and no balancing weights: nothing has been balanced. Export the .mcool and run `cooler balance` on it, or open a cooler that was written with weights.",{}):((r==="indexes/bin1_offset"||r.startsWith("pixels/"))&&Mr(r),new C("unsupported",`An imported .pairs map has no ${r}.`,{path:r}))},readInt32(r){throw r.startsWith("pixels/")&&Mr(r),new C("unsupported",`An imported .pairs map has no ${r}.`,{path:r})},readStrings(r,i=0,a){if(r==="chroms/name")return n.contigs.slice(i,a??n.contigs.length).map(c=>c.name);throw new C("unsupported",`An imported .pairs map has no ${r}.`,{path:r})},readTable(r){if(r==="chroms"||r==="contigs")return s();throw new C("unsupported",`An imported .pairs map has no /${r} table.`,{path:r})},at(r){throw new C("unsupported",`An imported .pairs has no /${r} group to open.`,{path:r})},close:()=>{}}}function Yh(e){const t=/v?(\d+)(?:\.(\d+))?/.exec(e);return t===null?null:Number(t[1])}const xr=1<<20;class Vh{constructor(t){this.pixels=t}offsets=null;get nnz(){return this.pixels.nnz}countKind="i";scoreColumns(){return["count"]}binOffsets(){if(this.offsets!==null)return this.offsets;const{bin1:t,nnz:n,nBins:s}=this.pixels,o=new Float64Array(s+1);let r=0;for(let i=0;i<s;i++){for(;r<n&&t[r]===i;)r++;o[i+1]=r}return this.offsets=o,o}async forEachWindow(t,n,s,o,r={}){this.refuseOtherColumns(r.value);const i=this.pixelRange(s.span[0],s.span[1]);return this.emit(i[0],i[1],o,r)}async forEachBands(t,n,s={}){this.refuseOtherColumns(s.value);for(const[o,r]of this.mergedBands(t))if(!await this.emit(o,r,n,s))return!1;return!0}async scanAll(t){const n=Math.max(1,Math.trunc(t.chunkSize??xr)),s=this.pixels.nnz;for(let o=0;o<s;o+=n){const r=Math.min(o+n,s);if(t.onChunk(this.chunk(o,r))===!1)return;t.onProgress?.(r,s),await St()}}pixelRange(t,n){const s=this.binOffsets(),o=this.pixels.nBins,r=s[Math.max(0,Math.min(o,t))],i=s[Math.max(0,Math.min(o,n))];return[r,Math.max(r,i)]}mergedBands(t){const n=[];for(const[o,r]of t){if(r<=o)continue;const[i,a]=this.pixelRange(o,r);a>i&&n.push([i,a])}n.sort((o,r)=>o[0]-r[0]);const s=[];for(const o of n){const r=s[s.length-1];r!==void 0&&o[0]<=r[1]+Ti?r[1]=Math.max(r[1],o[1]):s.push([o[0],o[1]])}return s}async emit(t,n,s,o){const r=Math.max(1,Math.trunc(o.chunkSize??xr)),i=n-t;for(let a=t;a<n;a+=r){if(o.cancelled?.()===!0)return!1;const c=Math.min(a+r,n);s(this.chunk(a,c)),o.onProgress?.(c-t,i),await St()}return!0}chunk(t,n){const{bin1:s,bin2:o,count:r}=this.pixels;return{bin1:s.slice(t,n),bin2:o.slice(t,n),count:Float64Array.from(r.subarray(t,n)),length:n-t}}refuseOtherColumns(t){if(!(t===void 0||t==="count"))throw new C("unsupported",`A map binned from a .pairs file stores one value per pixel — the number of contacts — so there is no '${t}' column to draw. Extra per-pixel columns come from a cooler that was written with them.`,{value:t})}}function en(e,t,n){const s=Math.max(0,Math.min(Math.trunc(t),e)),o=Math.max(s,Math.min(Math.trunc(n??e),e));return[s,o]}function Kh(e,t){const{bins:n,pixels:s}=t,o=()=>De(n.names.length,["name","length"],{name:[...n.names],length:n.lengths.slice()}),r={format:"HiC-Pro","format-url":"https://github.com/nservant/HiC-Pro","bin-size":n.binsize,"bin-type":"fixed",ordering:"genome-then-length","storage-mode":"symmetric-upper",nbins:n.nBins,ncontigs:n.names.length,nnz:s.nnz,sum:s.sum,ngenomes:null,"hicpro-matrix":t.matrixName,"hicpro-bins":t.binsName,"hicpro-stored":s.observed};return{uri:e,group:"/",rootEntries:[],rootEntryGroup:"",attrs:()=>({...r}),attrsAt:i=>i===""||i==="/"?{...r}:{},has(i){return["chroms","chroms/name","chroms/length","bins","pixels","pixels/bin1_id","pixels/bin2_id","pixels/count","indexes","indexes/bin1_offset","indexes/chrom_offset"].includes(i)},keys(i){return i===""||i==="/"?["chroms","bins","pixels","indexes"]:i==="chroms"?["name","length"]:i==="pixels"?["bin1_id","bin2_id","count"]:i==="indexes"?["bin1_offset","chrom_offset"]:i==="bins"?[]:[]},isSoftLink:()=>!1,datasetLength(i){return i==="chroms/name"||i==="chroms/length"?n.names.length:i.startsWith("pixels/")?s.nnz:i==="indexes/bin1_offset"?n.nBins+1:i==="indexes/chrom_offset"?n.names.length+1:0},dtype(i){return i==="pixels/count"?"<f":i==="pixels/bin1_id"||i==="pixels/bin2_id"||i==="chroms/length"?"<i":i==="chroms/name"?"S":"<d"},readNumeric(i,a=0,c){if(i==="indexes/chrom_offset")return n.chromOffset.slice();if(i==="indexes/bin1_offset"){const[l,u]=en(n.nBins+1,a,c);return s.binOffset.slice(l,u)}if(i==="chroms/length"){const[l,u]=en(n.names.length,a,c);return n.lengths.slice(l,u)}if(i==="pixels/count"){const[l,u]=en(s.nnz,a,c);return Float64Array.from(s.count.subarray(l,u))}throw i==="bins/weight"?new C("unsupported","A HiC-Pro matrix carries no balancing weights. Its `iced/` matrix is already normalised — open that one instead of balancing this one — and its `.biases` file belongs to the raw matrix, so applying it here would normalise twice.",{path:i}):new C("unsupported",`A HiC-Pro matrix has no ${i}.`,{path:i})},readInt32(i,a=0,c){const[l,u]=en(s.nnz,a,c);if(i==="pixels/bin1_id")return s.bin1.subarray(l,u);if(i==="pixels/bin2_id")return s.bin2.subarray(l,u);throw new C("unsupported",`A HiC-Pro matrix has no ${i}.`,{path:i})},readStrings(i,a=0,c){if(i==="chroms/name"){const[l,u]=en(n.names.length,a,c);return n.names.slice(l,u)}throw new C("unsupported",`A HiC-Pro matrix has no ${i}.`,{path:i})},readTable(i){if(i==="chroms"||i==="contigs")return o();throw new C("unsupported",`A HiC-Pro matrix has no /${i} table.`,{path:i})},at(i){throw new C("unsupported",`A HiC-Pro matrix has no /${i} group.`,{path:i})},close:()=>{}}}const Xh={K:1e3,KB:1e3,M:1e6,MB:1e6,G:1e9,GB:1e9};function Wt(e,t={}){throw new C("bad-range",e,t)}function Sr(e){const t=e.replace(/,/g,"").split(/([0-9.]+)/);(t.length!==3||t[0]!=="")&&Wt(`Unexpected token "${e}"`,{token:e});const[,n,s]=t;if(s.length===0)return/^[0-9]+$/.test(n)||Wt(`Unexpected token "${e}"`,{token:e}),Number(n);const o=Number.parseFloat(n);Number.isFinite(o)||Wt(`Unexpected token "${e}"`,{token:e});const r=s.toUpperCase().trim(),i=Xh[r];return i===void 0&&Wt(`Unknown unit '${r}'`,{unit:r}),Math.trunc(o*i)}function Zh(e){const t=/\s*(-)|\s*([0-9,]+(?:\.[0-9]*)?(?:[a-z]+)?)|\s*(.+)/gi,n=[];for(const s of e.matchAll(t)){const o=s[1],r=s[2],i=s[3];o!==void 0?n.push({kind:"HYPHEN",text:o}):r!==void 0?n.push({kind:"COORD",text:r}):n.push({kind:"OTHER",text:i??""})}return n}function Aa(e,t={}){const n=e.split(":"),s=n[0].trim();if(s.length===0&&Wt("Chromosome name cannot be empty",{region:e}),n.length<2)return[s,null,null];const o=Zh(n[1]);let r=0;const i=()=>o[r++],a=(h,f)=>(h===void 0&&Wt(`Expected ${f.join(" or ")} token missing`,{region:e}),f.includes(h.kind)||Wt(`Unexpected token "${h.text}"`,{region:e}),h),c=Sr(a(i(),["COORD"]).text);a(i(),["HYPHEN"]);const l=i();if(l===void 0)return[s,c,null];const u=Sr(a(l,["COORD"]).text);return u<c&&t.reversed!==!0&&Wt("End coordinate less than start — unless the sequence joins its own ends, which is a tick in the circular column of the Chromosomes table",{region:e,start:c,end:u}),[s,c,u]}function Jh(e,t){const[n,s,o]=Aa(e),r=t.get(n);if(r===void 0)throw new C("unknown-label",`Unknown sequence label: ${n}`,{label:n});const i=s===null?0:s,a=o===null?r:o;return a<i&&Wt("End cannot be less than start",{region:e,start:i,end:a}),(i<0||a>r)&&Wt(`Genomic region out of bounds: [${i}, ${a})`,{region:e,start:i,end:a,length:r}),[n,i,a]}function tf(e,t,n,s){const o=t.split(":")[0],r=e.genomes===null?[]:e.genomes.strings("name"),i=e.contigs.strings("name");if(r.includes(o)){if(o===ke)throw new C("unbinned-not-displayable",`Range ${V(t)}: ${V(ke)} holds every contig that binning failed to assign. It is a bookkeeping row, not a genome — there is no coherent contact map to draw for it — so it cannot be displayed. Its share of the file is reported as a QC statistic in the file info panel.`,{label:o});if(t.includes(":"))throw new C("genome-coordinate-suffix",`Range ${V(t)}: ${V(o)} is a genome name — coordinate suffixes are not allowed for genome ranges. Use just ${V(o)}.`,{label:o,region:t});return{kind:"genome",label:o,extent:e.genomeExtent(o)}}if(i.includes(o))return{kind:"contig",label:o,extent:Ir(e,o,t,s)};const a=(e.names??ef(e)).find(o,{from:n});if(a!==null){const c=t.slice(o.length);return{kind:"contig",label:a.name,extent:Ir(e,a.name,`${a.name}${c}`,s),matched:a}}throw e.genomes===null?new C("unknown-label",`Range ${V(t)}: ${V(o)} is not a sequence of this file.
3
+ Sequences: ${_e(i)}`,{label:o,region:t}):new C("unknown-label",`Range ${V(t)}: ${V(o)} is not a known genome or contig.
4
+ Genomes: ${_e(e.displayGenomes().map(c=>r[c]))}
5
+ Contigs: ${_e(i)}`,{label:o,region:t})}function Ir(e,t,n,s){if(s===void 0||!s.includes(t))return e.extent(n);const[,o,r]=Aa(n,{reversed:!0});if(o===null||r===null||r>=o)return e.extent(n);const i=e.extent(t),a=e.extent(`${t}:${o}-`),c=e.extent(`${t}:0-${r}`);return[a[0],i[1]+(c[1]-i[0])]}function ef(e){const t=e.contigs.strings("name"),n=e.contigs.numbers("length");return ie.of(t.map((s,o)=>({name:s,length:n[o]})))}function nf(e,t,n,s,o){const r=e[t],i=e[t+1]??r,a=Math.min(r+Math.floor(n/o),i),c=Math.min(r+Math.ceil(s/o),i);return[a,Math.max(a,c)]}const sf=["name","length","n_contigs","n_bins"],of=["name","length"],Es=["name","length","genome_id"],rf=["name","length","n_contigs","n_bins"],af=["bin-size","bin-type","storage-mode"],vs=["nnz","sum"];class et{uri;layout;entries;entryGroup;tables;info;metadata;genomes;contigs;binsize;unlensed;storageMode;countKind;coords;chromnames;get chromsizes(){return this.chromsizeCache??=new Map(this.chromnames.map((t,n)=>[t,this.contigLengths[n]])),this.chromsizeCache}get contigIds(){return this.contigIdCache??=new Map(this.chromnames.map((t,n)=>[t,n])),this.contigIdCache}get names(){return this.nameIndexCache??=ie.of(this.chromnames.map((t,n)=>({name:t,length:this.contigLengths[n]}))),this.nameIndexCache}genomeNames;contigGenomeIds;rawHandle;get handle(){const t=this.resampled?.weightScale??1;return t===1?this.rawHandle:(this.weighted?.scale!==t&&(this.weighted={scale:t,handle:cf(this.rawHandle,t)}),this.weighted.handle)}weighted=null;pixelStore;get store(){return this.resampled??this.pixelStore}get storedPixels(){return this.pixelStore}resampled=null;census=null;censusWanted=!1;chromOffset;genomeOffset;genomeIds;closed=!1;fullContigTable=null;fullGenomeTable=null;contigIdCache=null;chromsizeCache=null;nameIndexCache=null;contigLengths;static async open(t,n,s={}){if(await n.mount(),da(n.readBytes(0,4)))return et.fromHic(t,n);if(await qh(n)){const i=await ba(n);throw new C("pairs-binning-needed","This is a .pairs file: a list of contacts with no resolution of its own. Choose a bin size to build a map at.",{contigs:i.contigs.length,assembly:i.assembly,sorted:i.sorted})}const o=s.metacool===!1?".cool, .mcool or .scool":".cool, .mcool, .scool or .metacool";if(ma(n.readBytes(0,2)))throw new C("not-hdf5",`This file is gzip-compressed. HDF5 is read in place and cannot be decompressed on the fly, so a ${o} must be decompressed first. A .pairs.gz is read compressed — but this one carries no \`## pairs format\` line, so it is not one.`,{});if(!df(n))throw new C("not-hdf5",`${Mt(t).path} does not start with the HDF5 signature, so it is not a ${o} whatever its name says. A download that stopped short, an HTML page saved under the file’s name, or a text matrix look like this.`,{});const r=await Sl(t,n,Mt(t).group);try{return s.listingAgreed!==!0&&hf(r,n),et.fromHandle(r,s)}catch(i){if(r.close(),!(i instanceof C)&&i instanceof Error){const a=Mt(t).group;throw new C("format",`${Mt(t).path}${a===""?"":`::${a}`} could not be read as a cooler container. HDF5 said: ${i.message}. The file opens as HDF5, so this is a group, dataset or attribute the reader expected and did not find.`,{hdf5:i.message})}throw i}}static fromHic(t,n){const{group:s}=Mt(t),o=/^\/resolutions\/(\d+)$/.exec(s),r=So.open(n,o===null?{}:{binSize:Number(o[1])});if(!r.hasAnyMatrix())throw new C("unsupported",`This .hic carries no base-pair matrix at ${r.binSize} bp. Its resolutions are ${r.resolutions.join(", ")}.`,{binSize:r.binSize,resolutions:r.resolutions});const i=Oh(t,r),a=i.attrs();return new et({uri:t,handle:i,layout:{kind:"hic",group:s,entries:r.resolutions.map(c=>String(c))},attrs:a,contigs:i.readTable("chroms"),chromOffset:i.readNumeric("indexes/chrom_offset"),store:new _h(r)})}static fromPairs(t){const n=Qh({uri:t.uri,header:t.header,pixels:t.pixels,rungs:t.rungs,indexed:t.indexed,declaredRecords:t.declaredRecords??null});return new et({uri:t.uri,handle:n,layout:{kind:"pairs",group:`/resolutions/${t.pixels.binSize}`,entries:t.rungs.map(s=>String(s))},attrs:n.attrs(),contigs:n.readTable("chroms"),chromOffset:n.readNumeric("indexes/chrom_offset"),store:new Vh(t.pixels)})}static fromScool(t,n,s,o){const r=rr(n.entries??[],o),i=t.at(ts(n,(n.entries??[])[0])),a=Ui(t,n,s).attrs,c={...s};for(const f of af)c[f]===void 0&&a[f]!==void 0&&(c[f]=a[f]);const l=i.readNumeric("indexes/chrom_offset"),u=Ho(i.dtype("pixels/count")),h=Number(l[l.length-1]??0);return new et({uri:t.uri,handle:t,tables:i,layout:n,attrs:c,contigs:i.readTable("chroms",void 0,void 0,Es),chromOffset:l,store:new rn(t,n,r,h,u)})}static fromHicPro(t,n){if(!n.bins.fixed||n.bins.binsize===null)throw new C("variable-bins",`The viewer supports fixed-bin files only, and ${n.binsName} is not one: its intervals are of differing widths, which is what a fragment-level map (\`GENOME_FRAGMENT\` in HiC-Pro's config) looks like. Re-run HiC-Pro with a \`BIN_SIZE\`, or open the fixed-bin matrix beside this one.`,{"bin-type":"variable","bin-size":null,bins:n.binsName});const s=Kh(t,n);return new et({uri:t,handle:s,layout:{kind:"hicpro",group:"/"},attrs:s.attrs(),contigs:s.readTable("chroms"),chromOffset:n.bins.chromOffset})}static fromHandle(t,n={}){const s=t.attrs(),o=n.metacool===void 0?{}:{metacool:n.metacool},r=fl(t,s,o);if(bl(t,r,s,o),r.kind==="scool")return et.fromScool(t,r,s,null);if(r.kind!=="metacool")return new et({uri:t.uri,handle:t,layout:r,attrs:s,contigs:t.readTable("chroms",void 0,void 0,Es),chromOffset:t.readNumeric("indexes/chrom_offset")});if(!t.has("indexes/genome_offset"))throw new st("indexes/genome_offset is missing");return new et({uri:t.uri,handle:t,layout:r,attrs:s,genomes:t.readTable("genomes",void 0,void 0,rf),contigs:t.readTable("contigs",void 0,void 0,Es),chromOffset:t.readNumeric("indexes/chrom_offset"),genomeOffset:t.readNumeric("indexes/genome_offset")})}fullContigs(){return this.fullContigTable??=this.tables.readTable(this.layout.kind==="metacool"?"contigs":"chroms"),this.fullContigTable}fullGenomes(){return this.genomes===null?null:(this.fullGenomeTable??=this.handle.readTable("genomes"),this.fullGenomeTable)}constructor(t){this.uri=t.uri,this.unlensed=t.unlensed??null,this.rawHandle=t.handle,this.tables=t.tables??t.handle,this.layout=t.layout,this.entries=t.handle.rootEntries,this.entryGroup=t.handle.rootEntryGroup,this.genomes=t.genomes??null,this.contigs=t.contigs,this.chromOffset=t.chromOffset,this.genomeOffset=t.genomeOffset??new Float64Array(0),this.info=Al(t.attrs),this.metadata=Ml(t.attrs),this.storageMode=this.info["storage-mode"];const n=this.info["bin-size"];if(n===null||n<=0)throw new st(`attrs['bin-size'] must be positive, got ${V(n)}`,{"bin-size":n});this.binsize=n,this.chromnames=this.contigs.strings("name"),this.genomeNames=this.genomes===null?[]:this.genomes.strings("name");const s=lf(this.contigs,"length");this.contigGenomeIds=this.genomes===null?new Int32Array(0):uf(this.contigs,"genome_id"),this.coords=new Tl(this.binsize,this.chromOffset,s),this.contigLengths=s,this.genomeIds=new Map;for(let o=0;o<this.genomeNames.length;o++)this.genomeIds.set(this.genomeNames[o],o);this.countKind=Ho(this.tables.dtype("pixels/count")),this.pixelStore=t.store??new Vi(this.rawHandle,this.nBins,this.countKind),this.validateLight()}get hasGenomes(){return this.genomes!==null}get hasWeights(){return this.handle.has(`bins/${Ne}`)}get scoreColumns(){return this.store.scoreColumns()}get nGenomes(){return this.genomes?.length??0}get nContigs(){return this.contigs.length}get nBins(){return this.coords.nBins}get shape(){return[this.nBins,this.nBins]}hasGenome(t){return this.genomeIds.has(t)}hasContig(t){return this.contigIds.has(t)}genomeId(t){const n=this.genomeIds.get(t);if(n===void 0)throw new C("unknown-label",`Genome ${V(t)} not found. Available: ${_e(this.displayGenomes().map(s=>this.genomeNames[s]))}`,{label:t});return n}contigId(t){const n=this.contigIds.get(t);if(n===void 0)throw new C("unknown-label",`Contig ${V(t)} not found. Available: ${_e(this.chromnames)}`,{label:t});return n}extent(t){const[n,s,o]=Jh(t,this.chromsizes);return nf(this.chromOffset,this.contigId(n),s,o,this.binsize)}offset(t){return this.extent(t)[0]}genomeContigExtent(t){const n=typeof t=="number"?t:this.genomeId(t);return[this.genomeOffset[n],this.genomeOffset[n+1]]}genomeExtent(t){const n=typeof t=="number"?t:this.genomeId(t),[s,o]=this.genomeContigExtent(n);if(o<=s)return[0,0];this.assertContiguous(n,s,o);const r=this.chromOffset[s],i=this.chromOffset[o];return i<=r?[0,0]:[r,i]}assertContiguous(t,n,s){const o=this.contigGenomeIds;if(o[n]!==t||o[s-1]!==t||n>0&&o[n-1]===t||s<o.length&&o[s]===t)throw new C("bad-ordering",`Genome ${V(this.genomeNames[t])} is not contiguous in bin space under contig-ordering ${V(this.info.ordering)}; a single bin range cannot represent it, so the file's ordering attribute does not describe its actual contig layout. Re-create the file with a genome-grouped ordering.`,{genome:this.genomeNames[t],genomeId:t,contigs:[n,s]})}contigExtent(t){const n=typeof t=="number"?t:this.contigId(t),[s,o]=this.coords.contigBinExtent(n);return o<=s?[0,0]:[s,o]}displayGenomes(){const t=[];for(let n=0;n<this.genomeNames.length;n++)this.genomeNames[n]!==ke&&t.push(n);return t}displayBinExtent(){const t=[0,this.nBins],n=this.genomeIds.get(ke);if(n===void 0)return t;const[s,o]=this.genomeExtent(n);return o<=s?t:s===0?[o,this.nBins]:o===this.nBins?[0,s]:t}unassignedStats(){const t=this.nContigs,n=this.nBins,s=this.genomeIds.get(ke);if(s===void 0||this.genomes===null)return null;const o=Number(this.genomes.get("n_contigs",s)??0),r=Number(this.genomes.get("n_bins",s)??0);return{genomeIndex:s,contigs:o,bins:r,totalContigs:t,totalBins:n,contigFraction:t>0?o/t:0,binFraction:n>0?r/n:0}}genomeDensity(t){const[n,s]=this.genomeExtent(t);if(s<=n)return 0;const o=this.binOffsets();return o[s]-o[n]}binOffsets(){return this.store.binOffsets()}genomeDensities(){const t=new Float64Array(this.nGenomes);if(this.genomes===null)return t;const n=this.binOffsets();for(const s of this.displayGenomes()){const[o,r]=this.genomeExtent(s);r>o&&(t[s]=n[r]-n[o])}return t}async matrix(t,n=un.range){return Kc(this,t,n)}async genomeMatrix(t){const n=this.genomeExtent(t);return this.matrix({rows:n},un.binSelection)}async genomePairMatrix(t,n){return this.matrix({rows:this.genomeExtent(t),cols:this.genomeExtent(n)},un.binSelection)}async aggregateSparse(t,n,s={}){const o=On(t.rows,this.nBins),r=On(t.cols??t.rows,this.nBins),i=Te(o,r,this.storageMode),a=Ol(o,r,this.coords,this.contigGenomeIds,n,i.mode,this.storageMode==="symmetric-upper",qt),c=t.balance===!0?this.weightSlices(o,r):null;return await this.store.forEachWindow(o,r,i,l=>{for(let u=0;u<l.length;u++){const h=l.bin1[u],f=l.bin2[u],d=c===null?l.count[u]:l.count[u]*kn(c,o,r,h)*kn(c,o,r,f);a.place(h,f,d)}},vr(s,t.value)),{...a.finish(),contigsPerCell:a.perCell}}async pooledMatrix(t,n,s={}){const o=On(t.rows,this.nBins),r=On(t.cols??t.rows,this.nBins),i=Te(o,r,this.storageMode),a=o[0]===r[0]&&o[1]===r[1],c=this.contigGenomeIds,l=Qo(this.coords,o[0],o[1],n,qt,c),u=a?l:Qo(this.coords,r[0],r[1],n,qt,c),h=Vs(o,r,l,u,i.mode,this.storageMode==="symmetric-upper",!0),f=t.balance===!0?this.weightSlices(o,r):null;return await this.store.forEachWindow(o,r,i,d=>{for(let m=0;m<d.length;m++){const g=d.bin1[m],w=d.bin2[m],p=f===null?d.count[m]:d.count[m]*kn(f,o,r,g)*kn(f,o,r,w);h.place(g,w,p)}},vr(s,t.value)),{...h.finish(),binsPerCell:l.stride,contigsPerCell:Math.max(l.contigsPerCell,u.contigsPerCell),rowMembers:l,colMembers:u}}async selectionMatrix(t,n,s={}){const o=s.byGenome===!0?this.contigGenomeIds:void 0,r=Nl(this.nBins,t,n,s.cellCap===void 0?qt:s.cellCap,o),i=[0,this.nBins],a=Vs(i,i,r,r,Te(i,i,this.storageMode).mode,this.storageMode==="symmetric-upper"),c=s.balance===!0?this.weightSlices(i,i):null;return await this.store.forEachBands(t.map(({extent:u})=>[u[0],u[1]]),u=>{for(let h=0;h<u.length;h++){const f=u.bin1[h],d=u.bin2[h],m=c===null?u.count[h]:u.count[h]*c.rows[f]*c.cols[d];a.place(f,d,m)}},s),{...a.finish(),binsPerCell:r.stride,contigsPerCell:r.contigsPerCell,ids:r.ids,pooling:r}}static withLens(t,n){const s=n.original.genome!==void 0;if(t.hasGenomes&&!s)return{map:t,refusal:"An edit is not yet drawn on a map of several genomes."};if(t.layout.kind==="scool")return{map:t,refusal:"An edit is not yet drawn on a single-cell file."};const o=du(n,t.chromnames,t.contigLengths,{always:s});if(o===null)return{map:t,refusal:null};if("refusal"in o)return{map:t,refusal:o.refusal};const r=bo.of(t.coords,t.chromnames,o.assembly),i=fu(r),a={...t.rawHandle.attrs(),nchroms:r.names.length,nbins:r.nBins};return{map:new et({uri:t.uri,handle:hu(t.rawHandle,r,i,a),layout:t.layout,attrs:a,contigs:i,chromOffset:r.chromOffset,store:new uu(t.store,r,t.storageMode==="symmetric-upper"),unlensed:t}),refusal:null}}static coarsened(t,n){if(!Number.isInteger(n)||n<1)return{map:t,refusal:`A resolution is a whole number of this map's bins, not ${n} of them.`};if(n===1)return{map:t,refusal:null};if(t.layout.kind==="scool")return{map:t,refusal:"A single-cell file is not yet measured at a resolution you added; measure it at one it stores."};const s=yo.of(t.chromOffset,n),{nnz:o,...r}=t.handle.attrs(),i={...r,"bin-size":t.binsize*n,nbins:s.nBins};return{map:new et({uri:t.uri,handle:bu(t.handle,s,i),layout:t.layout,attrs:i,contigs:t.contigs,chromOffset:s.chromOffset,...t.genomes===null?{}:{genomes:t.genomes,genomeOffset:t.genomeOffset},store:new wu(t.store,s,t.storageMode),...t.unlensed===null?{}:{unlensed:t.unlensed}}),refusal:null}}async picture(t,n={}){const s=[0,this.nBins],o=n.balance===!0?this.weightSlices(s,s).rows:null,r=await Yl({store:this.store,coords:this.coords,layout:t,weights:o,...n.value===void 0?{}:{value:n.value},...n.gather===void 0?{}:{gather:n.gather},...n.cancelled===void 0?{}:{cancelled:n.cancelled},...n.onProgress===void 0?{}:{onProgress:n.onProgress}});return r===null?null:{levels:Xl({n:t.n,cells:r.cells},r.quantizer),quantizer:r.quantizer,histogram:r.histogram,pixels:r.pixels,...r.contacts===void 0?{}:{contacts:r.contacts}}}binColumns(){if(!this.tables.has("bins"))return[];const t=[];for(const n of this.tables.keys("bins")){const s=Er(this.tables.dtype(`bins/${n}`));s!==null&&t.push({name:n,text:s})}return t}binColumn(t,n,s){const o=`bins/${t}`;if(!this.tables.has(o))throw new C("unsupported",`This file has no /${o} column.`,{column:t});const r=Math.max(0,Math.min(n,this.nBins)),i=Math.max(r,Math.min(s,this.nBins));return t===Ne&&this.tables===this.rawHandle?this.handle.readNumeric(o,r,i):Er(this.tables.dtype(o))===!0?this.tables.readStrings(o,r,i):this.tables.readNumeric(o,r,i)}weightSlices(t,n){const s=`bins/${Ne}`;if(!this.handle.has(s))throw new C("unsupported",`This file has no /${s} column, so there are no weights to balance with. Run \`cooler balance\` on it, or view the raw counts.`,{column:Ne});const o=this.handle.readNumeric(s,t[0],t[1]),r=n[0]===t[0]&&n[1]===t[1]?o:this.handle.readNumeric(s,n[0],n[1]);return{rows:o,cols:r}}aggregate(t,n){return kl(t,this.coords,this.contigGenomeIds,n,this.storageMode==="symmetric-upper")}get cells(){return this.layout.kind==="scool"?this.layout.entries??[]:[]}get activeCells(){return this.pixelStore instanceof rn?this.pixelStore.names:[]}selectCells(t){if(this.layout.kind!=="scool")throw new C("unsupported",`${this.uri} is not a single-cell container, so it has no cells to choose.`,{layout:this.layout.kind});const n=rr(this.cells,t);this.pixelStore=new rn(this.handle,this.layout,n,this.nBins,this.countKind)}async scanCells(t){if(!(this.pixelStore instanceof rn))throw new C("unsupported",`${this.uri} is not a single-cell container, so it has no cells to walk.`,{layout:this.layout.kind});await this.pixelStore.scanPerCell(t)}cellTable(){const t=this.cells,n=t.map(a=>this.handle.attrsAt(ts(this.layout,a))),s=["name"],o={name:t},r=new Set;for(const a of n)for(const c of Object.keys(a))r.add(c);const i=[...r].filter(a=>!vs.includes(a)&&a!=="metadata").sort();for(const a of[...vs,...i]){if(!r.has(a))continue;const c=n.map(u=>u[a]);if(!vs.includes(a)&&c.every(u=>u===c[0]))continue;c.every(u=>typeof u=="number"||typeof u=="boolean")?o[a]=Float64Array.from(c,u=>Number(u)):o[a]=c.map(u=>u==null?"":String(u)),s.push(a)}return De(t.length,s,o)}get nnz(){return this.store.nnz??0}async scanPixels(t){await this.store.scanAll(t)}async validateDeep(t){const n=[],s=new Set,o=(b,y)=>{s.has(b)||(s.add(b),n.push(y))},r=this.nBins,i=this.storageMode==="square",a=this.binOffsets(),c=this.nnz;a.length!==r+1?n.push(`bin1_offset length (${a.length}) != ${r+1}`):(a[0]!==0||a[r]!==c)&&n.push(`bin1_offset endpoints (${a[0]}, ${a[r]}) do not bracket the table (0, ${c})`);for(let b=1;b<a.length;b++)if(a[b]<a[b-1]){o("monotone",`bin1_offset is not non-decreasing: bin1_offset[${b-1}]=${a[b-1]} > bin1_offset[${b}]=${a[b]}`);break}let l=0;const u=this.countKind!=="f";let h=-1,f=-1;const d=a.length===r+1;let m=0,g=0;const w=t?.cancelled;if(await this.pixelStore.scanAll({onProgress:t?.onProgress,storedRows:!0,onChunk:b=>{if(w?.()===!0)return!1;for(let y=0;y<b.length;y++,g++){const A=b.bin1[y],x=b.bin2[y],E=b.count[y];if(u&&(l+=E),(A<0||x<0||A>=r||x>=r)&&o("range",`pixel bin ids out of range [0, ${r}) at row ${g}`),!i&&A>x&&o("triangle",`pixels are not upper-triangular (bin1_id <= bin2_id): row ${g} is (${A}, ${x})`),h>=0&&!(h<A||h===A&&f<=x)&&o("order",`pixels are not sorted by (bin1_id, bin2_id) at row ${g}`),d){for(;m<r&&a[m+1]<=g;)m++;m!==A&&o("index",`bin1_offset disagrees with pixels/bin1_id at row ${g}: the index places it in bin ${m}, the pixel says ${A}`)}h=A,f=x}return!0}}),w?.()===!0){const b=new Error("cancelled");throw b.name="AbortError",b}const p=this.info.sum;return u&&p!==null&&p!==l&&n.push(`attrs['sum'] (${p}) != the sum of pixels/count (${l})`),{ok:n.length===0,problems:n,note:`Scanned ${c} pixels for range, upper-triangle, sort order and bin1_offset agreement${u?", and reconciled attrs['sum']":" (float counts: sum not reconciled)"}. The /bins geometry checks of the Python validate() are not run — this reader never reads /bins.`}}validateLight(){const t=(s,o={})=>{throw new st(s,o)};this.nContigs===0&&t("/contigs table is empty");for(const s of of)this.contigs.columns.includes(s)||t(`Missing column in /contigs: ${s}`);if(this.chromOffset.length!==this.nContigs+1&&t(`chrom_offset length (${this.chromOffset.length}) != ${this.nContigs+1}`),this.chromOffset[0]!==0&&t(`chrom_offset endpoints (${this.chromOffset[0]}, ${this.nBins}) do not bracket the table`),this.genomes!==null){this.nGenomes===0&&t("/genomes table is empty");for(const s of sf)this.genomes.columns.includes(s)||t(`Missing column in /genomes: ${s}`);this.contigs.columns.includes("genome_id")||t("Missing column in /contigs: genome_id"),this.handle.isSoftLink("chroms")||t("/chroms must be a soft link to /contigs for cooler compatibility"),this.genomeOffset.length!==this.nGenomes+1&&t(`genome_offset length (${this.genomeOffset.length}) != ${this.nGenomes+1}`),(this.genomeOffset[0]!==0||this.genomeOffset[this.nGenomes]!==this.nContigs)&&t(`genome_offset endpoints (${this.genomeOffset[0]}, ${this.genomeOffset[this.nGenomes]}) do not bracket the table (0, ${this.nContigs})`)}const n=[["nchroms",this.info.ncontigs,this.nContigs,"len(/contigs)"],...this.genomes===null?[]:[["ngenomes",this.info.ngenomes,this.nGenomes,"len(/genomes)"]],["nbins",this.info.nbins,this.nBins,"len(/bins)"],["nnz",this.info.nnz,this.tables.datasetLength("pixels/bin1_id"),"len(/pixels)"]];for(const[s,o,r,i]of n)o!==null&&o!==r&&t(`attrs[${V(s)}] (${o}) != ${i} (${r})`)}async resample(t,n={}){if(t===null)return this.resampled=null,null;const s=this.resampleRefusal();this.censusWanted=!0,n.census!==void 0&&(this.census=Promise.resolve(n.census));let o;s!==null?o=Promise.reject(s):(this.census??=sr(this.pixelStore,this.chromOffset,{...n.onProgress===void 0?{}:{onProgress:n.onProgress},cancelled:()=>this.closed||n.cancelled?.()===!0}),o=this.census,o.catch(i=>{i instanceof DOMException&&i.name==="AbortError"&&this.census===o&&(this.census=null)}));const r=new oh(this.pixelStore,{starts:this.chromOffset,names:this.chromnames},t,o);return this.resampled=r,r.ready()}get declaredContacts(){const t=this.info.sum;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}async countContacts(t={}){const n=this.declaredContacts;if(n!==null)return n;if(this.resampleRefusal()!==null)return null;const s=t.pause;this.census??=sr(this.pixelStore,this.chromOffset,{...t.onProgress===void 0?{}:{onProgress:t.onProgress},...s===void 0?{}:{pause:()=>s(()=>this.censusWanted)},cancelled:()=>this.closed});try{return(await this.census).total}catch{return null}}async takenCensus(){if(this.census===null)return null;try{return await this.census}catch{return null}}resampleRefusal(){return this.layout.kind==="scool"?new C("unsupported","A single-cell container’s map is a sum of its cells rather than one library, so it is not resampled as one. Open one cell, or a pseudo-bulk written as a cooler, to resample it.",{resample:!0,layout:"scool"}):this.storageMode!=="symmetric-upper"?new C("unsupported","This map stores both triangles, so each contact would be drawn twice. Resampling reads upper-triangular files — cooler’s default.",{resample:!0,storageMode:this.storageMode}):null}close(){this.closed||(this.closed=!0,this.rawHandle.close())}}function cf(e,t){const n=`bins/${Ne}`;return new Proxy(e,{get(s,o){if(o==="readNumeric")return(i,a,c)=>{const l=s.readNumeric(i,a,c);if(i!==n)return l;const u=new Float64Array(l.length);for(let h=0;h<l.length;h++)u[h]=l[h]*t;return u};const r=Reflect.get(s,o,s);return typeof r=="function"?r.bind(s):r}})}function lf(e,t){const n=e.data[t];return n instanceof Float64Array?n:Float64Array.from(e.numbers(t))}function Er(e){try{return"SOU".includes(Oi(e))}catch{return null}}function uf(e,t){const n=e.data[t];if(ArrayBuffer.isView(n)&&!(n instanceof DataView)&&!(n instanceof BigInt64Array)){const s=new Int32Array(n.length);return s.set(n),s}return Int32Array.from(e.numbers(t))}function vr(e,t){return t===void 0?e:{...e,value:t}}function On(e,t){const n=Math.min(Math.max(Math.trunc(e[0]),0),t),s=Math.min(Math.max(Math.trunc(e[1]),n),t);return[n,s]}function kn(e,t,n,s){return s>=t[0]&&s<t[1]?e.rows[s-t[0]]:s>=n[0]&&s<n[1]?e.cols[s-n[0]]:1}function hf(e,t){if(!t.isRemote||!ul(e,e.attrs()))return;const{path:n}=Mt(e.uri);throw new C("scool-listing-cost",`${n} is a single-cell container, and listing its cells is not a bounded read: the names live in HDF5 link records spread across the whole object. Reading them over the network costs either one download of ${At.bytes(t.size)} or a few percent of that in about a thousand separate requests. Choose which to pay, or open a local copy, where neither cost applies.`,{path:n,size:t.size})}const ff=[137,72,68,70,13,10,26,10];function df(e){for(const t of[0,512,1024,2048,4096,8192]){if(t+8>e.size)return!1;const n=e.readBytes(t,8);if(n.length===8&&ff.every((s,o)=>n[o]===s))return!0}return!1}const Le=16,mf=4,gf=64,wf=2048,pf=160,bf={width:gf,coarseCells:wf,endDepth:pf},Cr=48,yf=8,Af=[0,1,2,4,8,16,32,64,128,256,512,1024,2048],Ma=.01,Mf=.1;function Cs(e){if(e.length===0)return Number.NaN;e.sort();const t=Math.max(1,Math.floor(e.length*(1-Ma)));let n=0;for(let s=0;s<t;s++)n+=e[s];return n/t}function $r(e){if(e.length===0)return Number.NaN;e.sort();const t=e.length>>1;return e.length%2===1?e[t]:(e[t-1]+e[t])/2}class nn{data=new Float64Array(64);length=0;push(t){if(this.length===this.data.length){const n=new Float64Array(this.data.length*2);n.set(this.data),this.data=n}this.data[this.length++]=t}view(){return this.data.subarray(0,this.length)}}function xf(e,t){const{n,width:s,band:o,coarse:r,marginal:i,kept:a,sequenceOf:c}=e,l=new Float64Array(n).fill(1);if(!t){const k=new nn;for(let H=0;H<n;H++)i[H]>0&&k.push(i[H]);const G=$r(k.view());for(let H=0;H<n;H++)l[H]=i[H]>=Mf*G&&G>0?i[H]/G:Number.NaN}for(let k=0;k<n;k++)a[k]===0&&(l[k]=Number.NaN);let u=1;for(let k=0;k<n;k++)a[k]>u&&(u=a[k]);const h=new Float64Array(n);for(let k=0;k<n;k++)h[k]=a[k]/u;const f=new Float64Array(s).fill(Number.NaN),d=new nn;for(let k=0;k<s;k++){if(!t){let lt=0,U=0,q=0;for(let K=0;K+k<n;K++){const bt=h[K]*h[K+k],wt=o[K*s+k]*bt,yt=l[K]*l[K+k]*bt;!(wt>=0)||!(yt>0)||(lt+=wt,U+=yt,q++)}if(q<8||!(U>0))continue;const tt=lt/U;if(f[k]=tt,k===0||!(tt>0))continue;let nt=0;for(let K=0;K+k<n;K++){const bt=h[K]*h[K+k],wt=o[K*s+k]*bt,yt=l[K]*l[K+k]*bt;!(wt>=0)||!(yt>0)||(nt+=(wt-yt*tt)**2/(yt*tt))}d.push(nt/Math.max(1,q-1));continue}const G=new nn;for(let lt=0;lt+k<n;lt++){const U=o[lt*s+k]/(l[lt]*l[lt+k]);U>=0&&G.push(U)}if(G.length<8)continue;const H=G.view();if(f[k]=Cs(H),k===0)continue;const mt=Math.max(1,Math.floor(H.length*(1-Ma)));let gt=0,ct=0;for(let lt=0;lt<mt;lt++)gt+=H[lt],ct+=H[lt]*H[lt];const _t=gt/mt,ge=Math.max(0,ct/mt-_t*_t);_t>0&&d.push(ge/_t)}const m=r.factor,g=r.n,w=new Int32Array(g).fill(-1),p=new Float64Array(g),b=new Float64Array(g);for(let k=0;k<n;k++){const G=r.of[k];w[G]=c[k],l[k]>0&&(p[G]+=l[k],b[G]++)}for(let k=0;k<g;k++)p[k]=b[k]>0?p[k]/b[k]:Number.NaN;const y=[],A=new nn,x=new Float64Array(g),E=new Float64Array(g),S=new Int32Array(g);let v=0,I=0;for(let k=0;k<g;k++){let G=vt(k,k,g);for(let H=k;H<g;H++,G++){const mt=p[k]*p[H],gt=r.values[G]/mt;if(gt>=0)if(w[k]===w[H]){const ct=H-k;if(ct===0)continue;(y[ct]??=new nn).push(gt),x[ct]+=r.values[G],E[ct]+=mt,S[ct]++}else A.push(gt),v+=r.values[G],I+=mt}}const N=new Float64Array(y.length).fill(Number.NaN);for(let k=1;k<y.length;k++){const G=y[k];G===void 0||G.length<4||(N[k]=t?Cs(G.view()):E[k]>0?x[k]/E[k]:Number.NaN)}const B=new Float64Array(n+1).fill(Number.NaN),z=k=>{const G=k/m,H=Math.floor(G),mt=H+1,gt=N[H],ct=N[mt];return H>=1&&gt>0&&ct>0?Math.exp(Math.log(gt)+(Math.log(ct)-Math.log(gt))*(G-H)):H>=1&&gt>0?gt:ct>0&&H<1?ct:Number.NaN};let R=0;for(let k=0;k<=n;k++){const G=k<s&&f[k]>0?f[k]:k>=1?z(k):Number.NaN;G>0&&(B[k]=G,R=k)}for(let k=1;k<=R;k++)B[k]>0||(B[k]=B[k-1]);for(let k=1;k<=R;k++)B[k]>B[k-1]&&(B[k]=B[k-1]);const P=Sf(B,R);for(let k=R+1;k<=n;k++)B[k]=B[R]*Math.pow(k/Math.max(1,R),P);B[0]>0||(B[0]=B[1]>0?B[1]:1);let L=t?Cs(A.view()):I>0?v/I:Number.NaN;L>0||(L=.5*B[Math.max(1,R)]),L=Math.max(L,B[1]*1e-9);const j=Math.max($r(d.view())||1,1e-12);let W=1;for(;W<2*Le&&W<n&&B[W]>=8*L;)W++;const J=Math.max(mf,Math.min(Le,Math.ceil(W/2)));let Z=0;for(let k=0;k<J;k++)for(let G=0;G<J;G++)Z+=B[Math.min(n,k+G+1)];Z/=J*J;const It=Math.max(L,Z);let pt=0;for(let k=0;k<J;k++)for(let G=0;G<J;G++){const H=B[Math.min(n,k+G+1)];pt+=H*Math.log(H/It)-(H-It)}pt=Math.max(pt/j,1e-9);let Ut=1;for(;Ut<3*Cr&&Ut<n&&B[Ut]>=8*L;)Ut++;const Qt=Math.max(yf,Math.min(Cr,Math.ceil(Ut/3)));let Et=0;for(let k=0;k<Qt;k++)for(let G=0;G<Qt;G++){const H=B[Math.min(n,k+G+1)];Et+=H*Math.log((H+L)/L)-H}return Et=Math.max(Et/j,1e-9),{law:B,trans:L,dispersion:j,bias:l,share:h,window:J,unit:pt,reach:Qt,meetUnit:Et}}function Sf(e,t){const n=Math.max(1,Math.floor(t/10));let s=0,o=0,r=0,i=0,a=0;for(let u=n;u<=t;u++){if(!(e[u]>0))continue;const h=Math.log(u),f=Math.log(e[u]);s++,o+=h,r+=f,i+=h*h,a+=h*f}const c=s*i-o*o,l=s>=2&&c!==0?(s*a-o*r)/c:-1;return Math.max(-3,Math.min(-.3,l))}class xa{constructor(t,n,s){this.cellMap=s,this.law=n.law,this.trans=n.trans,this.dispersion=n.dispersion,this.window=n.window,this.unit=n.unit,this.reach=n.reach,this.meetUnit=n.meetUnit,this.band=t.band,this.width=t.width,this.sequenceOf=t.sequenceOf,this.coarseOf=t.coarse.of,this.coarseValues=t.coarse.values,this.coarseN=t.coarse.n,this.bias=n.bias,this.share=n.share,this.ends=t.ends??null,this.near=new Float64Array(2*this.window+2),this.logNear=new Float64Array(this.near.length);for(let o=0;o<this.near.length;o++)this.near[o]=this.law[Math.min(this.law.length-1,o)],this.logNear[o]=Math.log(this.near[o])}law;trans;dispersion;window;unit;reach;meetUnit;near;logNear;band;width;sequenceOf;coarseOf;coarseValues;coarseN;bias;share;ends;get n(){return this.cellMap.length}value(t,n){const s=this.cellMap[t],o=this.cellMap[n];return s<0||o<0?Number.NaN:this.original(s,o)}original(t,n){const s=t<n?t:n,o=t<n?n:t,r=o-s;let i;if(r<this.width&&this.sequenceOf[s]===this.sequenceOf[o])i=this.band[s*this.width+r];else{const a=this.ends,c=a!==null&&a.zone[s]>=0&&a.zone[o]>=0,l=c?Wl(a,s,o):void 0;l!==void 0?i=l:c&&a.complete?i=0:i=this.coarseValues[vt(this.coarseOf[s],this.coarseOf[o],this.coarseN)]}return i/(this.bias[t]*this.bias[n])}weight(t,n){const s=this.cellMap[t],o=this.cellMap[n];if(s<0||o<0)return 0;const r=this.bias[s]*this.bias[o]*this.share[s]*this.share[o];return r>0?r:0}coarseCell(t){const n=this.cellMap[t];return n<0?-1:this.coarseOf[n]}coarseValue(t,n){return this.coarseValues[t<=n?vt(t,n,this.coarseN):vt(n,t,this.coarseN)]}holds(t){const n=this.cellMap[t];return n>=0&&this.bias[n]>0}expectedAt(t){return this.law[Math.min(this.law.length-1,Math.max(0,t))]}}const Nr=new Float64Array(Le*Le),$s=new Float64Array(Le*Le);function Sa(e,t,n,s="trans"){const o=e.near,r=e.logNear,i=e.trans,a=e.window;let c=0,l=0,u=0,h=0;for(let p=0;p<a;p++){const b=t.cell+t.dir*p,y=b>=t.lo&&b<t.hi;for(let A=0;A<a;A++){const x=n.cell+n.dir*A;let E=Number.NaN,S=0;y&&x>=n.lo&&x<n.hi&&(l++,E=e.value(b,x),S=e.weight(b,x),E>=0&&S>0?(c++,u+=S*E,h+=S):E=Number.NaN),Nr[p*a+A]=E,$s[p*a+A]=S}}const f=s==="local"&&h>0?Math.max(i,u/h):i;let d=0,m=0;const g=Math.log(f);for(let p=0;p<a;p++)for(let b=0;b<a;b++){const y=Nr[p*a+b];if(Number.isNaN(y))continue;const A=p+b+1;d+=$s[p*a+b]*(y*(r[A]-g)-(o[A]-f)),m+=$s[p*a+b]*o[A]}const w=e.dispersion;return{score:d/w,seen:c,reached:l,contacts:Math.max(0,u-h*i)/w,expected:m/w}}function Br(e,t,n){const s=t.hi-t.lo,o=Math.max(1,Math.min(n,Math.floor(s/2))),r=new Int32Array(o),i=new Int32Array(o);let a=0;for(let c=0;c<3*o&&a<o;c++){const l=t.cell+t.dir*c;if(l<t.lo||l>=t.hi)break;e.holds(l)&&(r[a]=l,i[a]=c,a++)}return{cells:r,distance:i,length:a}}function If(e,t,n){const s=new Set,o=new Set;for(let a=0;a<t.length;a++)s.add(e.coarseCell(t.cells[a]));for(let a=0;a<n.length;a++)o.add(e.coarseCell(n.cells[a]));let r=0,i=0;for(const a of s)if(!(a<0))for(const c of o){if(c<0)continue;const l=e.coarseValue(a,c);l>=0&&(r+=l,i++)}return i===0||r>2*i*e.trans}function Ef(e,t,n){const s=e.reach,o=Br(e,t,s),r=Br(e,n,s),i=o.length*r.length,a={score:0,gap:0,amplitude:0,brightness:0,level:0,ideal:0,seen:0,reached:i,contacts:0};if(i===0||!If(e,o,r))return a;const c=new Float64Array(i),l=new Float64Array(i),u=new Int32Array(i);let h=0,f=0,d=0;for(let b=0;b<o.length;b++)for(let y=0;y<r.length;y++){const A=e.value(o.cells[b],r.cells[y]),x=e.weight(o.cells[b],r.cells[y]);!(A>=0)||!(x>0)||(c[h]=A,l[h]=x,u[h]=o.distance[b]+r.distance[y]+1,f+=x*A,d+=x,h++)}if(h===0)return a;const m=e.trans;if(f<1.5*d*m)return{...a,level:f/d/m,seen:h};let g=0,w=0;for(let b=0;b<h;b++){const y=e.expectedAt(u[b]);g+=l[b]*(y*Math.log((y+m)/m)-y),w+=l[b]*y}let p={score:Number.NEGATIVE_INFINITY,gap:0,amplitude:0};for(const b of Af){let y=0;for(let E=0;E<h;E++)y+=l[E]*e.expectedAt(u[E]+b);if(!(y>0))continue;const A=Math.min(1,Math.max(1e-6,(f-d*m)/y));let x=0;for(let E=0;E<h;E++){const S=A*e.expectedAt(u[E]+b)+m;x+=l[E]*(c[E]*Math.log(S/m)-(S-m))}if(x>p.score&&(p={score:x,gap:b,amplitude:A}),e.expectedAt(b)<m)break}return{score:p.score/e.dispersion,gap:p.gap,amplitude:p.amplitude,brightness:w>0?Math.max(0,f-d*m)/w:0,level:f/d/m,ideal:g/e.dispersion,seen:h,reached:i,contacts:Math.max(0,f-d*m)/e.dispersion}}function Ia(e,t){const n=new Float64Array(e.n+1).fill(Number.NaN),s=new Float64Array(e.n+1);for(const o of t)for(let r=o.from+1;r<o.to;r++){const i=Sa(e,{cell:r-1,dir:-1,lo:o.from,hi:r},{cell:r,dir:1,lo:r,hi:o.to});s[r]=i.reached===0?0:i.seen/i.reached,i.seen>=Math.max(4,i.reached/4)&&(n[r]=i.score)}return{score:n,seen:s}}const Ea=3;function vf(e,t,n,s,o=.2){const r=[],i=Math.max(1,s>>1),a=Math.max(o*n,Ea);for(const c of t)for(let l=c.from+1;l<c.to;l++){const u=e[l];if(!(u<-a))continue;let h=!0;for(let f=Math.max(c.from+1,l-i);f<=Math.min(c.to-1,l+i);f++){const d=e[f];if(f!==l&&d<u){h=!1;break}if(f<l&&d===u){h=!1;break}}h&&r.push(l)}return r}const Cf=4,Ns=1,$f=.45;function Nf(e,t){const{coarse:n,sequenceOf:s,n:o}=e,r=n.n,i=new Int32Array(r).fill(-1),a=new Int32Array(r+1).fill(o),c=new Float64Array(r),l=new Float64Array(r),u=new Float64Array(r);for(let y=o-1;y>=0;y--){const A=n.of[y];i[A]=s[y],a[A]=y,u[A]++,t.bias[y]>0&&(c[A]+=t.bias[y],l[A]++)}for(let y=0;y<r;y++)c[y]=l[y]>=.6*u[y]?c[y]/l[y]:Number.NaN;const h=[];for(let y=0;y<r;y++){const A=i[y];if(A<0)continue;const x=h[A];x===void 0?h[A]=[y,y+1]:x[1]=y+1}const f=[];if(h.forEach((y,A)=>{y!==void 0&&y[1]-y[0]>=Cf&&f.push(A)}),f.length<3)return[];const d=(y,A)=>{const x=n.values[y<=A?vt(y,A,r):vt(A,y,r)]/(c[y]*c[A]);return x>=0?x:Number.NaN},m=f.map(()=>new Int32Array(f.length).fill(-1));for(let y=0;y<f.length;y++){const[A,x]=h[f[y]];for(let E=y+1;E<f.length;E++){const[S,v]=h[f[E]];let I=0,N=-1,B=-1;for(let z=A;z<x;z++)for(let R=S;R<v;R++){let P=0,L=0;for(let W=-1;W<=1;W++)for(let J=-1;J<=1;J++){const Z=z+W,It=R+J;if(Z<A||Z>=x||It<S||It>=v)continue;const pt=d(Z,It);Number.isNaN(pt)||(P+=pt,L++)}const j=L>0?P/L:0;j>I&&(I=j,N=z,B=R)}N<0||I<4*t.trans||(m[y][E]=N,m[E][y]=B)}}const g=(y,A)=>{const x=[];for(const I of A)I!==y&&m[y][I]>=0&&x.push(m[y][I]);const E=A.filter(I=>I!==y).length;if(x.length<3||E===0)return{mode:-1,agreement:0};let S=-1,v=0;for(const I of x){let N=0;for(const B of x)Math.abs(B-I)<=Ns&&N++;N>v&&(v=N,S=I)}return{mode:S,agreement:v/E}},w=f.map((y,A)=>A),p=w.filter(y=>g(y,w).agreement>=1/3);if(p.length<3)return[];const b=[];return f.forEach((y,A)=>{const{mode:x,agreement:E}=g(A,p);if(x<0||E<$f)return;const S=Math.max(h[y][0],x-Ns),v=Math.min(h[y][1],x+Ns+1);b.push({sequence:y,from:a[S],to:a[v],agreement:E})}),b}const Or=4,kr=Math.log(3),Bf=240;function Of(e,t){const{coarse:n,n:s,sequenceOf:o}=e,r=n.n,i=n.factor;if(r<2*Or+1)return[];const a=new Int32Array(r+1).fill(s),c=new Int32Array(r),l=new Float64Array(r),u=new Float64Array(r);for(let I=s-1;I>=0;I--){const N=n.of[I];a[N]=I,c[N]=o[I];const B=t.bias[I];B>0&&(l[N]+=B,u[N]++)}a[r]=s;for(let I=0;I<r;I++)l[I]=u[I]>0?l[I]/u[I]:Number.NaN;const h=r+1,f=new Float64Array(h*h),d=new Int32Array(h*h);for(let I=0;I<r;I++){let N=0,B=0;for(let z=0;z<r;z++){const R=I<z?I:z,P=I<z?z:I,L=n.values[vt(R,P,r)]/(l[R]*l[P]);if(L>=0&&R!==P){const W=c[R]===c[P]?t.law[Math.min(s,(P-R)*i)]:t.trans;N+=Math.log((L+.5*W)/(1.5*W)),B++}const j=(I+1)*h+(z+1);f[j]=f[j-h]+N,d[j]=d[j-h]+B}}const m=(I,N,B,z)=>{if(I<0||B<0||N>r||z>r||N<=I||z<=B)return Number.NaN;const R=d[N*h+z]-d[I*h+z]-d[N*h+B]+d[I*h+B];return R<4?Number.NaN:(f[N*h+z]-f[I*h+z]-f[N*h+B]+f[I*h+B])/R},g=Or,w=[],p=I=>Number.isNaN(I)?0:I;for(let I=1;I<r;I++)for(let N=I+1;N<r;N++){if(c[I]===c[N-1]&&N-I<2*g)continue;const B=m(I-g,I,N-g,N),z=m(I,I+g,N,N+g),R=m(I-g,I,N,N+g),P=m(I,I+g,N-g,N),L=[[B,R,P,-1,-1],[z,R,P,1,1],[R,B,z,-1,1],[P,B,z,1,-1]];for(const[j,W,J,Z,It]of L){if(!(j>kr))continue;const pt=j-Math.max(p(W),p(J));pt>kr&&w.push({p:I,q:N,rowSide:Z,colSide:It,strength:pt})}}w.sort((I,N)=>N.strength-I.strength);const b=[];for(const I of w)if(b.some(B=>B.rowSide===I.rowSide&&B.colSide===I.colSide&&Math.abs(B.p-I.p)<=g&&Math.abs(B.q-I.q)<=g)||b.push(I),b.length>=Bf)break;const y=[];for(let I=0;I<s;I++)(I===0||o[I]!==o[I-1])&&y.push(I);y.push(s);const A=y.slice(0,-1).map((I,N)=>({from:I,to:y[N+1]})),x=new Int32Array(s);for(let I=0;I<s;I++)x[I]=I;const E=Ia(new xa(e,t,x),A),S=new Set(y),v=I=>{const N=a[I];let B=N,z=-.2*t.unit;for(let R=Math.max(1,N-i);R<=Math.min(s-1,N+i);R++){const P=E.score[R];P<z&&(B=R,z=P)}if(B!==N)return B;for(let R=Math.max(0,N-i);R<=Math.min(s,N+i);R++)if(S.has(R))return R;return N};return b.map(I=>{const N=v(I.p),B=v(I.q);return N<=B?{row:N,col:B,rowSide:I.rowSide,colSide:I.colSide,strength:I.strength}:{row:B,col:N,rowSide:I.colSide,colSide:I.rowSide,strength:I.strength}})}class Bo{binsize;n;parts;sequences;cellMap;pictureCells;axisHeld;constructor(t){this.binsize=t.binsize,this.n=t.n,this.parts=t.parts,this.sequences=t.sequences,this.cellMap=t.cellMap,this.pictureCells=t.pictureCells}static of(t,n){const s=n.binsize,o=new Map(n.sequences.map((u,h)=>[u.name,{...u,index:h}])),r=n.sequences.reduce((u,h)=>Math.max(u,h.firstCell+h.cells),0),i=(u,h,f)=>f>=h?u:Math.max(0,Math.min(u,Math.round(f/s))),a=[],c=[],l=[];for(const u of t.sequences){const h=l.length,f=a.length;let d=0;u.parts.forEach((m,g)=>{const w=l.length;if(at(m)){const v=Math.round(m.gap/s);for(let I=0;I<v;I++)l.push(-1);a.push({sequence:u.name,index:g,offset:d,length:m.gap,from:w,to:l.length,piece:null,original:-1,segment:null}),d+=m.gap;return}const p=o.get(m.sequence),b=m.end-m.start;if(p===void 0){a.push({sequence:u.name,index:g,offset:d,length:b,from:w,to:w,piece:m,original:-1,segment:null}),d+=b;return}const y=i(p.cells,p.length,m.start),A=i(p.cells,p.length,m.end),x=Math.max(0,A-y);for(let v=0;v<x;v++)l.push(m.strand===1?p.firstCell+y+v:p.firstCell+A-1-v);const E=l.length,S=x===0?null:{contig:m.sequence,unitStart:w,unitEnd:E,bpStart:(m.strand===1?y:A)*s,bpPerUnit:s,contigLength:p.length,strand:m.strand,bpFrom:m.start,bpTo:m.end};a.push({sequence:u.name,index:g,offset:d,length:b,from:w,to:E,piece:m,original:p.index,segment:S}),d+=b}),c.push({name:u.name,length:d,from:h,to:l.length,partFrom:f,partTo:a.length})}return new Bo({binsize:s,n:l.length,parts:a,sequences:c,cellMap:Int32Array.from(l),pictureCells:r})}get axis(){if(this.axisHeld===void 0){const t=this.parts.flatMap(n=>n.segment===null?[]:[n.segment]);this.axisHeld=t.length===0?null:new Tc(t)}return this.axisHeld}partAt(t){if(!(t>=0&&t<this.n))return null;let n=0,s=this.parts.length-1;for(;n<=s;){const o=n+s>>1,r=this.parts[o];if(t<r.from)s=o-1;else if(t>=r.to)n=o+1;else return r}return null}sequenceAt(t){if(!(t>=0&&t<this.n))return null;let n=0,s=this.sequences.length-1;for(;n<=s;){const o=n+s>>1,r=this.sequences[o];if(t<r.from)s=o-1;else if(t>=r.to)n=o+1;else return r}return null}sequence(t){return this.sequences.find(n=>n.name===t)??null}place(t){const n=this.partAt(t);if(n===null)return null;const s=n.piece;if(s===null||n.segment===null){const i=n.to>n.from?(t-n.from)/(n.to-n.from):0;return{sequence:n.sequence,bp:n.offset+i*n.length,part:n}}const o=Math.max(s.start,Math.min(s.end,Hn(n.segment,t))),r=s.strand===1?o-s.start:s.end-o;return{sequence:n.sequence,bp:n.offset+r,part:n}}unitOf(t,n){const s=this.sequence(t);if(s===null)return null;if(n<=0)return s.from;if(n>=s.length)return s.to;for(let o=s.partFrom;o<s.partTo;o++){const r=this.parts[o];if(n<r.offset||n>=r.offset+r.length)continue;if(n===r.offset)return r.from;const i=r.piece;if(i===null||r.segment===null){const l=(n-r.offset)/r.length;return r.from+l*(r.to-r.from)}const a=n-r.offset,c=i.strand===1?i.start+a:i.end-a;return Math.max(r.from,Math.min(r.to,qs(r.segment,c)))}return s.to}junctions(){const t=[];for(const n of this.sequences)for(let s=n.partFrom+1;s<n.partTo;s++){const o=this.parts[s].from;o>n.from&&o<n.to&&t[t.length-1]!==o&&t.push(o)}return t}boundaries(){const t=[0];for(const n of this.sequences)t[t.length-1]!==n.to&&t.push(n.to);return t}}function kf(e){return`${e.contig}:${(e.start+1).toLocaleString("en-US")}-${e.end.toLocaleString("en-US")}`}function _r(e,t){return`${e}:${_f(t)}`}function _f(e){return(e+1).toLocaleString("en-US")}function Ie(e,t,n){return kf({contig:e,start:t,end:n})}const Tf={debris:"debris",contaminant:"a contaminant",haplotig:"a haplotig",unplaced:"unplaced"};function Ff(e){switch(e.op){case"cut":return`cut ${e.sequence} before ${(e.at+1).toLocaleString("en-US")}`;case"invert":return`turn ${Ie(e.sequence,e.from,e.to)}`;case"move":case"duplicate":{const t=e.op==="move"?"move":"copy",n=e.at===0?`before ${_r(e.into,0)}`:`after ${_r(e.into,e.at-1)}`;return`${t} ${Ie(e.sequence,e.from,e.to)} ${n}${e.strand===-1?", turned":""}`}case"join":return`join ${e.a}’s ${e.aEnd} to ${e.b}’s ${e.bEnd}${e.gap>0?`, ${e.gap.toLocaleString("en-US")} N between`:""}`;case"split":return`split ${e.sequence} before ${(e.at+1).toLocaleString("en-US")}`;case"aside":return e.genome!==void 0&&e.genome!==""?`send ${Ie(e.sequence,e.from,e.to)} to ${e.genome}`:`set aside ${Ie(e.sequence,e.from,e.to)} as ${Tf[e.why]}`;case"bring":return`bring in ${e.sequence}`;case"rotate":return`start ${e.sequence} at ${(e.at+1).toLocaleString("en-US")}`;case"rename":return`rename ${e.sequence} to ${e.name}`;case"reorder":return"reorder the sequences";case"restore":return`put back ${Ie(e.sequence,e.start,e.end)}`;case"place":{const t=e.before===null?"last":`before ${e.before}`,n=e.strand===-1?", turned":"";return e.whole===!0?`put ${e.sequence} ${t}${n}`:`make ${Ie(e.sequence,e.from,e.to)} a sequence of its own, ${t}${n}`}case"layout":{const t=e.sequences.length;return`lay out as in ${e.from} · ${t.toLocaleString("en-US")} sequence${t===1?"":"s"}`}}}const Oo=16,va=1.5,zf=16,Rf=.5,Pf=.25,Lf=4;function Df(e,t,n){const s=[...new Set(e)].filter(i=>i>0&&i>=n).sort((i,a)=>i-a),o=[];let r=t;for(;;){const i=s.filter(c=>c*2<=r);if(i.length===0)break;const a=i.find(c=>r/c<=zf)??i[i.length-1];o.push(a),r=a}return o}function Uf(e){if(e.length<Lf)return Number.NaN;e.sort((o,r)=>o-r);const t=e.length>>1,n=e.length%2===1?e[t]:(e[t-1]+e[t])/2;if(n>0)return n;const s=e.reduce((o,r)=>o+r,0)/e.length;return s>0?s:Number.NaN}function Gf(e,t,n,s=Oo){const o=e.n,r=e.values,i=2*s-1,a=new Float64Array(i+1).fill(Number.NaN);for(let u=1;u<=i;u++){const h=[];for(let f=0;f+u<o;f++){const d=f+u;if(!(d<t||f>=n))continue;const m=r[f*o+d];Number.isNaN(m)||h.push(m)}a[u]=Uf(h)}const c=(t+n)/2;let l=null;for(let u=Math.max(1,t);u<=Math.min(o-1,n);u++){let h=0,f=0,d=0;for(let w=Math.max(0,u-s);w<u;w++)for(let p=u;p<Math.min(o,u+s);p++){const b=a[p-w],y=r[w*o+p];Number.isNaN(y)||!(b>0)||(h+=y,f+=b,d++)}if(d<Pf*s*s||!(f>0))continue;const m=h/f;(l===null||m<l.support-1e-9||m<=l.support+1e-9&&Math.abs(u-c)<Math.abs(l.cut-c))&&(l={cut:u,support:m})}return l}async function Hf(e,t,n,s,o){let r=e.bp,i=n,a=null;const c=Oo;for(const l of s){const u=Math.ceil(t/l),h=Math.round(r/l),f=Math.ceil(va*i/l),d=Math.max(1,h-f),m=Math.min(u-1,h+f);if(m<d)break;const g=Math.max(0,d-3*c),w=Math.min(u,m+3*c),p=await o(e.sequence,g,w,l);if(p===null||p.n!==w-g)break;const b=Gf(p,d-g,m-g);if(b===null||!(b.support<Rf))break;const y=(g+b.cut)*l;if(!(y>0&&y<t))break;r=y,i=l,a={bp:y,binsize:l,support:b.support}}return a}const _n=100,no=[-1.5,2,1.5,2,2.5,1.5,5,4,1,2],Tr=16,Fr=Math.log2(2.5),qf=Math.log2(1.6),Wf=1.2,zr=.1,jf=64;function Qf(e){return 1/(1+Math.exp(-e))}function Yf(e,t=no){let n=t[0]??0;for(let s=0;s<e.length;s++)n+=(t[s+1]??0)*e[s];return Qf(n)}const Rr=new WeakMap;function Vf(e){const{grid:t,expected:n}=e,s=new xa(e.contacts,n,t.cellMap),o=s.unit,r=t.sequences,i=r.map(M=>({from:M.from,to:M.to})),a=Ia(s,i),c=vf(a.score,i,o,s.window),l=t.n,u=new Int8Array(l);for(const M of t.parts)M.piece!==null&&u.fill(M.piece.strand,M.from,M.to);const h=e.contacts.n,f=new Int32Array(h+1);for(let M=0;M<l;M++){const $=t.cellMap[M];$>=0&&f[$+1]++}for(let M=0;M<h;M++)f[M+1]+=f[M];const d=new Int32Array(f[h]),m=f.slice(0,h);for(let M=0;M<l;M++){const $=t.cellMap[M];$>=0&&(d[m[$]++]=M)}const g=M=>{let $=0,O=r.length-1;for(;$<=O;){const _=$+O>>1;if(M<r[_].from)O=_-1;else if(M>=r[_].to)$=_+1;else return _}return-1},w=Math.max(2,Math.round(s.window/4)),p=r.map(M=>new Set([M.from,M.to])),b=r.map(()=>new Set),y=(M,$)=>{let O=-1,_=w+1;for(const T of p[M]){const F=Math.abs(T-$);F<_&&(O=T,_=F)}return O>=0?O:(p[M].add($),$)};for(const M of[...t.junctions(),...c]){const $=g(M);$>=0&&M>r[$].from&&y($,M)}const A=(M,$)=>{if(M<0||M>=h)return[];const O=[];for(let _=f[M];_<f[M+1];_++){const T=d[_],F=$*u[T],D=g(T);if(D<0)continue;const Y=y(D,F<0?T+1:T);b[D].add(Y),O.push(`${D}:${Y}`)}return O},x=new Map,E=(M,$)=>{let O=x.get(M);O===void 0&&(O=new Set,x.set(M,O)),O.add($)};for(const M of e.corners){const $=A(M.rowSide<0?M.row-1:M.row,M.rowSide),O=A(M.colSide<0?M.col-1:M.col,M.colSide);for(const _ of $)for(const T of O)E(_,T),E(T,_)}const S=(M,$)=>x.get(`${M.sequence}:${M.x}`)?.has(`${$.sequence}:${$.x}`)===!0,v=new Set(t.junctions()),I=r.map((M,$)=>[...p[$]].filter(O=>O>=M.from&&O<=M.to).sort((O,_)=>O-_).map(O=>{const _=O>M.from&&O<M.to,T=_&&a.score[O]<-Ea,F=T||_&&v.has(O)&&!(a.score[O]>=0);return{sequence:$,x:O,inside:_,refused:T,open:F,cornered:b[$].has(O)}})),N=(M,$,O)=>{const _=r[M.sequence];if($<0?M.x<=_.from:M.x>=_.to)return null;let T=_.from,F=_.to;for(const D of O)D.sequence===M.sequence&&(D.x<M.x&&D.x>T&&(T=D.x),D.x>M.x&&D.x<F&&(F=D.x));return $<0?{cell:M.x-1,dir:-1,lo:T,hi:M.x}:{cell:M.x,dir:1,lo:M.x,hi:F}},B=new Map,z=M=>`${M.cell}:${M.dir}:${M.lo}:${M.hi}`,R=(M,$,O)=>{const _=z(M),T=z($),F=_<T?`${_}|${T}|${O}`:`${T}|${_}|${O}`;let D=B.get(F);return D===void 0&&(D=Sa(s,M,$,O),B.set(F,D)),D},P=(M,$)=>M===null||$===null?0:R(M,$,"local").score/o,L=P,j=new Map,W=(M,$)=>{const O=z(M),_=z($),T=O<_?`${O}|${_}`:`${_}|${O}`;let F=j.get(T);return F===void 0&&(F=Ef(s,M,$),j.set(T,F)),F};let J=Rr.get(e.contacts);J===void 0&&(J=Nf(e.contacts,n),Rr.set(e.contacts,J));const Z=r.map(()=>[]);for(const M of J){const $=new Map;for(let O=M.from;O<M.to;O++)for(let _=f[O];_<f[O+1];_++){const T=d[_],F=g(T);if(F<0)continue;const D=$.get(F)??[];D.push(T),$.set(F,D)}for(const[O,_]of $)Z[O].push([Math.min(..._),Math.max(..._)+1])}const It=4*e.contacts.coarse.factor,pt=(M,$,O,_,T)=>{if($===_)return!1;for(const[F,D]of Z[$]){const Y=M.dir<0?M.cell+1-D:F-M.cell;for(const[Q,it]of Z[_]){const ot=O.dir<0?O.cell+1-it:Q-O.cell;if(Math.max(0,Y)+Math.max(0,ot)+T>It)return!0}}return!1},Ut=(M,$)=>{let O=0;for(let _=0;_<2;_++)for(let T=0;T<2;T++){const F=M.cell+M.dir*_,D=$.cell+$.dir*T;if(F<M.lo||F>=M.hi||D<$.lo||D>=$.hi)continue;const Y=s.value(F,D);Y>0&&(O=Math.max(O,Y/s.expectedAt(_+T+1)))}return O>0?Math.log2(O):0},Qt=[],Et=e.evidence?.facts,k=M=>{if(Et===void 0)return null;const $=t.partAt(M.cell),O=$?.piece;if($==null||O==null)return null;const _=M.dir===1;if(_?M.cell!==$.from:M.cell!==$.to-1)return null;const T=Et.get(O.sequence);return T===void 0?null:_===(O.strand===1)?O.start===0?T.start:null:O.end===T.length?T.end:null},G=M=>M.some(([$,O])=>k($)!==null||k(O)!==null),H=(M,$)=>{if(Et===void 0||$<=M.from||$>=M.to)return null;const O=t.place($),_=O?.part.piece;if(O==null||_==null||O.sequence!==M.name)return null;const T=Et.get(_.sequence);if(T===void 0||T.gaps.length===0)return null;const F=O.bp-O.part.offset,D=_.strand===1?_.start+F:_.end-F,Y=t.binsize;for(const[Q,it]of T.gaps){if(it+Y<D||Q-Y>D)continue;const ot=Math.max(_.start,Math.min(_.end,Math.round((Q+it)/2)));return O.part.offset+(_.strand===1?ot-_.start:_.end-ot)}return null},mt=(M,$)=>H(M,$)??Zf(t,M,$),gt=M=>M.some($=>$.inside&&H(r[$.sequence],$.x)!==null),ct=M=>{if(!(M.kind==="join"&&(M.exclusivity??0)>=1||M.gain>zr)||!(M.gain>0))return;let O=0,_=0,T=0;for(const[Q,it]of M.made){const ot=M.kind==="join"?W(Q,it):R(Q,it,"local");O+=ot.seen,_+=ot.reached,T+=ot.contacts}let F=0;for(const[Q,it]of M.taken){const ot=R(Q,it,"local");O+=ot.seen,_+=ot.reached,F+=R(Q,it,"trans").expected}M.made.length===0&&(T=F);const D=M.made.reduce((Q,[it,ot])=>Math.max(Q,M.kind==="join"?Math.log2(Math.max(1e-9,W(it,ot).brightness))-qf+Fr:Ut(it,ot)),0),Y=M.kind==="move"?M.points.slice(0,2):M.kind==="join"?[]:M.points;Qt.push({...M,seen:_===0?0:O/_,excess:D,atGap:gt(Y),buried:G(M.made),contacts:T})},_t=(M,$)=>{if(!M.inside)return null;const O=N(M,-1,$),_=N(M,1,$);return O===null||_===null?null:[O,_]};for(const M of I)for(const $ of M){if(!$.refused)continue;const O=r[$.sequence],_=_t($,[]);_!==null&&ct({kind:"split",gain:-L(..._),points:[$],made:[],taken:[_],step:{op:"split",sequence:O.name,at:mt(O,$.x)},stretch:null,target:null,cells:Number.POSITIVE_INFINITY})}const ge=I.flat(),lt=r.length<=jf;for(const M of I){if(M.length===0)continue;const $=r[M[0].sequence];for(let O=0;O<M.length;O++)for(let _=O+1;_<M.length;_++){const T=M[O],F=M[_],D=F.x-T.x,Y=!T.inside&&!F.inside,Q=[T,F],it=_t(T,Q),ot=_t(F,Q),ft=[it,ot].filter(X=>X!==null),Ft=ft.reduce((X,[zt,Bt])=>X+L(zt,Bt),0);if(!Y&&(T.open||F.open||T.cornered&&F.cornered)){const X=[],zt=N(T,-1,Q),Bt=N(F,-1,Q),se=N(T,1,Q),Qe=N(F,1,Q);zt!==null&&Bt!==null&&X.push([zt,Bt]),se!==null&&Qe!==null&&X.push([se,Qe]),ct({kind:"turn",gain:X.reduce((Ae,[Me,xe])=>Ae+P(Me,xe),0)-Ft,points:[T,F],made:X,taken:ft,step:{op:"invert",sequence:$.name,from:mt($,T.x),to:mt($,F.x)},stretch:[T.x,F.x],target:null,cells:D})}if(!((T.open||F.open)&&(T.open||!T.inside)&&(F.open||!F.inside)||Y&&(T.cornered||F.cornered)))continue;let ut=null;for(const X of ge){if(X.sequence===T.sequence&&X.x>=T.x&&X.x<=F.x||Y&&(!X.inside||!(S(T,X)||S(F,X))))continue;const zt=X.sequence===T.sequence?[T,F,X]:[X],Bt=X.sequence===T.sequence?[T,F,X]:Q,se=N(T,-1,Bt),Qe=N(F,1,Bt),Ae=N(T,1,Bt),Me=N(F,-1,Bt),xe=N(X,-1,zt),yn=N(X,1,zt),An=_t(X,zt),nc=An===null?0:L(...An),Mn=se!==null&&Qe!==null&&T.inside&&F.inside?[[se,Qe]]:[],sc=Mn.reduce((xn,[Kt,Ye])=>xn+P(Kt,Ye),0);for(const xn of[1,-1]){const Kt=[...Mn];if(xn===1?(xe!==null&&Ae!==null&&Kt.push([xe,Ae]),Me!==null&&yn!==null&&Kt.push([Me,yn])):(xe!==null&&Me!==null&&Kt.push([xe,Me]),Ae!==null&&yn!==null&&Kt.push([Ae,yn])),Kt.length===Mn.length)continue;let Ye=sc-Ft-nc;for(const[oc,rc]of Kt.slice(Mn.length))Ye+=P(oc,rc);(ut===null||Ye>ut.gain)&&(ut={gain:Ye,z:X,strand:xn,made:Kt,taken:An===null?ft:[...ft,An]})}}if(ut!==null){const X=r[ut.z.sequence],zt=mt($,T.x),Bt=mt($,F.x),se=mt(X,ut.z.x);ct({kind:"move",gain:ut.gain,points:[T,F,ut.z],made:ut.made,taken:ut.taken,step:{op:"move",sequence:$.name,from:zt,to:Bt,into:X.name,at:ut.z.sequence===T.sequence&&ut.z.x>F.x?se-(Bt-zt):se,strand:ut.strand},stretch:[T.x,F.x],target:ut.z.x,cells:D})}}}const U=new Map,q=[],tt=new Set,nt=(M,$)=>`${M.sequence}:${M.x}:${$}`;if(!lt){const M=[],$=new Map;for(const F of I){const D=F[0],Y=F[F.length-1];if(!(D===void 0||Y===void 0))for(const[Q,it]of[[D,1],[Y,-1]]){const ot=N(Q,it,[]);if(ot===null)continue;const ft=new Set;for(let Vt=0;Vt<s.reach;Vt++){const ut=ot.cell+ot.dir*Vt;if(ut<ot.lo||ut>=ot.hi)break;const X=s.coarseCell(ut);X>=0&&ft.add(X)}const Ft=q.length;U.set(nt(Q,it),Ft),q.push(Q.sequence),M.push([...ft]);for(const Vt of ft){const ut=$.get(Vt);ut===void 0?$.set(Vt,[Ft]):ut.push(Ft)}}}const O=q.length,_=2*s.trans,T=[...$.keys()];for(let F=0;F<O;F++)for(const D of M[F])for(const Y of T)if(s.coarseValue(D,Y)>_)for(const Q of $.get(Y)??[])q[Q]!==q[F]&&tt.add(F*O+Q)}const K=(M,$,O,_)=>{if(S(M,O))return!0;const T=U.get(nt(M,$.dir)),F=U.get(nt(O,_.dir));return T!==void 0&&F!==void 0&&tt.has(T*q.length+F)},bt=[];if(lt)for(let M=0;M<r.length;M++)for(let $=M+1;$<r.length;$++)bt.push([M,$]);else{const M=new Set,$=(_,T)=>{if(_===T||_<0||T<0)return;const F=Math.min(_,T),D=Math.max(_,T),Y=F*r.length+D;M.has(Y)||(M.add(Y),bt.push([F,D]))},O=q.length;for(const _ of tt)$(q[Math.floor(_/O)],q[_%O]);for(const[_,T]of x){const F=Number(_.slice(0,_.indexOf(":")));for(const D of T)$(F,Number(D.slice(0,D.indexOf(":"))))}}const wt=[];for(const[M,$]of bt){const O=I[M],_=I[$],T=O[0],F=O[O.length-1],D=_[0],Y=_[_.length-1];if(T===void 0||F===void 0||D===void 0||Y===void 0)continue;const Q=r[M].name,it=r[$].name,ot=[{e:N(F,-1,[]),f:N(D,1,[]),pa:F,pb:D,step:{op:"join",a:Q,aEnd:"end",b:it,bEnd:"start",gap:_n}},{e:N(F,-1,[]),f:N(Y,-1,[]),pa:F,pb:Y,step:{op:"join",a:Q,aEnd:"end",b:it,bEnd:"end",gap:_n}},{e:N(T,1,[]),f:N(D,1,[]),pa:T,pb:D,step:{op:"join",a:Q,aEnd:"start",b:it,bEnd:"start",gap:_n}},{e:N(T,1,[]),f:N(Y,-1,[]),pa:T,pb:Y,step:{op:"join",a:it,aEnd:"end",b:Q,bEnd:"start",gap:_n}}];for(const ft of ot){if(ft.e===null||ft.f===null||!lt&&!K(ft.pa,ft.e,ft.pb,ft.f))continue;const Ft=W(ft.e,ft.f),Vt=Ft.ideal>0?Math.min(Wf,Ft.score/Ft.ideal):0;wt.push({...ft,e:ft.e,f:ft.f,a:M,b:$,meeting:Ft,gain:Vt})}}const yt=new Map,Yt=(M,$)=>`${M.sequence}:${M.x}:${$.dir}`,we=M=>Math.max(0,M.score)/s.meetUnit,qe=new Set(wt.filter(M=>!G([[M.e,M.f]])&&!pt(M.e,M.a,M.f,M.b,M.meeting.gap)));for(const M of wt)if(qe.has(M))for(const $ of[Yt(M.pa,M.e),Yt(M.pb,M.f)]){const O=yt.get($)??[];O.push(we(M.meeting)),yt.set($,O)}for(const M of yt.values())M.sort(($,O)=>O-$);const pe=(M,$)=>{const O=yt.get(M)??[];return O[0]===$?O[1]??0:O[0]??0},be=.01;for(const M of wt){const $=we(M.meeting),O=Math.max(pe(Yt(M.pa,M.e),$),pe(Yt(M.pb,M.f),$)),_=Math.max(-2,Math.min(2,Math.log2(Math.max($,be)/Math.max(O,be)))),T=M.meeting.gap>s.window?M.meeting.gap*t.binsize:0,F=T>0&&M.step.op==="join"?{...M.step,gap:T}:M.step;ct({kind:"join",gain:M.gain,points:[M.pa,M.pb],made:[[M.e,M.f]],taken:[],step:F,stretch:null,target:null,cells:Number.POSITIVE_INFINITY,exclusivity:_,dicentric:pt(M.e,M.a,M.f,M.b,M.meeting.gap),gapCells:M.meeting.gap})}const We=e.weights!==void 0&&e.weights.length===no.length?e.weights:no,ye=Qt.map(M=>{const $=[Math.log2(1+Math.min(Math.max(0,M.gain),M.contacts/Tr)),Number.isFinite(M.cells)?Math.min(0,Math.log10(M.cells/4)):0,M.seen-1,-Math.max(0,M.excess-Fr)*(M.kind==="join"?1-Math.max(0,Math.min(1,M.exclusivity??0)):1),M.exclusivity??0,M.dicentric===!0?-1:0,M.buried===!0?-1:0,M.atGap===!0?1:0,Math.min(0,Math.log2(Math.max(.001,M.contacts)/Tr))];return{trade:M,features:$,confidence:Yf($,We)}});ye.sort((M,$)=>$.confidence-M.confidence||$.trade.gain-M.trade.gain);const je=[],Tt=M=>je.some($=>$.sequence===M.sequence&&Math.abs($.x-M.x)<=w),Nt=[];for(const{trade:M,features:$,confidence:O}of ye)M.points.some(Tt)||(je.push(...M.points),Nt.push(Kf(M,$,O,t,o,(_,T)=>M.kind==="join"?{score:W(_,T).score/s.meetUnit*o,seen:0,reached:0,contacts:0,expected:0}:R(_,T,"local"))));return{list:Nt,along:a.score,breakpoints:c,unit:o}}function Pr(e){return e.dir<0?{x:e.cell+1,side:-1}:{x:e.cell,side:1}}function Kf(e,t,n,s,o,r){const i=e.made.map(([d,m])=>{const g=Pr(d),w=Pr(m),p=r(d,m).score/o;return g.x<=w.x?{row:g.x,col:w.x,rowSide:g.side,colSide:w.side,score:p}:{row:w.x,col:g.x,rowSide:w.side,colSide:g.side,score:p}}),c=(e.kind==="move"?e.points.slice(0,2):e.points).filter(d=>d.inside&&e.kind!=="join").map(d=>d.x),l=[...e.points.map(d=>d.x)],u=[Math.min(...l),Math.max(...l)],h=e.made.flat().map(d=>{const m=s.cellMap[d.cell]??-1,w=(s.partAt(d.cell)?.piece?.strand??1)*d.dir;return`${m}${w<0?"<":">"}`}).concat(e.points.filter(d=>d.inside&&e.made.length===0).map(d=>{const m=s.cellMap[d.x-1]??-1,g=s.cellMap[d.x]??-1;return`${m}|${g}`})).sort().join(","),f=["map"];return t[2]<-.25&&f.push("sparse"),t[3]<0&&f.push("brighter than an adjacency"),e.kind==="join"&&(e.gapCells??0)>0&&f.push(`a gap of about ${Xf((e.gapCells??0)*s.binsize)}`),t[4]<-.5&&f.push("an end with a better offer"),e.dicentric===!0&&f.push("two centromeres"),e.buried===!0&&f.push("a telomere"),e.atGap===!0&&f.push("at a gap of N"),t[8]<-.5&&f.push("few contacts"),{key:`${e.kind}:${h}`,kind:e.kind,step:e.step,words:Ff(e.step),gain:e.gain,confidence:n,features:t,breaks:c,corners:i,extent:u,stretch:e.stretch,target:e.target,evidence:f}}function Xf(e){return e>=1e6?`${(e/1e6).toPrecision(2)} Mb`:e>=1e3?`${Math.round(e/1e3)} kb`:`${Math.round(e)} bp`}function Zf(e,t,n){if(n<=t.from)return 0;if(n>=t.to)return t.length;const s=e.place(n);return s===null||s.sequence!==t.name?0:Math.max(0,Math.min(t.length,Math.round(s.bp)))}function bn(e,t,n,s,o){const r=[];if(e.length===0)return r;let i=0;for(let a=1;a<=e.length;a++)if(a===e.length||e[a]!==e[i]){const c=e[i];r.push({label:t(c),start:i,end:a,...n===void 0?{}:{unitStart:n(c)},...s===void 0?{}:{unitLength:s(c)},...o===void 0?{}:{unitBin:o(c)}}),i=a}return r}function Lr(e,t){const n=e.coords.contigsOfBins(t[0],t[1]);return bn(n,s=>e.chromnames[s]??String(s),s=>e.coords.contigStartBin(s),s=>e.coords.contigLengths[s],s=>e.coords.contigStartBin(s))}function Dr(e,t){const n=e.coords.contigsOfBins(t[0],t[1]),s=new Int32Array(n.length);for(let o=0;o<n.length;o++)s[o]=e.contigGenomeIds[n[o]];return bn(s,o=>e.genomeNames[o]??String(o),o=>e.genomeExtent(o)[0])}function dn(e,t){const n=new Int32Array(t.length);for(let s=0;s<t.length;s++)n[s]=e.contigGenomeIds[t[s]];return bn(n,s=>e.genomeNames[s]??String(s))}function Jf(e,t){return e==="genome"&&t!==void 0&&t.length>1}function Ur(e,t,n){const s=n==="contig"?e.chromnames:e.genomeNames,o=new Array(t.length);for(let r=0;r<t.length;r++)o[r]={label:s[t[r]]??String(t[r]),start:r,end:r+1};return o}function td(e,t){return{rows:Ur(e,t.rowIds,t.level),cols:Ur(e,t.colIds,t.level)}}const Gr=new WeakMap;function Ca(e){let t=Gr.get(e);return t===void 0&&(t={},Gr.set(e,t)),t}function ed(e){const t=Ca(e);return t.contig??=e.coords.contigsOfBins(0,e.nBins),t.contig}function nd(e){const t=Ca(e);if(t.genome===void 0){const n=e.coords.contigsOfBins(0,e.nBins),s=e.contigGenomeIds;for(let o=0;o<n.length;o++)n[o]=s[n[o]];t.genome=n}return t.genome}const so=qt,sd=8,od=12*so*so;function rd(e){const t=Math.max(0,e-od),n=Math.floor(Math.sqrt(t/sd));return Math.max(256,Math.min(so,n))}function id(e,t,n){const s=new Int32Array(e);if(e<=t){for(let c=0;c<e;c++)s[c]=c;return{slotOf:s,slots:e,pooled:!1}}const o=n===void 0?null:ad(e,n);if(o===null||o.length>t){for(let c=0;c<e;c++)s[c]=Math.floor(c*t/e);return{slotOf:s,slots:t,pooled:!0}}const r=cd(o,t);let i=0,a=0;for(let c=0;c<o.length;c++){const l=o[c],u=r[c];for(let h=0;h<l;h++,i++)s[i]=a+Math.min(u-1,Math.floor(h*u/l));a+=u}return{slotOf:s,slots:a,pooled:!0}}function ad(e,t){const n=[];let s=0;for(let o=1;o<=e;o++)o<e&&t(o)===t(s)||(n.push(o-s),s=o);return n}function cd(e,t){const n=e.length,s=new Int32Array(n);if(n===0)return s;const o=e.reduce((c,l)=>c+l,0),r=t-n,i=[];let a=0;for(let c=0;c<n;c++){const l=o===0?0:e[c]*r/o,u=Math.floor(l);s[c]=1+u,a+=u,i.push({index:c,fraction:l-u})}i.sort((c,l)=>l.fraction-c.fraction||c.index-l.index);for(let c=0;a<r;c++,a++)s[i[c%n].index]+=1;return s}class ld{n;values;constructor(t){this.n=t,this.values=new Float64Array(t*(t+1)/2)}add(t,n,s){const o=t<n?t:n,r=t<n?n:t;this.values[o*this.n-o*(o-1)/2+(r-o)]+=s}get(t,n){const s=t<n?t:n,o=t<n?n:t;return this.values[s*this.n-s*(s-1)/2+(o-s)]}toSquare(){const{n:t,values:n}=this,s=new Float32Array(t*t);let o=0;for(let r=0;r<t;r++)for(let i=r;i<t;i++,o++){const a=n[o];s[r*t+i]=a,s[i*t+r]=a}return s}}function $a(e,t){const n=t[1]-t[0];if(!(n>0))return[];const s=Math.min(n,Math.max(0,Math.round(e[1])-Math.round(e[0])));if(s<=0)return[];const o=Math.round(e[0]),r=Math.floor((o-t[0])/n);let i=o-r*n,a=r*n,c=0,l=s;const u=[];for(;l>0;){const h=Math.min(l,t[1]-i);u.push({from:i,to:i+h,at:c,shift:a}),c+=h,l-=h,i=t[0],a+=n}return u}function Hr(e,t){const n=$a(e,t);return n.length>1||n.length===1&&n[0].shift!==0}function ud(e){const t=e.map(a=>a[0]?.nrows??0),n=(e[0]??[]).map(a=>a.ncols),s=t.reduce((a,c)=>a+c,0),o=n.reduce((a,c)=>a+c,0),r=new Float32Array(s*o);let i=0;for(let a=0;a<e.length;a++){let c=0;for(let l=0;l<e[a].length;l++){const u=e[a][l];for(let h=0;h<u.nrows;h++)r.set(u.values.subarray(h*u.ncols,h*u.ncols+u.ncols),(i+h)*o+c);c+=n[l]}i+=t[a]}return{nrows:s,ncols:o,values:r}}function hd(e){const t=Math.max(1,e.binsPerCell),n=[];let s=0;for(let o=0;o<e.starts.length;o++){const r=Math.round((e.starts[o]-e.contigStart)/t);n.push(e.blockStart+s-r),s+=e.cells[o]??0}return n}async function fd(e,t,n,s,o,r){const i=e.coords.contigOfBin(o[0]),[a,c]=e.coords.contigBinExtent(i);if(a!==o[0]||c!==o[1])throw new C("unsupported","A circular window must be a whole sequence: it is the sequence that joins its own ends.",{wrap:o,contig:e.chromnames[i]});const l={binsPerCell:Math.max(1,Math.trunc(t.binsPerCell??1)),contigsPerCell:Math.max(1,Math.trunc(t.contigsPerCell??1))},u=l.binsPerCell>1||l.contigsPerCell>1?l:r.planFor(o,n[1]-n[0],s[1]-s[0])??{binsPerCell:1,contigsPerCell:1};if(u.contigsPerCell>1)throw new C("unsupported","A circular sequence cannot be read at whole-sequence resolution: there is only one of it.",{wrap:o});const h=Math.max(1,u.binsPerCell),f=qr(r,n,o,u),d=qr(r,s,o,u);if(f.length===0||d.length===0)throw new C("unsupported","A circular window with nothing in it cannot be read.",{rows:n,cols:s,wrap:o});const m=async(S,v)=>{const I={rows:S.read,cols:v.read,...t.balance===!0?{balance:!0}:{},...t.value===void 0?{}:{value:t.value},...t.budgetBytes===void 0?{}:{budgetBytes:t.budgetBytes}};if(h<=1){const z=await e.matrix(I,r.hint(S.read,v.read));return{nrows:z.nrows,ncols:z.ncols,values:z.values}}const N=await e.pooledMatrix(I,u,r.hooks??{});r.throwIfCancelled();const B=N.values instanceof Float32Array?N.values:Float32Array.from(N.values);return{nrows:N.nrows,ncols:N.ncols,values:B}},g=[];for(const S of f){const v=[];for(const I of d)v.push(await m(S,I));g.push(v)}const w=g.map(S=>S[0].nrows),p=g[0].map(S=>S.ncols),{nrows:b,ncols:y,values:A}=ud(g),x=Wr(f),E=Wr(d);return{nrows:b,ncols:y,values:A,rowExtent:x,colExtent:E,rowGroups:jr(e,i,f,w,x[0],h),colGroups:jr(e,i,d,p,E[0],h),...t.genomes===!0&&e.hasGenomes?{rowGenomes:Qr(e,i,f,w),colGenomes:Qr(e,i,d,p)}:{},level:"bin",wrapped:o,...h>1?{binsPerCell:h}:{}}}function qr(e,t,n,s){const o=[];for(const r of $a(t,n)){const i=s.binsPerCell>1?e.snap([r.from,r.to],s):[r.from,r.to];i[1]>i[0]&&o.push({read:i,unwrapped:i[0]+r.shift})}return o}function Wr(e){const t=e.reduce((n,s)=>n+(s.read[1]-s.read[0]),0);return[e[0].unwrapped,e[0].unwrapped+t]}function jr(e,t,n,s,o,r){const[i]=e.coords.contigBinExtent(t),a=e.chromnames[t]??String(t),c=e.coords.contigLengths[t],l=hd({starts:n.map(f=>f.read[0]),cells:s,blockStart:o,contigStart:i,binsPerCell:r}),u=[];let h=0;for(let f=0;f<n.length;f++)u.push({label:a,start:h,end:h+s[f],unitStart:l[f],...c===void 0?{}:{unitLength:c}}),h+=s[f];return u}function Qr(e,t,n,s){const o=e.contigGenomeIds[t],r=e.genomeNames[o]??String(o),i=s.reduce((a,c)=>a+c,0);return i>0?[{label:r,start:0,end:i}]:[]}function dd(e){return Array.isArray(e)&&(e.length===0||typeof e[0]=="string")}function ko(e){const t={};for(const n of e.columns){const s=e.data[n];s!==void 0&&(dd(s)?t[n]=s:s instanceof BigInt64Array?t[n]=Float64Array.from(s,Number):t[n]=Float64Array.from(s))}return{length:e.length,columns:[...e.columns],data:t}}function Qn(e){if(e==null)return null;switch(typeof e){case"string":case"number":case"boolean":return e;case"bigint":return Number(e);case"object":{if(Array.isArray(e))return e.map(Qn);if(ArrayBuffer.isView(e))return Array.from(e);if(e instanceof Map){const n={};for(const[s,o]of e)n[String(s)]=Qn(o);return n}const t={};for(const[n,s]of Object.entries(e))t[n]=Qn(s);return t}default:return String(e)}}function md(e){return e instanceof C?{name:e.name,code:e.code,message:e.message,detail:Qn(e.detail),stack:e.stack}:e instanceof Error?{name:e.name,code:null,message:e.message,detail:{},stack:e.stack}:{name:"Error",code:null,message:String(e),detail:{}}}function gd(e){const t=[],n=new Set,s=o=>{if(!(o===null||typeof o!="object")){if(ArrayBuffer.isView(o)){const r=o.buffer;r instanceof ArrayBuffer&&!n.has(r)&&(n.add(r),t.push(r));return}if(Array.isArray(o)){if(o.length===0||typeof o[0]!="object")return;for(const r of o)s(r);return}for(const r of Object.values(o))s(r)}};return s(e),t}const Ee=1<<20,wd=64<<20;let Yr=0;class te{id;size;isRemote=!1;bytes;blob;existingPath;tempDir;mountPath=null;ownsMount=!1;requests=0;bytesRead=0;cache=new Map;cachedBytes=0;syncReader=null;module=null;readExact;constructor(t,n={}){if(this.tempDir=n.tempDir,this.bytes=null,this.blob=null,this.existingPath=null,pd(t)){const o=typeof File<"u"&&t instanceof File?t.name:null;this.blob=t,this.size=t.size,this.id=n.name??o??`blob-${Bs()}`,this.readExact=(r,i)=>this.readBlobExact(t,r,i);return}if(bd(t)){this.existingPath=t.path,this.size=t.size,this.id=n.name??t.path;return}const s=yd(t);this.bytes=s,this.size=s.byteLength,this.id=n.name??`bytes-${Bs()}`}static async fromPath(t,n={}){if(!Re())throw new C("bad-uri",`cannot open the filesystem path ${t} in a browser; pass the File object instead`,{path:t});const s=await ae();let o;try{o=s.FS.stat(t).size}catch(r){throw new C("not-hdf5",`cannot stat ${t}: ${r instanceof Error?r.message:String(r)}`,{path:t})}return new te({path:t,size:o},{name:n.name??t,...n})}static async open(t,n={}){return typeof t=="string"?te.fromPath(t,n):new te(t,n)}async mount(){if(this.mountPath!==null)return this.mountPath;const t=await ae();if(this.module=t,this.existingPath!==null)return this.mountPath=this.existingPath,this.ownsMount=!1,this.mountPath;if(this.blob!==null&&typeof FileReaderSync<"u")return this.mountPath=this.mountLazy(t,this.blob),this.ownsMount=!0,this.mountPath;const n=this.bytes??new Uint8Array(await this.blob.arrayBuffer()),s=this.mountTarget();return t.FS.writeFile(s,n),this.mountPath=s,this.ownsMount=!0,this.requests+=1,this.bytesRead+=n.byteLength,s}mountLazy(t,n){const s=this.mountTarget().replace(/^\//,""),o=t.FS.createFile("/",s,{},!0,!1),r={length:this.size};return o.contents=r,Object.defineProperty(o,"usedBytes",{get:()=>r.length}),o.stream_ops={...o.stream_ops,read:(i,a,c,l,u)=>{if(u>=this.size)return 0;const h=Math.min(this.size-u,l);return this.copyInto(n,a,c,u,h),h},mmap:(i,a,c)=>{const l=t.Module._malloc(a);if(l===0)throw new Error("mmap allocation failed");const u=Math.max(0,Math.min(this.size-c,a));return u>0&&this.copyInto(n,t.Module.HEAPU8,l,c,u),{ptr:l,allocated:!0}}},`/${s}`}readBytes(t,n){const s=Math.max(0,Math.min(this.size-t,n));if(s<=0)return new Uint8Array(0);if(this.bytes!==null)return this.bytes.subarray(t,t+s).slice();if(this.blob!==null){const a=new Uint8Array(s);return this.copyInto(this.blob,a,0,t,s),a}const o=this.module;if(this.existingPath===null||o===null)throw new C("unsupported",`${this.id} cannot be read directly before it has been mounted.`,{id:this.id});const r=new Uint8Array(s),i=o.FS.open(this.existingPath,"r");try{let a=0;for(;a<s;){const c=o.FS.read(i,r,a,s-a,t+a);if(c<=0)break;a+=c}return this.requests+=1,this.bytesRead+=a,a===s?r:r.subarray(0,a)}finally{o.FS.close(i)}}async readBlobExact(t,n,s){const o=Math.max(0,Math.min(this.size-n,s));if(o===0)return new Uint8Array(0);const r=Math.floor(n/Ee),i=Math.floor((n+o-1)/Ee);let a=!0;for(let l=r;l<=i&&a;l++)a=this.cache.has(l);if(a)return this.readBytes(n,o);const c=new Uint8Array(await t.slice(n,n+o).arrayBuffer());return this.requests+=1,this.bytesRead+=c.byteLength,c}copyInto(t,n,s,o,r){let i=0;for(;i<r;){const a=o+i,c=Math.floor(a/Ee);let l=this.cache.get(c);if(l===void 0){const f=c*Ee,d=Math.min(f+Ee,this.size);l=new Uint8Array(this.reader().readAsArrayBuffer(t.slice(f,d))),this.store(c,l),this.requests+=1,this.bytesRead+=l.byteLength}else this.cache.delete(c),this.cache.set(c,l);const u=a-c*Ee,h=Math.min(l.length-u,r-i);if(h<=0)throw new Error(`short read of ${this.id} at ${a}`);n.set(l.subarray(u,u+h),s+i),i+=h}}store(t,n){this.cache.set(t,n),this.cachedBytes+=n.byteLength;for(const s of this.cache.keys()){if(this.cachedBytes<=wd)break;if(s===t)continue;const o=this.cache.get(s);o&&(this.cachedBytes-=o.byteLength),this.cache.delete(s)}}reader(){return this.syncReader??=new FileReaderSync,this.syncReader}close(){if(this.cache.clear(),this.cachedBytes=0,this.mountPath===null)return;const t=this.mountPath;this.mountPath=null,this.ownsMount&&(this.ownsMount=!1,ae().then(n=>{try{n.FS.unlink(t)}catch{}},()=>{}))}stats(){return{requests:this.requests,bytes:this.bytesRead}}cachedChunkCount(){return this.cache.size}resetStats(){this.requests=0,this.bytesRead=0}mountTarget(){const t=this.id.replace(/[^A-Za-z0-9._-]+/g,"_").slice(-100),n=`chromosomix-${Bs()}-${t}`;if(!Re())return`/${n}`;const s=globalThis.process?.env;return`${(this.tempDir??s?.TMPDIR??s?.TMP??s?.TEMP??"/tmp").replace(/\/+$/,"")}/${n}`}}function Bs(){return Yr+=1,`${Date.now().toString(36)}${Yr.toString(36)}`}function pd(e){return typeof Blob<"u"&&e instanceof Blob}function bd(e){return typeof e=="object"&&e!==null&&typeof e.path=="string"&&typeof e.size=="number"}function yd(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const Ad="/chromosomix-lazy",hn=new Map,Vr=new WeakSet;let Os=0;function Md(e,t,n){return{read:(s,o,r,i,a)=>{if(a>=t)return 0;const c=Math.min(t-a,i);return n(o,r,a,c),c},llseek:(s,o,r)=>{const i=r===1?s.position+o:r===2?t+o:o;if(i<0)throw new Error("a lazy file cannot be sought before its start");return i},mmap:(s,o,r)=>{const i=e.Module._malloc(o);if(i===0)throw new Error("mmap allocation failed");const a=Math.max(0,Math.min(t-r,o));return a>0&&n(e.Module.HEAPU8,i,r,a),{ptr:i,allocated:!0}}}}function xd(e,t,n,s){const o=Md(e,n,s);if(Re()){Id(e),Os+=1;const a=`${Ad}/${t}-${Os}`;return hn.set(a,{size:n,ino:79691776+Os,ops:o}),a}const r=e.FS.createFile("/",t,{},!0,!1),i={length:n};return r.contents=i,Object.defineProperty(r,"usedBytes",{get:()=>i.length}),r.stream_ops={...r.stream_ops,read:o.read,mmap:o.mmap},`/${t}`}function Sd(e,t){if(!hn.delete(t))try{e.FS.unlink(t)}catch{}}function Kr(e){const t=new Date(0);return{dev:76,ino:e.ino,mode:33060,nlink:1,uid:0,gid:0,rdev:0,size:e.size,blksize:4096,blocks:Math.ceil(e.size/512),atime:t,mtime:t,ctime:t}}function Id(e){const t=e.FS;if(Vr.has(t))return;Vr.add(t);const n=t.open.bind(t),s=t.fstat.bind(t),o=t.stat.bind(t);t.open=(r,i,a)=>{const c=typeof r=="string"?hn.get(r):void 0;if(c===void 0)return n(r,i,a);const l={id:c.ino,mode:33060,node_ops:{},path:r,usedBytes:c.size};return t.createStream({path:r,flags:0,node:l,stream_ops:c.ops,seekable:!0,position:0})},t.fstat=r=>{const i=t.getStream(r),a=i?.path===void 0?void 0:hn.get(i.path);return a!==void 0&&i?.stream_ops===a.ops?Kr(a):s(r)},t.stat=(r,i)=>{const a=typeof r=="string"?hn.get(r):void 0;return a===void 0?o(r,i):Kr(a)}}const Ed=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),vd=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ht=64,Na=32;function Gt(e,t){return e>>>t|e<<32-t}function Yn(e){const t=new Uint32Array(vd),n=new Uint32Array(64),s=e.length*8,o=new Uint8Array((Math.floor((e.length+8)/Ht)+1)*Ht);o.set(e),o[e.length]=128;const r=new DataView(o.buffer);r.setUint32(o.length-8,Math.floor(s/4294967296),!1),r.setUint32(o.length-4,s>>>0,!1);for(let c=0;c<o.length;c+=Ht){for(let p=0;p<16;p++)n[p]=r.getUint32(c+p*4,!1);for(let p=16;p<64;p++){const b=n[p-15],y=n[p-2],A=Gt(b,7)^Gt(b,18)^b>>>3,x=Gt(y,17)^Gt(y,19)^y>>>10;n[p]=n[p-16]+A+n[p-7]+x>>>0}let[l,u,h,f,d,m,g,w]=t;for(let p=0;p<64;p++){const b=Gt(d,6)^Gt(d,11)^Gt(d,25),y=d&m^~d&g,A=w+b+y+Ed[p]+n[p]>>>0,x=Gt(l,2)^Gt(l,13)^Gt(l,22),E=l&u^l&h^u&h,S=x+E>>>0;w=g,g=m,m=d,d=f+A>>>0,f=h,h=u,u=l,l=A+S>>>0}t[0]=t[0]+l>>>0,t[1]=t[1]+u>>>0,t[2]=t[2]+h>>>0,t[3]=t[3]+f>>>0,t[4]=t[4]+d>>>0,t[5]=t[5]+m>>>0,t[6]=t[6]+g>>>0,t[7]=t[7]+w>>>0}const i=new Uint8Array(Na),a=new DataView(i.buffer);for(let c=0;c<8;c++)a.setUint32(c*4,t[c],!1);return i}function an(e,t){const n=new Uint8Array(Ht);n.set(e.length>Ht?Yn(e):e);const s=new Uint8Array(Ht+t.length),o=new Uint8Array(Ht+Na);for(let r=0;r<Ht;r++)s[r]=n[r]^54,o[r]=n[r]^92;return s.set(t,Ht),o.set(Yn(s),Ht),Yn(o)}function Xr(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function he(e){return new TextEncoder().encode(e)}const Cd="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",Zr="AWS4-HMAC-SHA256",Ba="s3",Oa="aws4_request";function $d(e){const t=(n,s=2)=>String(n).padStart(s,"0");return`${t(e.getUTCFullYear(),4)}${t(e.getUTCMonth()+1)}${t(e.getUTCDate())}T${t(e.getUTCHours())}${t(e.getUTCMinutes())}${t(e.getUTCSeconds())}Z`}function oo(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function Nd(e){return e===""?"/":e.split("/").map(t=>oo(decodeURIComponent(t))).join("/")}function Bd(e){const t=[];return e.forEach((n,s)=>t.push([oo(s),oo(n)])),t.sort((n,s)=>n[0]===s[0]?n[1]<s[1]?-1:1:n[0]<s[0]?-1:1),t.map(([n,s])=>`${n}=${s}`).join("&")}let Tn=null;function Od(e,t,n){const s=`${e}|${t}|${n}`;if(Tn!==null&&Tn.id===s)return Tn.key;const o=an(he(`AWS4${e}`),he(t)),r=an(o,he(n)),i=an(r,he(Ba)),a=an(i,he(Oa));return Tn={id:s,key:a},a}function kd(e){const t=new URL(e.url),n=e.now??new Date,s=$d(n),o=s.slice(0,8),r=e.payloadHash??Cd,{credential:i}=e,a=[["host",t.host],["x-amz-content-sha256",r],["x-amz-date",s]];i.sessionToken!==void 0&&i.sessionToken!==""&&a.push(["x-amz-security-token",i.sessionToken]);const c=a.map(([g,w])=>`${g}:${w.trim()}
6
+ `).join(""),l=a.map(([g])=>g).join(";"),u=[e.method.toUpperCase(),Nd(t.pathname),Bd(t.searchParams),c,l,r].join(`
7
+ `),h=`${o}/${i.region}/${Ba}/${Oa}`,f=[Zr,s,h,Xr(Yn(he(u)))].join(`
8
+ `),d=Xr(an(Od(i.secretAccessKey,o,i.region),he(f))),m={Authorization:`${Zr} Credential=${i.accessKeyId}/${h}, SignedHeaders=${l}, Signature=${d}`,"x-amz-content-sha256":r,"x-amz-date":s};return i.sessionToken!==void 0&&i.sessionToken!==""&&(m["x-amz-security-token"]=i.sessionToken),m}function me(e){const t={...e.headers};return e.credential===void 0?t:{...t,...kd({method:(e.method??"GET").toUpperCase(),url:e.url,credential:e.credential})}}function _o(e){const t=_d(e);return t.has("x-amz-signature")||t.has("x-goog-signature")?!0:t.has("sig")&&t.has("sv")}function _d(e){const t=new Set;if(typeof e!="string")return t;const n=e.indexOf("#"),s=n<0?e:e.slice(0,n),o=s.indexOf("?");if(o<0)return t;const r=s.slice(o+1);for(const i of r.split("&")){const a=i.indexOf("=");a<=0||t.add(i.slice(0,a).toLowerCase())}return t}const Td=1<<20,Fd=64<<20,zd=4<<20,Rd=16<<20,Pd=8;function Ld(e,t){const n=new XMLHttpRequest;n.open("GET",e,!1);for(const[s,o]of Object.entries(t))n.setRequestHeader(s,o);return n.responseType="arraybuffer",n.send(null),{status:n.status,body:new Uint8Array(n.response??new ArrayBuffer(0)),contentRange:n.getResponseHeader("content-range")}}class de{id;size;isRemote=!0;url;chunkSize;onRead;maxCacheBytes;cache=new Map;cachedBytes=0;readAhead;recent=[];requests;bytesRead;mountPath=null;credential;headers;fetchImpl;syncFetch;constructor(t,n,s,o){this.url=t,this.id=t,this.size=n,this.credential=s.credential,this.headers=s.headers,this.fetchImpl=s.fetchImpl??((i,a)=>globalThis.fetch(i,a)),this.syncFetch=s.syncFetch??null,this.chunkSize=Math.max(1,Math.trunc(s.chunkSize??Td)),this.readAhead=s.readAhead??!0,this.onRead=s.onRead;const r=Math.trunc(s.maxCacheBytes??Fd);this.maxCacheBytes=Math.max(this.chunkSize,r),this.requests=o.requests,this.bytesRead=o.bytes}static async open(t,n={}){const s=n.fetchImpl??globalThis.fetch,o=m=>me({url:t,method:m,...n.headers===void 0?{}:{headers:n.headers},...n.credential===void 0?{}:{credential:n.credential}});if(typeof s!="function")throw new C("remote-cors","this runtime has no fetch(); remote files need one",{url:t});const r=sn(t),i={requests:0,bytes:0};let a=null;if(!_o(t))try{i.requests+=1,a=await s(t,{method:"HEAD",headers:o("HEAD")})}catch(m){await ti(t,r,m,s,i)}if(a&&!a.ok)throw new C("bad-uri",n.credential===void 0?`${r} answered ${a.status} ${a.statusText} to a HEAD of ${t}; the viewer needs a publicly readable object, or a bucket entry holding a key for it (Open a file → Private buckets). A presigned link is read without this probe and does not reach here, so a URL carrying a signature in its query that fails has expired rather than been rejected for its method.`:`${r} answered ${a.status} ${a.statusText} to a signed HEAD of ${t}. The key reached the bucket and was rejected: check that the region on the bucket entry matches the bucket, that the key is allowed \`s3:GetObject\` on this prefix, and — for a temporary credential — that the session token has not expired.`,{url:t,host:r,status:a.status,signed:n.credential!==void 0});const c=ei(a);if(c!==null){const m=await Dd(t,s,o,i),g=ni(m?.headers.get("content-range")??null)??Fn(m,"content-length");if(m!==null&&m.status===206&&ei(m)===null&&g!==null)return new de(t,g,n,i);throw new C("remote-compressed",`${r} is serving ${t} with “Content-Encoding: ${c}”, so byte ranges address the compressed stream rather than the file.`,{url:t,host:r,encoding:c,encodedLength:Fn(a,"content-length")})}const l=Fn(a,"content-length"),u=l===0?null:l;if((a?.headers.get("accept-ranges")??"").toLowerCase().includes("bytes")&&u!==null)return new de(t,u,n,i);let f;try{i.requests+=1,f=await s(t,{method:"GET",headers:{...o("GET"),Range:"bytes=0-0"}})}catch(m){throw await ti(t,r,m,s,i),new Error("unreachable")}if(i.bytes+=Fn(f,"content-length")??1,f.status!==206)throw new C("remote-no-ranges",`${r} does not serve HTTP range requests: a “Range: bytes=0-0” request for ${t} returned ${f.status}, not 206 Partial Content.`,{url:t,host:r,status:f.status});const d=ni(f.headers.get("content-range"))??u;if(d===null)throw new C("remote-cors",`${r} serves ranges for ${t} but does not expose its size to this page: neither “Content-Length” nor “Content-Range” was readable. Add both to the bucket’s CORS “Access-Control-Expose-Headers”.`,{url:t,host:r});return new de(t,d,n,i)}async mount(){if(this.mountPath!==null)return this.mountPath;if(this.syncFetch===null&&typeof XMLHttpRequest>"u")throw new C("remote-cors","remote files are read with synchronous XMLHttpRequest, which exists only in a browser worker; this runtime has none.",{url:this.url});const t=await ae(),n=`remote-${Math.abs(Gd(this.url)).toString(36)}`;return this.mountPath=xd(t,n,this.size,(s,o,r,i)=>this.copyInto(s,o,r,i)),this.mountPath}close(){if(this.cache.clear(),this.cachedBytes=0,this.mountPath===null)return;const t=this.mountPath;this.mountPath=null,ae().then(n=>Sd(n,t),()=>{})}stats(){return{requests:this.requests,bytes:this.bytesRead}}resetStats(){this.requests=0,this.bytesRead=0}cachedChunkCount(){return this.cache.size}readBytes(t,n){const s=Math.max(0,Math.min(this.size-t,n)),o=new Uint8Array(s);return s>0&&this.copyInto(o,0,t,s),o}async readExact(t,n){const s=Math.max(0,Math.min(this.size-t,n));if(s===0)return new Uint8Array(0);const o=Math.floor(t/this.chunkSize),r=Math.floor((t+s-1)/this.chunkSize);let i=!0;for(let d=o;d<=r&&i;d++)i=this.cache.has(d);if(i)return this.readBytes(t,s);const a=t,c=t+s-1,l=this.fetchImpl,u=await l(this.url,{method:"GET",headers:{...this.authorisation(),Range:`bytes=${a}-${c}`}});this.requests+=1,this.refuseStatus(u.status,a,c);const h=new Uint8Array(await u.arrayBuffer());this.bytesRead+=h.byteLength,this.onRead?.(this.requests,this.bytesRead);const f=this.windowOf(h,a,c,u.headers.get("content-range"));if(f.byteLength<s)throw new C("remote-no-ranges","a range request returned a short response",{wanted:s,available:f.byteLength});return f.byteLength===s&&f.buffer.byteLength===s?f:f.slice(0,s)}copyInto(t,n,s,o){let r=0;for(;r<o;){const i=s+r,a=Math.floor(i/this.chunkSize),c=this.cache.get(a);if(c){this.touch(a),r+=Jr(t,n+r,c,i-a*this.chunkSize,o-r);continue}const l=Math.floor((s+o-1)/this.chunkSize);let u=a;for(;u+1<=l&&!this.cache.has(u+1);)u+=1;const{ahead:h,streak:f}=this.aheadFor(a,u),d=Math.min(u+h,Math.ceil(this.size/this.chunkSize)-1);for(;u<d&&!this.cache.has(u+1);)u+=1;this.recent.push({from:a,to:u,streak:f}),this.recent.length>Pd&&this.recent.shift();const m=a*this.chunkSize,g=Math.min((u+1)*this.chunkSize,this.size)-1,w=this.fetchRange(m,g);r+=Jr(t,n+r,w,i-m,o-r);for(let p=a;p<=u;p++){const b=p*this.chunkSize-m;if(b>=w.length)break;this.store(p,w.subarray(b,Math.min(b+this.chunkSize,w.length)))}}}aheadFor(t,n){if(!this.readAhead)return{ahead:0,streak:0};const s=Math.max(1,Math.floor(zd/this.chunkSize));let o=0;for(const i of this.recent)t>=i.from-s&&t<=i.to+s&&(o=Math.max(o,i.streak+1));if(o<2)return{ahead:0,streak:o};const r=Math.max(0,Math.floor(Rd/this.chunkSize)-(n-t+1));return{ahead:Math.min(r,2**(o-2)),streak:o}}fetchRange(t,n){const s={...this.authorisation(),Range:`bytes=${t}-${n}`},o=(this.syncFetch??Ld)(this.url,s);return this.requests+=1,this.refuseStatus(o.status,t,n),this.bytesRead+=o.body.byteLength,this.onRead?.(this.requests,this.bytesRead),this.windowOf(o.body,t,n,o.contentRange)}authorisation(){return this.credential===void 0&&this.headers===void 0?{}:me({url:this.url,method:"GET",...this.headers===void 0?{}:{headers:this.headers},...this.credential===void 0?{}:{credential:this.credential}})}refuseStatus(t,n,s){if(t===403&&this.credential!==void 0)throw new C("bad-uri",`${sn(this.url)} refused a signed request for bytes ${n}-${s} of ${this.url}. The key reached the bucket and was rejected: check the region on the bucket entry matches the bucket, that the key is allowed \`s3:GetObject\` on this prefix, and — for a temporary credential — that the session token has not expired.`,{url:this.url,status:403,from:n,to:s,signed:!0});if(t!==206&&t!==200)throw new C("remote-no-ranges",`${sn(this.url)} returned ${t} for bytes ${n}-${s} of ${this.url}`,{url:this.url,status:t,from:n,to:s})}windowOf(t,n,s,o){const r=s-n+1,i=ka(o);if(i!==null&&i.end-i.start+1!==t.byteLength)throw new C("remote-compressed",`${sn(this.url)} answered a request for bytes ${n}-${s} of ${this.url} with “Content-Range: ${o}” — ${i.end-i.start+1} octets — but the body is ${t.byteLength}. The response was re-encoded in transit (transfer compression), so ranges do not address the file. Serve it without “Content-Encoding”, or download it and drop it here.`,{url:this.url,from:n,to:s,claimed:i.end-i.start+1,received:t.byteLength});const a=i?.start??Ud(o),c=a===null?t.byteLength>r?n:0:n-a;if(c===0&&t.byteLength<=r)return t;if(c<0||c>=t.byteLength)throw new C("remote-no-ranges",`${sn(this.url)} answered a request for bytes ${n}-${s} of ${this.url} with ${t.byteLength} bytes starting at ${a??"an unstated offset"}, which does not contain what was asked for.`,{url:this.url,from:n,to:s,start:a,length:t.byteLength});return t.subarray(c,Math.min(c+r,t.byteLength))}store(t,n){const s=new Uint8Array(n);this.cache.set(t,s),this.cachedBytes+=s.byteLength;for(const o of this.cache.keys()){if(this.cachedBytes<=this.maxCacheBytes)break;if(o===t)continue;const r=this.cache.get(o);r&&(this.cachedBytes-=r.byteLength),this.cache.delete(o)}}touch(t){const n=this.cache.get(t);n&&(this.cache.delete(t),this.cache.set(t,n))}}function Jr(e,t,n,s,o){const r=Math.min(n.length-s,o);if(r<=0)throw new C("remote-no-ranges","a range request returned a short response",{wanted:o,available:n.length-s});return e.set(n.subarray(s,s+r),t),r}async function ti(e,t,n,s,o){let r=!1;try{o.requests+=1,await s(e,{method:"GET",mode:"no-cors",headers:{Range:"bytes=0-0"}}),r=!0}catch{r=!1}const i=n instanceof Error?`${n.name}: ${n.message}`:String(n);throw r?new C("remote-cors",`${t} is reachable but refused a cross-origin read of ${e} (${i}). That is what a missing “Access-Control-Allow-Origin” looks like from a browser: the failure has no status and no headers. Configure the bucket to allow GET and HEAD and the “Range” request header, and to expose “Content-Length” and “Content-Range”.`,{url:e,host:t,cause:i,reachable:!0}):new C("remote-cors",`${t} could not be reached for ${e} (${i}). The request failed before any response arrived, so this is a DNS, TLS or connectivity problem rather than a CORS one.`,{url:e,host:t,cause:i,reachable:!1})}function sn(e){try{return new URL(e).host}catch{return e}}async function Dd(e,t,n,s){try{return s.requests+=1,await t(e,{method:"HEAD",headers:{...n("HEAD"),Range:"bytes=0-"}})}catch{return null}}function ei(e){const t=(e?.headers.get("content-encoding")??"").trim().toLowerCase();return t===""||t==="identity"?null:t}function Fn(e,t){const n=e?.headers.get(t);if(n==null||n.trim()==="")return null;const s=Number(n);return Number.isFinite(s)?s:null}function Ud(e){return ka(e)?.start??null}function ka(e){if(!e)return null;const t=/bytes\s+(\d+)-(\d+)\/\s*(\d+|\*)\s*$/.exec(e);if(!t)return null;const n=Number(t[1]),s=Number(t[2]),o=t[3]==="*"?null:Number(t[3]);return!Number.isFinite(n)||!Number.isFinite(s)?null:{start:n,end:s,total:o!==null&&Number.isFinite(o)?o:null}}function ni(e){if(!e)return null;const t=/\/\s*(\d+)\s*$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null}function Gd(e){let t=0;for(let n=0;n<e.length;n++)t=Math.imul(31,t)+e.charCodeAt(n)|0;return t}(()=>{const e=new Int8Array(256).fill(-1),t=(n,s)=>{for(const o of n)e[o.charCodeAt(0)]=s,e[o.toLowerCase().charCodeAt(0)]=s};return t("TU",0),t("C",1),t("A",2),t("G",3),e})();const To=12,si=65536;function Hd(e){return e.length<To||e[0]!==31||e[1]!==139||e[2]!==8||(e[3]&4)===0?!1:Fo(e)!==null}function Fo(e){if(e.length<To)return null;const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint16(10,!0);let s=12;const o=Math.min(12+n,e.length);for(;s+4<=o;){const r=e[s],i=e[s+1],a=t.getUint16(s+2,!0);if(r===66&&i===67&&a===2)return t.getUint16(s+4,!0)+1;s+=4+a}return null}const qd=wa;async function _a(e,t=Number.POSITIVE_INFINITY,n=Mo){const s=[];let o=0,r=0;for(;r+To<=e.length;){const c=r,l=Fo(e.subarray(r,Math.min(r+64,e.length)));if(l===null||r+l>e.length)break;const h=new DataView(e.buffer,e.byteOffset+r,l).getUint16(10,!0),f=r+12+h,d=r+l-8;if(d>f){const m=await qd(e.subarray(f,d));if(m.length>0){if(o+m.length>n)throw la({format:"BGZF file",field:"span read"},n,e.length);s.push(m),o+=m.length}}if(r+=l,c>=t)break}const i=new Uint8Array(o);let a=0;for(const c of s)i.set(c,a),a+=c.length;return i}const Wd={ratio:64,floor:Mo,ceiling:2**34};async function jd(e,t=Mo){if(!(e.length>2&&e[0]===31&&e[1]===139))return e;if(typeof DecompressionStream>"u")throw new Error("This file is gzipped and this browser has no DecompressionStream to un-gzip it with. Decompress it and drop the plain text file.");return Hd(e)?_a(e,Number.POSITIVE_INFINITY,t):xo(e,{format:"file",field:"gzip stream",encoding:"gzip",maxBytes:t})}async function ro(e,t){if(e.kind==="local"){const r=Kd(e.file);return r!==null?r:(gn(),Vd(e.file,new te(e.file)))}if(e.reading==="whole"){const r=tm(e.url);return r!==null?r:Jd(e.url,await Ra(e.url,mn(e),t))}const n=e.reading??"",s=Xd(e.url,n);if(s!==null)return s;const o=mn(e);try{return oi(e.url,n,await de.open(e.url,{...o,...e.reading==="fine"?{chunkSize:za,readAhead:!1,...t?.onRead===void 0?{}:{onRead:t.onRead.bind(t)}}:{}}))}catch(r){if(r instanceof C&&r.code==="remote-compressed")return oi(e.url,n,await Zd(e.url,r,o));if(r instanceof C)throw r;const i=ss(e.url);throw new C("remote-cors",`Could not read ${e.url}. The host ${i} either did not allow this page to read it (CORS must permit GET and HEAD and expose Content-Length and Content-Range) or refused the request outright. Underlying error: ${r instanceof Error?r.message:String(r)}`,{url:e.url,host:i})}}async function Qd(e){if(e.kind==="local")return new te(e.file);const t=mn(e);return e.reading==="whole"?await Ra(e.url,t):await de.open(e.url,{...t,...e.reading==="fine"?{chunkSize:za,readAhead:!1}:{}})}async function Ta(e){if(e.kind==="local")return e.index===void 0?null:new te(e.index);const t=`${Yd(e.url)}.px2`;try{return await de.open(t,mn(e))}catch{return null}}function Yd(e){const t=e.search(/[?#]/);return t<0?e:e.slice(0,t)}function mn(e){return{...e.credential===void 0?{}:{credential:e.credential},...e.headers===void 0?{}:{headers:e.headers}}}function Fa(e){return e===void 0?{}:"accessKeyId"in e?{credential:e}:e}let fe=null,ze=null;function Vd(e,t){return ze={file:e,source:t},Ge(t)}function Kd(e){return ze===null||ze.file!==e?null:Ge(ze.source)}function oi(e,t,n){return fe={url:e,reading:t,source:n},Ge(n)}function Ge(e){const t=e.readExact?.bind(e);return{id:e.id,size:e.size,isRemote:e.isRemote,mount:()=>e.mount(),readBytes:(n,s)=>e.readBytes(n,s),...t===void 0?{}:{readExact:t},stats:()=>e.stats(),close:()=>{}}}function Xd(e,t){return fe===null||fe.url!==e||fe.reading!==t?(gn(),null):Ge(fe.source)}function gn(){fe?.source.close(),fe=null,ze?.source.close(),ze=null,re?.source.close(),re=null}const ri=128<<20;async function Zd(e,t,n={}){const s=t.detail.encodedLength,o=typeof s=="number"?s:null;if(o!==null&&o>ri)throw new C("remote-too-large",`${t.message} Downloading it whole is the only way left to read it, and at ${Math.round(o/(1<<20))} MB encoded that is too much to ask a browser tab for. Download it and drop it here instead.`,{...t.detail,limit:ri});let r;try{const i=await fetch(e,{headers:me({url:e,method:"GET",...Fa(n)})});if(!i.ok)throw new Error(`${i.status} ${i.statusText}`);r=new Uint8Array(await i.arrayBuffer())}catch(i){throw new C("remote-compressed",`${t.message} Falling back to downloading it whole also failed: ${i instanceof Error?i.message:String(i)}`,t.detail)}return new te(r,{name:e})}const za=16384,ii=2*(1<<30);async function Ra(e,t={},n){let s;try{const o=await fetch(e,{headers:me({url:e,method:"GET",...Fa(t)})});if(!o.ok)throw new Error(`${o.status} ${o.statusText}`);const r=Number(o.headers.get("Content-Length")??Number.NaN);if(Number.isFinite(r)&&r>ii)throw new C("remote-too-large",`${e} is ${(r/(1<<30)).toFixed(1)} GB, which is more than a browser tab can hold in memory. Download it and drop it here instead, where it is read from disk rather than held.`,{url:e,size:r,limit:ii});s=await Pa(o,n)}catch(o){throw o instanceof C||nm(o)?o:new C("remote-cors",`Could not download ${e} whole: ${o instanceof Error?o.message:String(o)}`,{url:e,host:ss(e)})}return new te(s,{name:e})}let re=null;function Jd(e,t){return gn(),re={url:e,source:t},Ge(t)}function tm(e){return re===null?null:re.url!==e?(re.source.close(),re=null,null):Ge(re.source)}async function ai(e,t){let n;if(e.kind==="local")n=new Uint8Array(await e.file.arrayBuffer());else{let s;try{s=await fetch(e.url,{headers:me({url:e.url,method:"GET",...mn(e)})})}catch(o){throw new C("remote-cors",`Could not read ${e.url}: ${o instanceof Error?o.message:String(o)}. The host ${ss(e.url)} must allow this page to GET it.`,{url:e.url,host:ss(e.url)})}if(!s.ok)throw new C("remote-cors",`${e.url} answered ${s.status} ${s.statusText}.`,{url:e.url,status:s.status});n=await Pa(s,t)}return jd(n,ca(n.length,Wd))}function em(){const e=new Error("cancelled");return e.name="AbortError",e}function nm(e){return e instanceof Error&&e.name==="AbortError"}async function Pa(e,t){const n=Number(e.headers.get("Content-Length")??Number.NaN),s=Number.isFinite(n)&&n>0?n:0,o=sm(e)?0:s,r=e.body,i=t?.onProgress;if(r===null||t===void 0)return new Uint8Array(await e.arrayBuffer());const a=r.getReader(),c=()=>{throw a.cancel(),em()};let l=0;if(o>0){const u=new Uint8Array(o);for(;;){const{done:h,value:f}=await a.read();if(h)break;if(t.cancelled?.()===!0&&c(),f!==void 0){if(l+f.length>o){const d=[u.subarray(0,l),f];return await ci(a,t,c,d,l+f.length)}u.set(f,l),l+=f.length,i?.(l,o)}}if(i?.(l,o),l<o){const h=e.url??"";throw new C("remote-cors",`${h===""?"The response":h} ended after ${l} bytes, short of the ${o} its \`Content-Length\` promised. The transfer was cut off; a partial file is not opened as though it were whole. Retry it, or download the file and drop it here.`,{url:e.url,received:l,declared:o})}return u}return await ci(a,t,c,[],0)}async function ci(e,t,n,s,o){const r=t.onProgress;for(o>0&&r?.(o,0);;){const{done:c,value:l}=await e.read();if(c)break;t.cancelled?.()===!0&&n(),l!==void 0&&(s.push(l),o+=l.length,r?.(o,0))}const i=new Uint8Array(o);let a=0;for(const c of s)i.set(c,a),a+=c.length;return i}function sm(e){const t=(e.headers.get("Content-Encoding")??"").trim().toLowerCase();return t!==""&&t!=="identity"}function ss(e){try{return new URL(e).host}catch{return e}}const li=["+-","-+","--","++"],zn=[1,2,4,10,20,40],om=8;function rm(e=om){const t=1/e,n=Math.ceil(9.001/t),s=new Set([0]);for(let o=0;o<n;o++)s.add(Math.round(10**(o*t)));return[...s].sort((o,r)=>o-r)}const ui=33,ks=43,_s=45;function im(e,t){return e===ks?t===_s?0:t===ks?3:-1:e===_s?t===ks?1:t===_s?2:-1:-1}const am=1024;class cm{constructor(t,n){this.contigs=t,this.pairTypeColumn=n,this.edges=rm(),this.distFreq=li.map(()=>new Float64Array(this.edges.length)),this.nContigs=t.length,this.densePairs=t.length<=am?new Float64Array(t.length*t.length):null}total=0;totalUnmapped=0;totalMapped=0;totalDups=0;cis=0;trans=0;cisAtLeast=new Float64Array(zn.length);edges;distFreq;shortTypes=new Float64Array(65536);typeOrder=[];longTypes=new Map;nContigs;densePairs;sparsePairs=new Map;namedPairs=new Map;pairSeen=new Map;decoder=new TextDecoder;pairTypeSeen=!1;add(t,n,s,o,r,i,a,c,l,u,h,f,d){this.total++;let m=!1;if(f>=0&&d>f)if(this.pairTypeSeen=!0,d-f===2){const A=t[f]<<8|t[f+1];this.shortTypes[A]===0&&this.typeOrder.push(String.fromCharCode(t[f],t[f+1])),this.shortTypes[A]++,m=A===17476}else{const A=this.decoder.decode(t.subarray(f,d));this.longTypes.has(A)||this.typeOrder.push(A),this.longTypes.set(A,(this.longTypes.get(A)??0)+1)}const g=o-s===1&&t[s]===ui,w=a-i===1&&t[i]===ui;if(g&&w){this.totalUnmapped++;return}if(g||w)return;if(this.totalMapped++,m){this.totalDups++;return}let p;if(n>=0&&r>=0){p=n===r;const A=n*this.nContigs+r;if(this.densePairs!==null)this.densePairs[A]===0&&this.notePair(this.contigs[n].name,this.contigs[r].name),this.densePairs[A]++;else{const x=this.sparsePairs.get(A);x===void 0&&this.notePair(this.contigs[n].name,this.contigs[r].name),this.sparsePairs.set(A,(x??0)+1)}}else{const A=n>=0?this.contigs[n].name:this.decoder.decode(t.subarray(s,o)),x=r>=0?this.contigs[r].name:this.decoder.decode(t.subarray(i,a));p=A===x;const E=`${A} ${x}`;this.namedPairs.has(E)||this.notePair(A,x),this.namedPairs.set(E,(this.namedPairs.get(E)??0)+1)}if(!p){this.trans++;return}if(this.cis++,c<0||l<0)return;const b=Math.abs(l-c),y=im(u,h);if(y>=0){const A=this.edges;let x=0,E=A.length;for(;E-x>1;){const S=x+E>>1;A[S]<=b?x=S:E=S}this.distFreq[y][x]++}for(let A=0;A<zn.length;A++)b>=zn[A]*1e3&&this.cisAtLeast[A]++}notePair(t,n){const s=`${t} ${n}`;this.pairSeen.has(s)||this.pairSeen.set(s,this.pairSeen.size)}result(t){const n=c=>c.length===2&&this.longTypes.get(c)===void 0?this.shortTypes[c.charCodeAt(0)<<8|c.charCodeAt(1)]:this.longTypes.get(c)??0,s=this.typeOrder.map((c,l)=>({name:c,count:n(c),order:l})).sort((c,l)=>l.count-c.count||c.order-l.order).map(({name:c,count:l})=>[c,l]),o=[],r=this.nContigs;if(this.densePairs!==null)for(let c=0;c<this.densePairs.length;c++){const l=this.densePairs[c];l>0&&o.push({name1:this.contigs[Math.floor(c/r)].name,name2:this.contigs[c%r].name,count:l})}else for(const[c,l]of this.sparsePairs)o.push({name1:this.contigs[Math.floor(c/r)].name,name2:this.contigs[c%r].name,count:l});for(const[c,l]of this.namedPairs){const[u,h]=c.split(" ");o.push({name1:u,name2:h,count:l})}const i=c=>this.pairSeen.get(`${c.name1} ${c.name2}`)??0;o.sort((c,l)=>l.count-c.count||i(c)-i(l));const a={};return li.forEach((c,l)=>{a[c]=Array.from(this.distFreq[l])}),{total:this.total,totalUnmapped:this.totalUnmapped,totalSingleSidedMapped:this.total-this.totalMapped-this.totalUnmapped,totalMapped:this.totalMapped,totalDups:this.totalDups,totalNodups:this.totalMapped-this.totalDups,cis:this.cis,trans:this.trans,pairTypes:s,cisAtLeast:zn.map((c,l)=>[c,this.cisAtLeast[l]]),chromFreq:o.map(({name1:c,name2:l,count:u})=>[c,l,u]),distEdges:[...this.edges],distFreq:a,chromsizes:this.contigs.map(c=>[c.name,c.length]),pairTypeColumn:this.pairTypeColumn&&this.pairTypeSeen,scoped:t}}}const lm=9,um=35,Ts=1<<20;class hm{unique=new Map;ambiguous=new Map;byName=new Map;decoder=new TextDecoder;constructor(t){for(let n=0;n<t.length;n++){const s=t[n].name;this.byName.set(s,n);const o=fm(s),r=this.unique.get(o);if(r===void 0&&!this.ambiguous.has(o)){this.unique.set(o,n);continue}const i=this.ambiguous.get(o)??[];r!==void 0&&(i.push([t[r].name,r]),this.unique.delete(o)),i.push([s,n]),this.ambiguous.set(o,i)}}lookup(t,n,s){let o=2166136261;for(let c=n;c<s;c++)o^=t[c],o=Math.imul(o,16777619);o|=0;const r=this.unique.get(o);if(r!==void 0)return r;const i=this.ambiguous.get(o);if(i===void 0)return-1;const a=this.decoder.decode(t.subarray(n,s));for(const[c,l]of i)if(c===a)return l;return-1}of(t){return this.byName.get(t)??-1}}function fm(e){let t=2166136261;const n=new TextEncoder().encode(e);for(let s=0;s<n.length;s++)t^=n[s],t=Math.imul(t,16777619);return t|0}const dm=1.05;function mm(e){const t=[0,1];let n=1;for(;n<e;)n=Math.max(n+1,Math.round(n*dm)),t.push(n);return Float64Array.from(t)}function gm(e,t){return e===Fs?t===Fs?0:t===zs?1:-1:e===zs?t===Fs?2:t===zs?3:-1:-1}const Fs=43,zs=45;async function wm(e,t){const{binSize:n,contigs:s,columns:o}=t,r=t.oneBased??!0,i=No(s,n),a=ya(s,n),c=new hm(s),l=s.length,u=o.strand1>=0&&o.strand2>=0,h=o.pairType??-1,f=Math.max(o.chrom1,o.chrom2,o.pos1,o.pos2,...u?[o.strand1,o.strand2]:[],h),d=new cm(s,h>=0),m=t.onRecord;let g=0;for(const U of s)g=Math.max(g,U.length);const w=u?mm(g):null,p=w===null?null:[new Float64Array(w.length-1),new Float64Array(w.length-1),new Float64Array(w.length-1),new Float64Array(w.length-1)];let b=0;const y=new Int32Array(s.length);for(let U=0;U<s.length;U++)y[U]=Math.max(0,Math.ceil(s[U].length/n)-1);const A=new Int32Array(a);let x=new Int32Array(Math.min(a,65536)),E=0,S=new Int32Array(Ts),v=new Int32Array(Ts),I=new Int32Array(Ts),N=0,B=-1,z=0,R=0,P=0,L=0,j=0,W=!1,J=!1,Z=-1;const It=new Set;let pt=!1,Ut=!1;const Qt=new Uint8Array(s.length);let Et=null;const k=t.maxPixelBytes===void 0?1/0:Math.floor(t.maxPixelBytes/12),G=()=>{if(E===0)return;const U=x.subarray(0,E);if(U.sort(),N+E>k)throw Et=new C("dense-too-large",`Binning this file at ${n} bp produces more stored pixels than the memory budget allows. Choose a coarser base resolution, or import fewer sequences.`,{binSize:n,nnz:N,limitBytes:t.maxPixelBytes}),Et;for(;N+E>S.length;)S=Rn(S),v=Rn(v),I=Rn(I);for(let q=0;q<E;q++){const tt=U[q];S[N]=B,v[N]=tt,I[N]=A[tt],N++,A[tt]=0}E=0},H=t.expectedRecords??0,mt=U=>{if(U.length===0||U[0]===um)return;let q=0,tt=0,nt=-1,K=-1,bt=-1,wt=-1,yt=-1,Yt=-1,we=0,qe=0,pe=0,be=0,We=-1,ye=-1;const je=U.length;for(let $=0;$<=je;$++)if(!($!==je&&U[$]!==lm)){if(q===o.chrom1?(nt=c.lookup(U,tt,$),we=tt,qe=$):q===o.chrom2?(K=c.lookup(U,tt,$),pe=tt,be=$):q===h?(We=tt,ye=$):q===o.pos1?bt=hi(U,tt,$):q===o.pos2?wt=hi(U,tt,$):u&&q===o.strand1?yt=$>tt?U[tt]:-1:u&&q===o.strand2&&(Yt=$>tt?U[tt]:-1),q++,q>f)break;tt=$+1}if(d.add(U,nt,we,qe,K,pe,be,bt,wt,yt,Yt,We,ye),m!==void 0&&m(U,nt,we,qe,K,pe,be,bt,wt,yt,Yt,We,ye),nt<0||K<0){P++;return}if(bt<0||wt<0){L++;return}if(p!==null&&w!==null&&nt===K){const $=gm(yt,Yt);if($>=0){const O=Math.abs(wt-bt);let _=0,T=w.length-1;for(;_+1<T;){const F=_+T>>1;w[F]<=O?_=F:T=F}p[$][_]++,b++}}let Tt=gt(bt),Nt=gt(wt);if(Tt>y[nt]&&(Tt=y[nt],j++),Nt>y[K]&&(Nt=y[K],j++),Tt+=i[nt],Nt+=i[K],Tt>Nt){const $=Tt;Tt=Nt,Nt=$}nt===K&&(Qt[nt]=1);let M=!1;if(!J){const $=nt<=K?nt*l+K:K*l+nt;$!==Z&&(M=!0,Z>=0&&It.add(Z),It.has($)&&(J=!0,It.clear()),Z=$)}Tt!==B&&(Tt<B&&(W=!0,M||(J=!0)),G(),B=Tt),A[Nt]===0&&(E===x.length&&(x=Rn(x)),x[E++]=Nt),A[Nt]++,z++,R++};function gt(U){const q=r?U-1:U;return q<0?0:Math.floor(q/n)}const ct=t.spans??[{from:0,to:e.size}],_t=ct.reduce((U,q)=>U+Math.max(0,q.to-q.from),0);let ge=0;try{for(const U of ct){const q={from:U.from,to:U.to,onProgress:nt=>{H>0?t.onProgress?.(z,H,"reading records"):t.onProgress?.(ge+nt,_t,"reading records")}};t.cancelled!==void 0&&(q.cancelled=t.cancelled),t.spans===void 0&&(q.onFraming=nt=>{Ut=!0,(nt.partialMember||!nt.endedOnEofMarker)&&(pt=!0)});const tt=await $o(Co(e,q),mt,t.cancelled);if(ge+=Math.max(0,U.to-U.from),!tt||t.cancelled?.()===!0)return null}G()}catch(U){throw Et!==null?Et:U}const lt={binSize:n,contigs:[...s],chromOffset:i,nBins:a,bin1:S.subarray(0,N),bin2:v.subarray(0,N),count:I.subarray(0,N),nnz:N,sum:R,skippedUnknownContig:P,skippedBadPosition:L,clampedPosition:j,wasUnsorted:J,truncated:Ut&&pt,contigsWithoutCisContacts:s.filter((U,q)=>Qt[q]===0).map(U=>U.name),orientation:w===null||p===null?null:{edges:w,counts:p,total:b},stats:d.result(t.spans!==void 0)};return W?La(lt):lt}function Rn(e){const t=new Int32Array(e.length*2);return t.set(e),t}function hi(e,t,n){if(n<=t)return-1;let s=0;for(let o=t;o<n;o++){const r=e[o]-48;if(r<0||r>9)return-1;s=s*10+r}return s}function La(e){const{nnz:t,nBins:n}=e,s=new Int32Array(n+1);for(let h=0;h<t;h++)s[e.bin1[h]+1]++;for(let h=0;h<n;h++)s[h+1]+=s[h];const o=s.slice(0,n),r=new Int32Array(t),i=new Int32Array(t);for(let h=0;h<t;h++){const f=o[e.bin1[h]]++;r[f]=e.bin2[h],i[f]=e.count[h]}const a=new Int32Array(t),c=new Int32Array(t),l=new Int32Array(t);let u=0;for(let h=0;h<n;h++){const f=s[h],d=s[h+1];if(d<=f)continue;let m=!0;for(let p=f+1;p<d;p++)if(r[p]<r[p-1]){m=!1;break}const g=m?null:Array.from({length:d-f},(p,b)=>f+b);g?.sort((p,b)=>r[p]-r[b]);let w=-1;for(let p=0;p<d-f;p++){const b=g===null?f+p:g[p],y=r[b];if(y===w){l[u-1]+=i[b];continue}a[u]=h,c[u]=y,l[u]=i[b],u++,w=y}}return{...e,bin1:a.subarray(0,u),bin2:c.subarray(0,u),count:l.subarray(0,u),nnz:u}}const Da=[1,2,5,10,20,50,100,200,500,1e3,2e3,5e3,1e4],pm=Da.length;function bm(e,t){const n=Math.max(1,Math.min(t,pm));return Da.slice(0,n).map(s=>e*s)}function ym(e,t){const n=new Int32Array(t);for(let s=0;s+1<e.length;s++){const o=e[s],r=e[s+1];for(let i=o;i<r&&i<t;i++)n[i]=s}return n}async function Am(e,t,n={}){if(t===e.binSize)return e;if(t%e.binSize!==0)throw new Error(`A ladder rung must be a whole multiple of the base: ${t} is not a multiple of ${e.binSize}.`);const s=t/e.binSize,o=e.contigs,r=No(o,t),i=ya(o,t),a=ym(e.chromOffset,e.nBins),c=A=>{const x=a[A];return r[x]+Math.floor((A-e.chromOffset[x])/s)},l=new Int32Array(i);let u=new Int32Array(Math.min(i,65536)),h=0,f=new Int32Array(Math.min(e.nnz,1<<20)||1),d=new Int32Array(f.length),m=new Int32Array(f.length),g=0,w=-1,p=0;const b=()=>{if(h===0)return;const A=u.subarray(0,h);for(A.sort();g+h>f.length;)f=Pn(f),d=Pn(d),m=Pn(m);for(let x=0;x<h;x++){const E=A[x];f[g]=w,d[g]=E,m[g]=l[E],g++,l[E]=0}h=0},y=1<<20;for(let A=0;A<e.nnz;A+=y){if(n.cancelled?.()===!0)return null;const x=Math.min(A+y,e.nnz);for(let E=A;E<x;E++){const S=c(e.bin1[E]),v=c(e.bin2[E]);S!==w&&(b(),w=S),l[v]===0&&(h===u.length&&(u=Pn(u)),u[h++]=v),l[v]+=e.count[E],p+=e.count[E]}n.onProgress?.(x,e.nnz,`aggregating to ${t} bp`),await St()}return b(),{binSize:t,contigs:[...o],chromOffset:r,nBins:i,bin1:f.subarray(0,g),bin2:d.subarray(0,g),count:m.subarray(0,g),nnz:g,sum:p,skippedUnknownContig:e.skippedUnknownContig,skippedBadPosition:e.skippedBadPosition,clampedPosition:e.clampedPosition,wasUnsorted:e.wasUnsorted,truncated:e.truncated,contigsWithoutCisContacts:[...e.contigsWithoutCisContacts]}}function Pn(e){const t=new Int32Array(Math.max(1,e.length*2));return t.set(e),t}const Mm=[{magic:"PX2.004",wideLinecount:!0},{magic:"PX2.003",wideLinecount:!1},{magic:"PX2.002",wideLinecount:!1}],fi=[36,40,44];function xm(e){if(e.length<20)throw new C("format","This .px2 index is too short to hold a header.",{bytes:e.length});const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=String.fromCharCode(...e.subarray(0,8)),s=Mm.find(p=>p.magic===n);if(s===void 0)throw new C("format","This is not a pairix index: the magic bytes are not PX2. A `.tbi` cannot be used for a pairs file — build one with `pairix <file>.pairs.gz`.",{magic:n.replace(/[^\x20-\x7e]/g,"?")});const o=t.getInt32(8,!0);let r=12,i;s.wideLinecount?(i=Number(t.getBigUint64(r,!0)),r+=8):(i=t.getUint32(r,!0),r+=4);const a=Sm(t,e,r,o),{splitChar:c,metaChar:l,lineSkip:u,namesAt:h,nameBytes:f}=a,d=[],m=new TextDecoder().decode(e.subarray(h,h+f));for(const p of m.split("\0"))p!==""&&d.push(p);let g=h+f;const w=new Map;for(let p=0;p<o&&!(g+4>e.length);p++){const b=t.getInt32(g,!0);g+=4;let y=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY;for(let E=0;E<b&&!(g+8>e.length);E++){g+=4;const S=t.getInt32(g,!0);g+=4;for(let v=0;v<S&&!(g+16>e.length);v++){const I=Number(t.getBigUint64(g,!0)>>16n),N=Number(t.getBigUint64(g+8,!0)>>16n);g+=16,I<y&&(y=I),N>A&&(A=N)}}if(g+4>e.length)break;const x=t.getInt32(g,!0);g+=4;for(let E=0;E<x&&!(g+8>e.length);E++){const S=Number(t.getBigUint64(g,!0)>>16n);g+=8,S>0&&S<y&&(y=S)}Number.isFinite(y)&&Number.isFinite(A)&&p<d.length&&w.set(d[p],{from:y,to:A})}return{keys:d,spans:w,linecount:i,splitChar:c,metaChar:l,lineSkip:u}}function Sm(e,t,n,s){const o=[];for(const r of fi){const i=n+r;if(i+4>t.length)continue;const a=e.getInt32(i,!0),c=i+4;if(o.push(a),a<=0||c+a>t.length||new TextDecoder().decode(t.subarray(c,c+a)).split("\0").filter(h=>h!=="").length!==s)continue;const u=n+28;return{splitChar:String.fromCharCode(t[u+1]||124),metaChar:String.fromCharCode(t[u+2]||35),lineSkip:e.getInt32(n+32,!0),namesAt:c,nameBytes:a}}throw new C("format",`This .px2 index has a header this reader cannot lay out: no candidate config size produced a coherent name block for ${s} references. Rebuild it with \`pairix <file>.pairs.gz\`, or open the file without an index.`,{nRef:s,candidates:fi,sawNameBytes:o})}async function Im(e){const t=await e();if(t===null)return null;try{const n=t.readBytes(0,t.size);return xm(await _a(n))}finally{t.close()}}function Em(e,t,n){const s=[];for(const r of t){const i=e.spans.get(r);i!==void 0&&s.push({from:i.from,to:vm(n,i.to)})}s.sort((r,i)=>r.from-i.from);const o=[];for(const r of s){const i=o[o.length-1];i!==void 0&&r.from<=i.to+(1<<20)?i.to=Math.max(i.to,r.to):o.push({...r})}return o}function vm(e,t){if(t>=e.size)return e.size;const n=e.readBytes(t,Math.min(si,e.size-t)),s=Fo(n);return s===null?Math.min(e.size,t+si):Math.min(e.size,t+s)}const Cm=12;async function Ua(e,t){const n=await ba(e);let s=null;try{s=await Im(t)}catch(r){if(!(r instanceof C))throw r;s=null}let o=0;for(const r of n.contigs)o+=r.length;return{header:n,index:s,records:s?.linecount??null,genomeLength:o,sourceBytes:e.size}}function $m(e,t=wn()){const n=e.records??Nm(e),s=Math.max(1,Math.floor(t/Cm)),o=Math.max(1e3,Math.min(Math.sqrt(s*2),2e5)),r=Math.max(1,e.genomeLength/o),i=Math.max(r,e.genomeLength/Math.max(1,Math.sqrt(n)));return Bm(i)}function Nm(e){return Math.max(1,Math.round(e.sourceBytes*4.5/55))}function Bm(e){if(!Number.isFinite(e)||e<=1)return 1;const t=10**Math.floor(Math.log10(e));for(const n of[1,2,5,10])if(e<=n*t)return n*t;return 10*t}async function Ga(e,t,n){const s=bm(n.base,n.rungs),o=n.maxPixelBytes??wn(),r=.85,i=(h,f)=>{n.onProgress?.(Math.round(h*1e3),1e3,f)},a=n.keys===void 0?void 0:Om(t,n.keys,e),c={binSize:n.base,contigs:t.header.contigs,columns:t.header.columns,oneBased:n.oneBased??!0,maxPixelBytes:o,onProgress:(h,f,d)=>{i(f>0?h/f*r:0,d??"reading records")}};a!==void 0&&(c.spans=a),t.records!==null&&(c.expectedRecords=t.records),n.cancelled!==void 0&&(c.cancelled=n.cancelled);const l=await wm(e,c);if(l===null)return null;const u=new Map([[n.base,l]]);for(let h=1;h<s.length;h++){const f=s[h],d=await Am(l,f,{onProgress:(m,g)=>{const w=g>0?m/g:1,p=(h-1+w)/Math.max(1,s.length-1);i(r+p*(1-r),`building the ${Ha(f)} rung`)},...n.cancelled===void 0?{}:{cancelled:n.cancelled}});if(d===null)return null;u.set(f,d)}return i(1,"done"),{header:t.header,rungs:s,tables:u,indexed:t.index!==null,declaredRecords:t.records}}function Om(e,t,n){if(e.index===null)return;const s=Em(e.index,t,n);return s.length===0?void 0:s}function km(e,t,n){if(Mt(n).path!==Mt(t).path)return null;const s=/^\/resolutions\/(\d+)$/.exec(Mt(n).group);if(s===null)return null;const o=Number(s[1]);return e.tables.has(o)?o:null}function Ha(e){return e>=1e6&&e%1e6===0?`${e/1e6} Mb`:e>=1e3&&e%1e3===0?`${e/1e3} kb`:`${e} bp`}function _m(e){return`${(e.split(/[\\/]/).pop()??"pairs").replace(/\.px2$/i,"").replace(/\.b?gz$/i,"").replace(/\.pairs$/i,"")||"pairs"}.mcool`}const os="0.17.0",Rs=1<<20;function Tm(){if(!Re())return"";const e=globalThis.process?.env;return(e?.TMPDIR??e?.TMP??e?.TEMP??"/tmp").replace(/\/+$/,"")}const rs="<q",cn="<i",Fm="HDF5::Cooler",zm="HDF5::MCOOL",Rm=3,Pm=2,Lm="https://github.com/open2c/cooler";async function qa(e,t={}){const n=await ae(),s=`${Tm()}/pairs-export-${Date.now()}.mcool`;n.FS.analyzePath(s).exists&&n.FS.unlink(s);try{return await Dm(n,s,e,t)}finally{n.FS.analyzePath(s).exists&&n.FS.unlink(s)}}async function Dm(e,t,n,s){const o=new e.File(t,"w");try{o.create_attribute("format",zm),o.create_attribute("format-version",Pm);const i=o.create_group("resolutions"),a=n.rungs.reduce((l,u)=>l+(n.tables.get(u)?.nnz??0),0);let c=0;for(const l of n.rungs){const u=n.tables.get(l);if(u===void 0)continue;const h=i.create_group(String(l));if(Um(h,u,n,l,s.about),c=await Hm(h,u,c,a,s),s.cancelled?.()===!0)return null;s.onProgress?.(c,a,`writing the ${Ha(l)} rung`)}}finally{o.close()}const r=e.FS.readFile(t);return r instanceof Uint8Array?r:new Uint8Array(r)}function Um(e,t,n,s,o){const r=t.contigs.length;e.create_attribute("format",Fm),e.create_attribute("format-version",Rm),e.create_attribute("format-url",Lm),e.create_attribute("bin-type","fixed"),e.create_attribute("bin-size",s),e.create_attribute("storage-mode","symmetric-upper"),e.create_attribute("nchroms",r),e.create_attribute("nbins",t.nBins),e.create_attribute("nnz",t.nnz),e.create_attribute("sum",t.sum),e.create_attribute("generated-by",o?.generatedBy??`chromosomix ${os} (pairs import; unbalanced)`),e.create_attribute("creation-date",new Date().toISOString()),n.header.assembly!==null&&e.create_attribute("genome-assembly",n.header.assembly),e.create_attribute("metadata",JSON.stringify(o===void 0?qm(n,t):o.metadata(t)));const i=e.create_group("chroms");i.create_dataset({name:"name",data:t.contigs.map(f=>f.name)}),i.create_dataset({name:"length",data:Int32Array.from(t.contigs,f=>f.length),dtype:cn});const a=e.create_group("bins"),c=new Int32Array(t.nBins),l=new Int32Array(t.nBins),u=new Int32Array(t.nBins);for(let f=0;f<r;f++){const d=t.chromOffset[f],m=t.chromOffset[f+1],g=t.contigs[f].length;for(let w=d;w<m;w++){const p=(w-d)*s;c[w]=f,l[w]=p,u[w]=Math.min(p+s,g)}}a.create_dataset({name:"chrom",data:c,dtype:cn}),a.create_dataset({name:"start",data:l,dtype:cn}),a.create_dataset({name:"end",data:u,dtype:cn});const h=e.create_group("indexes");h.create_dataset({name:"chrom_offset",data:BigInt64Array.from(t.chromOffset,f=>BigInt(f)),dtype:rs}),h.create_dataset({name:"bin1_offset",data:Gm(t),dtype:rs})}function Gm(e){const t=new BigInt64Array(e.nBins+1);let n=0;for(let s=0;s<e.nBins;s++){for(;n<e.nnz&&e.bin1[n]===s;)n++;t[s+1]=BigInt(n)}return t}async function Hm(e,t,n,s,o){const r=e.create_group("pixels"),i=t.nnz,a=Math.min(Rs,Math.max(1,i)),c=r.create_dataset({name:"bin1_id",data:Ln(t.bin1,0,Math.min(a,i)),shape:[Math.min(a,i)],maxshape:[null],chunks:[a],dtype:rs,compression:"gzip"}),l=r.create_dataset({name:"bin2_id",data:Ln(t.bin2,0,Math.min(a,i)),shape:[Math.min(a,i)],maxshape:[null],chunks:[a],dtype:rs,compression:"gzip"}),u=r.create_dataset({name:"count",data:t.count.slice(0,Math.min(a,i)),shape:[Math.min(a,i)],maxshape:[null],chunks:[a],dtype:cn,compression:"gzip"});if(i>a){c.resize([i]),l.resize([i]),u.resize([i]);for(let h=a;h<i;h+=Rs){if(o.cancelled?.()===!0)return n+h;const f=Math.min(h+Rs,i);c.write_slice([[h,f]],Ln(t.bin1,h,f)),l.write_slice([[h,f]],Ln(t.bin2,h,f)),u.write_slice([[h,f]],t.count.slice(h,f)),o.onProgress?.(n+f,s,"writing pixels"),await new Promise(d=>setTimeout(d,0))}}return n+i}function Ln(e,t,n){const s=new BigInt64Array(Math.max(0,n-t));for(let o=0;o<s.length;o++)s[o]=BigInt(e[t+o]);return s}function qm(e,t){const n=e.header;return{"generated-by":`chromosomix ${os}`,"imported-from":"pairs","pairs-format":n.version,"pairs-sorted":n.sorted,"pairs-shape":n.shape,"pairs-indexed":e.indexed,"pairs-header":n.text,"records-binned":t.sum,...e.declaredRecords==null?{}:{"records-declared-by-index":e.declaredRecords},...t.skippedUnknownContig===0?{}:{"records-skipped-unknown-contig":t.skippedUnknownContig},...t.skippedBadPosition===0?{}:{"records-skipped-bad-position":t.skippedBadPosition},...t.clampedPosition===0?{}:{"positions-clamped":t.clampedPosition},...t.wasUnsorted?{"required-merge-pass":!0}:{},...t.truncated?{"source-truncated":!0}:{},...t.contigsWithoutCisContacts.length===0?{}:{"sequences-without-cis-contacts":t.contigsWithoutCisContacts},balanced:!1,note:"Raw counts, unbalanced. Run `cooler balance` to add a bins/weight column."}}class Ps{data=new Int32Array(65536);length=0;push(t){if(this.length===this.data.length){const n=new Int32Array(this.data.length*2);n.set(this.data),this.data=n}this.data[this.length++]=t}view(){return this.data.subarray(0,this.length)}}async function Wm(e,t={}){const n=[...e.chromnames],s=Array.from(e.coords.contigLengths),o=e.binsize,r=n.map((g,w)=>({name:g,length:s[w]})),i=No(r,o),a=i[i.length-1],c=new Ps,l=new Ps,u=new Ps;let h=!1;if(await e.storedPixels.scanAll({onChunk:g=>{if(t.cancelled?.()===!0)return h=!0,!1;for(let w=0;w<g.length;w++){const p=g.bin1[w],b=g.bin2[w],y=Math.round(g.count[w]);y<=0||p<0||b<0||p>=a||b>=a||(c.push(p<=b?p:b),l.push(p<=b?b:p),u.push(y))}return!0},...t.onProgress===void 0?{}:{onProgress:t.onProgress}}),h)return null;const f={binSize:o,contigs:r,chromOffset:i,nBins:a,bin1:c.view().slice(),bin2:l.view().slice(),count:u.view().slice(),nnz:u.length,sum:0,skippedUnknownContig:0,skippedBadPosition:0,clampedPosition:0,wasUnsorted:!0,truncated:!1,contigsWithoutCisContacts:[]},d=La(f);let m=0;for(let g=0;g<d.nnz;g++)m+=d.count[g];return{...d,sum:m}}function jm(e){return/\.matrix(\.gz)?$/i.test(e)}function is(e){const t=e.replace(/\.matrix(\.gz)?$/i,"").replace(/_iced$/i,"");return[`${t}_abs.bed`,`${t}_abs.bed.gz`]}const fn=9,Lt=10,Wa=13,ja=35,Qm=43,io=45,Ym=46,Ot=48,$e=57,Vm=69,Km=101;function Xm(e,t){const n=[],s=[],o=[0];let r=0,i=0,a=null,c=0,l=!1;const u=new TextDecoder,h=e.length;let f=0;for(;f<h;){if(e[f]===Lt||e[f]===Wa){f++;continue}if(e[f]===ja||Jm(e,f)){for(;f<h&&e[f]!==Lt;)f++;continue}const g=f;for(;f<h&&e[f]!==fn&&e[f]!==Lt;)f++;const w=u.decode(e.subarray(g,f));if(f<h&&e[f]===Lt)throw ve(t,i+1,"a row with one column");f++;const p=Ls(e,f);if(f=p.at,e[f]!==fn)throw ve(t,i+1,"a row with two columns");f++;const b=Ls(e,f);f=b.at;let y=null;if(e[f]===fn){f++;const x=Ls(e,f);if(f=x.at,!x.saw)throw new C("format",`${t} is a BED whose fourth column holds names rather than bin ids, so it describes features rather than a bin grid — drop it as a track instead. A HiC-Pro bin file numbers its bins 1…n, and is written as \`<prefix>_<res>_abs.bed\`.`,{label:t,row:i+1});y=x.value}for(;f<h&&e[f]!==Lt;)f++;f++;const A=b.value-p.value;if(A<=0)throw ve(t,i+1,`an interval of width ${A}`);if(A>r&&(r=A),i++,y!==null&&(l||(a=y),l=!0,c=y),n.length===0||n[n.length-1]!==w){if(n.includes(w))throw ve(t,i,`${JSON.stringify(w)} in two separate runs of rows`);n.push(w),s.push(b.value),o.push(i-1)}else s[s.length-1]=b.value}if(i===0)throw ve(t,0,"no rows at all");const d=Float64Array.from([...o.slice(1),i]);if(d.length!==n.length+1)throw ve(t,i,`${n.length} sequences but ${d.length} offsets`);const m=Zm(n.length,d,s,r);if(a!==null&&(a!==1||c!==i))throw new C("format",`${t} is not a HiC-Pro bin file: its bin ids run ${a}…${c} over ${i} rows, and HiC-Pro numbers them 1…n in row order. If this is an ordinary BED, it describes features rather than a bin grid — drop it as a track instead.`,{label:t,firstId:a,lastId:c,rows:i});return{names:n,lengths:Float64Array.from(s),chromOffset:d,nBins:i,binsize:m?r:null,fixed:m}}function Zm(e,t,n,s){if(s<=0)return!1;for(let o=0;o<e;o++){const r=t[o+1]-t[o],i=(r-1)*s;if(n[o]<=i||n[o]>r*s)return!1}return!0}function Jm(e,t){const n="track";if(t+n.length>e.length)return!1;for(let s=0;s<n.length;s++)if(e[t+s]!==n.charCodeAt(s))return!1;return!0}function ve(e,t,n){return new C("format",`${e} is not a HiC-Pro bin file: ${n}${t>0?` at row ${t}`:""}. The file beside a \`.matrix\` is \`chrom start end binID\`, one row per bin of the whole genome, and HiC-Pro writes it as \`<prefix>_<res>_abs.bed\`.`,{label:e,row:t})}const tg=()=>{},eg=()=>!1;async function ng(e,t,n,s={}){const o=e.length;let r=0;for(let B=0;B<o;B++)e[B]===Lt&&r++;if(o>0&&e[o-1]!==Lt&&r++,r===0)throw new C("format",`${n} holds no pixels. A HiC-Pro matrix is \`binA binB count\`, one row per non-zero pixel.`,{label:n});const i=new Int32Array(r),a=new Int32Array(r),c=new Float32Array(r),l=new Uint8Array(r),u={out:0,line:0,sawUpper:!1,sawLower:!1};let h=0,f=0;const d=s.onProgress??tg,m=s.cancelled??eg;for(;f<o;){const B=og(e,Math.min(o,f+sg));if(f=rg(e,f,B,t,n,i,a,c,l,u),await St(),m())throw lg();d(u.out,r)}const g=u.out,{sawUpper:w,sawLower:p}=u,b=w&&p?"mixed":p?"lower":"upper",y=ag(a,g,t),{order:A,offsets:x}=cg(i,y,g,t),E=new Int32Array(g),S=new Int32Array(g),v=new Float32Array(g),I=new Uint8Array(g);for(let B=0;B<g;B++){const z=A[B];E[B]=i[z],S[B]=a[z],v[B]=c[z],I[B]=l[z]}const N=ig(E,S,v,I,x,t);for(let B=0;B<N.nnz;B++)h+=v[B];return{bin1:E.subarray(0,N.nnz),bin2:S.subarray(0,N.nnz),count:v.subarray(0,N.nnz),binOffset:N.binOffset,nnz:N.nnz,sum:h,observed:b==="mixed"&&N.mirrored>0?"complete":b}}const sg=1<<23;function og(e,t){let n=t;for(;n<e.length&&e[n]!==Lt;)n++;return Math.min(e.length,n+1)}function rg(e,t,n,s,o,r,i,a,c,l){let u=t,h=l.out,f=l.line,d=l.sawUpper,m=l.sawLower;for(;u<n;){if(e[u]===Lt||e[u]===Wa){u++;continue}if(e[u]===ja){for(;u<n&&e[u]!==Lt;)u++;continue}f++;let g=0,w=!1;for(;u<n;){const v=e[u];if(v<Ot||v>$e)break;g=g*10+(v-Ot),w=!0,u++}if(!w||e[u]!==fn)throw Ds(o,f,s);u++;let p=0,b=!1;for(;u<n;){const v=e[u];if(v<Ot||v>$e)break;p=p*10+(v-Ot),b=!0,u++}if(!b||e[u]!==fn)throw Ds(o,f,s);u++;let y=0,A=!1,x=!1;for(e[u]===io&&(x=!0,u++);u<n;){const v=e[u];if(v<Ot||v>$e)break;y=y*10+(v-Ot),A=!0,u++}if(e[u]===Ym){u++;let v=.1;for(;u<n;){const I=e[u];if(I<Ot||I>$e)break;y+=(I-Ot)*v,v/=10,A=!0,u++}}if(e[u]===Km||e[u]===Vm){const v=u;u++;let I=1;e[u]===io?(I=-1,u++):e[u]===Qm&&u++;let N=0,B=!1;for(;u<n;){const z=e[u];if(z<Ot||z>$e)break;N=N*10+(z-Ot),B=!0,u++}B?y*=10**(N*I):u=v}if(!A)throw Ds(o,f,s);for(x&&(y=-y);u<n&&e[u]!==Lt;)u++;u++;const E=g-1,S=p-1;if(E<0||S<0||E>=s||S>=s)throw new C("format",`${o} names bin ${g} × ${p} on line ${f}, and the bin file has ${s} bins numbered 1…${s}. The two halves of the pair are for different resolutions, or for different genomes.`,{label:o,line:f,bin1:g,bin2:p,nBins:s});E<S&&(d=!0),E>S&&(m=!0),r[h]=E<=S?E:S,i[h]=E<=S?S:E,a[h]=y,c[h]=E<=S?0:1,h++}return l.out=h,l.line=f,l.sawUpper=d,l.sawLower=m,u}function ig(e,t,n,s,o,r){let i=0,a=0;const c=new Float64Array(r+1);for(let l=0;l<r;l++){const u=o[l],h=o[l+1];c[l]=i;let f=-1;for(let d=u;d<h;d++){if(d>u&&t[d]===t[d-1]){if(s[d]!==f){a++,f=-2;continue}n[i-1]+=n[d];continue}f=s[d],e[i]=l,t[i]=t[d],n[i]=n[d],i++}}return c[r]=i,{nnz:i,binOffset:c,mirrored:a}}function ag(e,t,n){const s=new Int32Array(n+1);for(let r=0;r<t;r++)s[e[r]+1]++;for(let r=0;r<n;r++)s[r+1]+=s[r];const o=new Int32Array(t);for(let r=0;r<t;r++)o[s[e[r]]++]=r;return o}function cg(e,t,n,s){const o=new Float64Array(s+1);for(let a=0;a<n;a++)o[e[a]+1]++;for(let a=0;a<s;a++)o[a+1]+=o[a];const r=Float64Array.from(o),i=new Int32Array(n);for(let a=0;a<n;a++){const c=t[a];i[r[e[c]]++]=c}return{order:i,offsets:o}}function Ls(e,t){let n=0,s=!1,o=1;for(e[t]===io&&(o=-1,t++);t<e.length;){const r=e[t];if(r<Ot||r>$e)break;n=n*10+(r-Ot),s=!0,t++}return{value:n*o,at:t,saw:s}}function Ds(e,t,n){return new C("format",`${e} is not a HiC-Pro matrix: line ${t} is not \`binA binB count\`. The bin file beside it has ${n} bins, and the matrix names pairs of them, tab-separated, one pixel per line.`,{label:e,line:t,nBins:n})}function lg(){const e=new Error("cancelled");return e.name="AbortError",e}async function ug(e,t,n={}){const s=await wg(t);return s===null?await hg(e,t,n):await mg(e,t,s,n)}async function hg(e,t,n){const s=n.detached===!0?await Qd(t):await ro(t,{...n.report===void 0?{}:{onProgress:(r,i)=>n.report?.(r,i,"downloading")},...n.cancelled===void 0?{}:{cancelled:n.cancelled},...n.report===void 0||!di(e)?{}:{onRead:(r,i)=>n.report?.(i,0,`listing cells · ${r.toLocaleString()} reads`)}}),o=t.kind==="remote"&&t.reading!==void 0;di(e)&&n.report?.(0,0,"listing cells");try{return{mc:await et.open(e,s,{...o?{listingAgreed:!0}:{},...n.metacool===void 0?{}:{metacool:n.metacool}}),source:s}}catch(r){const i=n.binning;if(i===void 0||!(r instanceof C)||r.code!=="pairs-binning-needed")throw r;return{mc:await fg(e,t,s,i,n),source:s}}}async function fg(e,t,n,s,o){const r=await Ua(n,()=>Ta(t)),i=await Ga(n,r,{base:s.base,rungs:s.rungs,oneBased:s.oneBased??!0,...o.report===void 0?{}:{onProgress:(c,l,u)=>o.report?.(c,l,u??"binning records")},...o.cancelled===void 0?{}:{cancelled:o.cancelled}});if(i===null)throw dg();const a=i.tables.get(i.rungs[0]);if(a===void 0)throw new C("format",`${e} imported no pixel table.`);return et.fromPairs({uri:e,header:i.header,pixels:a,rungs:i.rungs,indexed:i.indexed,declaredRecords:i.declaredRecords})}function dg(){const e=new Error("open cancelled");return e.name="AbortError",e}async function mg(e,t,n,s){const o=ao(n),r=ao(t),i=u=>({...s.report===void 0?{}:{onProgress:(h,f)=>s.report?.(h,f,u)},...s.cancelled===void 0?{}:{cancelled:s.cancelled}}),a=await ai(n,i("reading the bins")),c=Xm(a,o);await yg(t,r,c.nBins);const l=await ai(t,i("downloading the matrix"));return gg(e,{bytes:l,name:r},c,o,a.length,s)}async function gg(e,t,n,s,o,r={}){const i=await ng(t.bytes,n.nBins,t.name,{...r.cancelled===void 0?{}:{cancelled:r.cancelled},...r.report===void 0?{}:{onProgress:(c,l)=>r.report?.(c,l,"reading pixels")}});return{mc:et.fromHicPro(e,{bins:n,pixels:i,matrixName:t.name,binsName:s}),source:Mg(t.name,o+t.bytes.length)}}async function wg(e){const t=ao(e);if(!jm(t))return null;if(e.bins!==void 0)return e.bins;if(e.kind==="remote"){const n=await pg(e.url,e.credential,e.headers);if(n!==null)return n}throw new C("hicpro-no-bins",`${t} is a HiC-Pro matrix, which is half of a contact map: the bin file beside it — ${is(t).join(" or ")} — is what says which genomic interval each bin id means, and there are no coordinates without it. Drop the two together, pick the matrix out of a connected folder so its bin file comes with it, or name the bin file on the URL as \`<matrix>#bins=<url>\`.`,{matrix:t,wanted:is(t)})}async function pg(e,t,n){if(_o(e))return null;const s=e.lastIndexOf("/"),o=s<0?"":e.slice(0,s+1),r=e.slice(s+1),i=is(r).map(c=>`${o}${c}`);if(o.includes("/iced/"))for(const c of is(r))i.push(`${o.replace("/iced/","/raw/")}${c}`);const a={...t===void 0?{}:{credential:t},...n===void 0?{}:{headers:n}};for(const c of i)try{if((await fetch(c,{method:"HEAD",headers:me({url:c,method:"HEAD",...a})})).ok)return{kind:"remote",url:c,...a}}catch{}return null}function di(e){return/\.scool(\.gz)?(\?|#|$)/i.test(e)}const bg=200<<20;async function yg(e,t,n){if(e.reading!==void 0)return;const s=await Ag(e);if(s===null||s<=bg)return;const o=Math.round(s/15);throw new C("hicpro-load-cost",`${t} is ${Math.round(s/(1<<20))} MB of text, and a HiC-Pro matrix has no index — so the whole of it is read and turned into about ${o.toLocaleString()} pixels over ${n.toLocaleString()} bins before anything can be drawn. That is the only cost: afterwards every region is instant and panning is free.`,{matrix:t,bytes:s,pixels:o,nBins:n})}async function Ag(e){if(e.kind==="local")return e.file.size;if(_o(e.url))return null;try{const t=await fetch(e.url,{method:"HEAD",headers:me({url:e.url,method:"HEAD",...e.credential===void 0?{}:{credential:e.credential},...e.headers===void 0?{}:{headers:e.headers}})}),n=Number(t.headers.get("Content-Length")??Number.NaN);return Number.isFinite(n)?n:null}catch{return null}}function ao(e){const t=e.kind==="local"?e.file.name:e.url;return t.split(/[\\/]/).pop()?.split(/[?#]/)[0]??t}function Mg(e,t){return{id:e,size:t,isRemote:!1,mount:()=>Promise.resolve(e),readBytes(){throw new C("unsupported",`${e} was read whole and parsed at open; there are no bytes left to read from it. A read reaching here is a code path that bypassed the parsed arrays.`,{id:e})},stats:()=>({requests:1,bytes:t}),close:()=>{}}}const xg=200,Sg=3e3,Ig=3e4,Eg=1e3;function vg(e=xg,t=Sg){const n=[];let s=performance.now();const o=setInterval(()=>{const r=performance.now(),i=r-s;for(s=r,i<Ig?n.push({at:r,span:i,late:Math.max(0,i-e)}):n.length=0;n.length>0&&r-n[0].at>t;)n.shift()},e);return{busy(){if(n.length<3)return 0;let r=0,i=0;for(const a of n)r+=a.span,i+=a.late;return r<=0?0:Math.min(1,i/r)},reset(){n.length=0,s=performance.now()},stop(){clearInterval(o)}}}const Cg=250,$g=50;class Ng{constructor(t=()=>performance.now(),n=s=>new Promise(o=>setTimeout(o,s))){this.now=t,this.sleep=n}reading=0;quietSince=Number.NEGATIVE_INFINITY;begin(){this.reading+=1;let t=!1;return()=>{t||(t=!0,this.reading-=1,this.quietSince=this.now())}}async quiet(t){for(await St();t?.()!==!0&&(this.reading>0||this.now()-this.quietSince<Cg);)await this.sleep($g)}}const Qa=self;ae().catch(()=>{});const Bg=1e6,mi=3;let Ct=null,Ya=0,Va={requests:0,bytes:0};const dt=new Set,co=new Ng;function rt(){if(Ct===null)throw new Error("no file is open in the reader worker");return Ct}async function He(e){const t=rt();if(e===void 0||e===""||!t.mc.entries.includes(e))return t.mc;const n=t.rungs.get(e);if(n!==void 0)return Us(t,e),n;if(t.pairs!==null){const i=t.pairs.tables.get(Number(e));if(i===void 0)return t.mc;const a=et.fromPairs({uri:t.mc.uri,header:t.pairs.header,pixels:i,rungs:t.pairs.rungs,indexed:t.pairs.indexed,declaredRecords:t.pairs.declaredRecords}),c=gi(t,a);for(wi(t,c),t.rungs.set(e,c),Us(t,e);t.recent.length>mi;){const l=t.recent.pop();if(l===void 0)break;t.rungs.get(l)?.close(),t.rungs.delete(l)}return c}const s=t.mc.entryGroup===""?"entries":t.mc.entryGroup,{path:o}=Mt(t.mc.uri);let r;try{r=await et.open(`${o}::${s}/${e}`,t.source,t.metacool===void 0?{}:{metacool:t.metacool})}catch{return t.mc}for(r=gi(t,r),wi(t,r),t.rungs.set(e,r),Us(t,e);t.recent.length>mi;){const i=t.recent.pop();if(i===void 0)break;t.rungs.get(i)?.close(),t.rungs.delete(i)}return r}function gi(e,t){if(e.lens===null)return t;const{map:n,refusal:s}=et.withLens(t,e.lens);return s===null?n:(t.close(),e.mc)}function wi(e,t){e.resample!==null&&t.resample(e.resample).catch(()=>{})}function Us(e,t){e.recent=[t,...e.recent.filter(n=>n!==t)]}function Ka(e){if(e!==null){for(const t of e.rungs.values())t.close();e.rungs.clear(),e.recent=[]}}function Gs(e,t,n){return e===t?n:Fl(e.coords,t.coords,n)}function ce(e,t=[]){Qa.postMessage(e,t)}function ne(e){return{cancelled:()=>dt.has(e),onProgress:(t,n,s)=>ce(s===void 0?{type:"progress",id:e,done:t,total:n}:{type:"progress",id:e,done:t,total:n,note:s})}}function $t(){const e=new Error("cancelled");return e.name="AbortError",e}async function Og(e,t){const n=await Ua(t,()=>Ta(e.source)),s=e.binning;if(s===void 0){const o={contigs:n.header.contigs.map(r=>({...r})),genomeLength:n.genomeLength,records:n.records,indexed:n.index!==null,assembly:n.header.assembly,sorted:n.header.sorted,sourceBytes:n.sourceBytes,suggestedBase:$m(n)};throw new C("pairs-binning-needed","This is a .pairs file: a list of contacts with no resolution of its own. Choose a bin size to build a map at.",o)}return Ga(t,n,{base:s.base,rungs:s.rungs,oneBased:s.oneBased??!0,...ne(e.id)})}function kg(e,t,n){const s=e.tables.get(e.rungs[0]),o=s.orientation??null;return{binning:n,orientation:o===null?null:{edges:o.edges,counts:o.counts,total:o.total},stats:s.stats??null,base:e.rungs[0],rungs:e.rungs,records:s.sum,nnz:s.nnz,indexed:e.indexed,skippedUnknownContig:s.skippedUnknownContig,skippedBadPosition:s.skippedBadPosition,clampedPosition:s.clampedPosition,requiredMerge:s.wasUnsorted,truncated:s.truncated,sequencesWithoutCisContacts:s.contigsWithoutCisContacts,download:t}}async function _g(e){const t=rt();if(t.pairs===null)throw new C("unsupported","This map was not imported from a .pairs file, so there is nothing to write: it is already a file on disk or on a bucket.",{layout:t.mc.layout.kind});const n=await qa(t.pairs,ne(e));if(n===null)throw $t();return{bytes:n,filename:_m(t.mc.uri),rungs:t.pairs.rungs}}const pi=6e7;async function Tg(e,t){const n=rt(),s=n.mc.unlensed??n.mc,o=ne(e),i=(s.entries.length>0?[...s.entries]:[""]).map(w=>({name:w,size:w===""?s.binsize:Number(w)})).sort((w,p)=>w.size-p.size),a=new Map,c=[];let l=0;for(const{name:w,size:p}of[...i].reverse()){const b=w===""?s:await Fg(n,w);if(b===null){c.push({rung:p,why:"it would not open"});continue}try{const y=b.nnz??0;if(l+y>pi){c.push({rung:p,why:`${y.toLocaleString("en-US")} pixels would pass the budget of ${pi.toLocaleString("en-US")}`});continue}const{map:A,refusal:x}=et.withLens(b,t);if(x!==null)throw new C("unsupported",x,{});const E=await Wm(A,{cancelled:o.cancelled,onProgress:(S,v)=>o.onProgress(S,v,`lifting the ${p.toLocaleString("en-US")} bp rung`)});if(E===null)throw $t();a.set(p,E),l+=E.nnz}finally{b!==s&&b.close()}}const u=[...a.keys()].sort((w,p)=>w-p);if(u.length===0)throw new C("unsupported","No rung of this map could be lifted within the budget.",{});const h=a.get(u[0]),f={version:"",assembly:null,sorted:null,shape:"upper triangle",contigs:h.contigs,columns:{chrom1:1,pos1:2,chrom2:3,pos2:4,strand1:-1,strand2:-1},text:""},d=await qa({header:f,rungs:u,tables:a,indexed:!1,declaredRecords:null},{...o,about:{generatedBy:`chromosomix ${os} (lifted through an edit of the reference; unbalanced)`,metadata:w=>({"generated-by":`chromosomix ${os}`,"lifted-from":n.mc.uri,"lifted-through":t.history.slice(0,t.cursor).map(p=>p.step),"contacts-written":w.sum,balanced:!1,note:"Raw counts through an edit of the reference: bins moved whole, a stretch set aside left out, a duplicated one written at each copy. Run `cooler balance` to add a bins/weight column."})}});if(d===null)throw $t();const m=(Mt(n.mc.uri).path.split("/").pop()??"map").replace(/\.(m?m?(meta)?cool|hic|pairs(\.b?gz)?)$/i,""),g=t.original.genome===void 0?"":`.${t.original.genome}`;return{bytes:d,filename:`${m}${g}.edited.mcool`,rungs:u,contacts:h.sum,skipped:c}}async function Fg(e,t){if(e.pairs!==null){const r=e.pairs.tables.get(Number(t));return r===void 0?null:et.fromPairs({uri:e.mc.uri,header:e.pairs.header,pixels:r,rungs:e.pairs.rungs,indexed:e.pairs.indexed,declaredRecords:e.pairs.declaredRecords})}const n=e.mc.unlensed??e.mc,s=n.entryGroup===""?"entries":n.entryGroup,{path:o}=Mt(n.uri);try{return await et.open(`${o}::${s}/${t}`,e.source,e.metacool===void 0?{}:{metacool:e.metacool})}catch{return null}}function zg(e,t){if(e?.pairs==null)return null;const n=km(e.pairs,e.mc.uri,t);return n===null?null:{pairs:e.pairs,size:n}}function gs(e){let t=0;return(n,s,o)=>{const r=Date.now();r-t<50&&n<s||(t=r,ce({type:"progress",id:e,done:n,total:s,note:o}))}}async function Rg(e){const t=zg(Ct,e.uri);Ka(Ct),t===null&&Ct?.mc.close(),Ct=null,dt.clear();const s={report:gs(e.id),cancelled:()=>dt.has(e.id),...e.metacool===void 0?{}:{metacool:e.metacool}};let o,r,i=t?.pairs??null;if(t!==null)r=await ro(e.source),o=et.fromPairs({uri:e.uri,header:t.pairs.header,pixels:t.pairs.tables.get(t.size),rungs:t.pairs.rungs,indexed:t.pairs.indexed,declaredRecords:t.pairs.declaredRecords});else try{({mc:o,source:r}=await ug(e.uri,e.source,s))}catch(l){if(!(l instanceof C)||l.code!=="pairs-binning-needed")throw l;if(r=await ro(e.source),i=await Og(e,r),i===null)throw $t();o=et.fromPairs({uri:e.uri,header:i.header,pixels:i.tables.get(i.rungs[0]),rungs:i.rungs,indexed:i.indexed,declaredRecords:i.declaredRecords})}let a=null,c=null;if(e.edit!==void 0){const l=et.withLens(o,e.edit);o=l.map,c=l.refusal,l.refusal===null&&(a=e.edit)}return Ct={mc:o,source:r,sourceKind:e.source.kind,rungs:new Map,recent:[],pairs:i,resample:null,lens:a,...e.metacool===void 0?{}:{metacool:e.metacool}},{...i===null||e.binning===void 0?{}:{pairs:kg(i,e.binning.download===!0,e.binning)},...e.edit===void 0?{}:{edit:{refusal:c}},uri:o.uri,layout:o.layout,info:o.info,metadata:o.metadata,binsize:o.binsize,shape:o.shape,nGenomes:o.nGenomes,nContigs:o.nContigs,nBins:o.nBins,unassigned:o.unassignedStats(),displayExtent:o.displayBinExtent(),entries:o.entries,entryGroup:o.entryGroup,cells:o.cells,activeCells:o.activeCells,cellNnz:o.cells.length>0&&!(e.source.kind==="remote"&&e.source.reading==="fine")?o.nnz:null,hasGenomes:o.hasGenomes,hasWeights:o.hasWeights,scoreColumns:o.scoreColumns,sourceBytes:r.size,contacts:o.declaredContacts,sourceKind:e.source.kind}}function Pg(){const{mc:e}=rt(),t=e.fullGenomes();if(t===null)return{table:{columns:[],length:0,data:{}},display:new Int32Array(0),density:new Float64Array(0)};const n=Int32Array.from(e.displayGenomes()),s=e.genomeDensities();return{table:ko(t),display:n,density:s}}function Lg(){return{table:ko(rt().mc.fullContigs())}}function Dg(){const{mc:e}=rt(),t=e.cellTable(),n=new Set(e.activeCells),s=e.cells,o=[];for(let r=0;r<s.length;r++)n.has(s[r])&&o.push(r);return{table:ko(t),selected:Int32Array.from(o)}}function Ug(e){const{mc:t}=rt();return t.selectCells(e.names),{names:t.activeCells,nnz:t.nnz??0,scoreColumns:t.scoreColumns}}function Gg(){return{columns:rt().mc.binColumns()}}function Hg(e){const{mc:t}=rt(),n=Math.max(0,Math.min(Math.trunc(e.from),t.nBins)),s=Math.max(n,Math.min(Math.trunc(e.to),t.nBins)),o=t.binColumn(e.column,n,s);return{column:e.column,from:n,to:s,...Array.isArray(o)?{text:o}:{values:o}}}function qg(e,t,n=!1){const s=n&&e.hasGenomes;return{nrows:t.nrows,ncols:t.ncols,values:t.values,rowExtent:t.rowExtent,colExtent:t.colExtent,rowGroups:Lr(e,t.rowExtent),colGroups:Lr(e,t.colExtent),...s?{rowGenomes:Dr(e,t.rowExtent),colGenomes:Dr(e,t.colExtent)}:{},level:"bin"}}function Xa(e,t){return e[0]===t[0]&&e[1]===t[1]?un.binSelection:un.range}async function Wg(e){const t=rt().mc,n=Math.max(256,Math.min(Ks,Math.trunc(e.cells??Ks))),s=t.unlensed??t;let o;if(e.contigs!==void 0){const S=new Map(s.chromnames.map((v,I)=>[v,I]));if(o=[...new Set(e.contigs.map(v=>S.get(v)).filter(v=>v!==void 0))].sort((v,I)=>v-I),o.length===0)throw new C("unsupported","None of the sequences the stage asked for are in this file.")}const r=Jg(s,n,o),i=await He(r),a=i.unlensed??i,c=Dl(a.coords,n,o);let l=null;try{l=a.store.binOffsets()}catch{l=null}const u=Ul(a.coords,l,o),h=c===null?null:Math.max(c,u);if(h===null)throw new C("unsupported",`The stage draws the whole assembly at ${n.toLocaleString("en-US")} cells a side, each inside one sequence, and this one has ${(o?.length??a.coords.nContigs).toLocaleString("en-US")} sequences.`);const f=Pl(a.coords,h,o),d=e.balance===!0&&a.hasWeights,m=Zg(a,l,o);ce({type:"progress",id:e.id,done:0,total:1,note:`${m===null?"every stored pixel":`${m.toLocaleString("en-US")} stored pixels`} at ${fc(a.binsize)}`+(h>1?`, ${h} bins a cell`:"")});const g=await a.picture(f,{balance:d,...e.value===void 0?{}:{value:e.value},...e.method===!0?{gather:bf}:{},...ne(e.id)});if(g===null||dt.has(e.id))throw $t();const{vmin:w,vmax:p}=Zl(g.histogram,g.quantizer),b=g.contacts,y=b===void 0?null:xf(b,d),A=b===void 0||y===null?void 0:{contacts:b,expected:y,corners:Of(b,y)},x=e.keep===!0&&A!==void 0,E=rt();return x&&(E.stageMethod={picture:e.id,...A}),{rung:i===t?null:r??null,binsize:a.binsize*h,stride:h,n:f.n,sequences:(o??a.chromnames.map((S,v)=>v)).map((S,v)=>({name:a.chromnames[S],length:a.coords.contigLengths[S],firstCell:f.offsets[v],cells:f.offsets[v+1]-f.offsets[v]})),levels:g.levels,low:g.quantizer.low,high:g.quantizer.high,vmin:w,vmax:p,balanced:d,pixels:g.pixels,least:Gl(a.coords,l,a.binsize,o),...A===void 0?{}:x?{methodKept:e.id}:{method:A}}}const jg=4e6;async function Qg(e){const t=rt(),n=t.mc.unlensed??t.mc,s=Za(n),o=s.filter(w=>w.size<=e.binsize),r=o.length>0?o[o.length-1]:s[0];if(r===void 0||!(r.size<e.coarser))return null;const i=`${r.name}|${e.key}`;if(t.stageWindowMap?.key!==i){const w=r.size===n.binsize?n:await He(r.name),p=w.unlensed??w,{map:b,refusal:y}=et.withLens(p,e.edit);if(y!==null)throw new C("unsupported",y);t.stageWindowMap={key:i,map:b}}const a=t.stageWindowMap.map,c=new Map(a.chromnames.map((w,p)=>[w,p])),l=a.coords.chromOffset,u=a.binsize,h=w=>{const p=c.get(w.from.sequence),b=c.get(w.to.sequence);if(p===void 0||b===void 0)return null;const y=Math.min(l[p+1]-1,l[p]+Math.floor(Math.max(0,w.from.bp)/u)),A=Math.min(l[b+1],l[b]+Math.ceil(Math.max(0,w.to.bp)/u));return A>y?[y,A]:null},f=h(e.rows),d=h(e.cols);if(f===null||d===null||(f[1]-f[0])*(d[1]-d[0])>jg)return null;const m=await a.matrix({rows:f,cols:d,balance:e.balance&&a.hasWeights}),g=([w,p])=>{const b=[];for(let y=0;y<a.chromnames.length;y++){const A=Math.max(w,l[y]),x=Math.min(p,l[y+1]);x>A&&b.push({sequence:a.chromnames[y],firstBin:A-l[y],count:x-A,at:A-w})}return b};return{binsize:u,rows:g(m.rowExtent),cols:g(m.colExtent),values:m.values,ncols:m.ncols}}function Za(e){return e.entryGroup==="resolutions"?e.entries.map(t=>({name:t,size:Number(t)})).filter(t=>Number.isInteger(t.size)&&t.size>0).sort((t,n)=>t.size-n.size):[{name:"",size:e.binsize}]}const Yg=4096;async function Vg(e){const t=rt(),n=t.mc.unlensed??t.mc,s=Za(n),o=Df(s.map(d=>d.size),e.cell,e.least);if(o.length===0)return e.points.map(()=>null);const r=au(e.edit);t.refineMaps?.fingerprint!==r&&(t.refineMaps={fingerprint:r,maps:new Map});const i=t.refineMaps.maps,a=t.refinePlaced??=new Map;a.size>Yg&&a.clear();const c=pn.of(e.edit),l=async d=>{const m=s.find(w=>w.size===d);if(m===void 0)return null;let g=i.get(m.name);if(g===void 0){const w=m.size===n.binsize?n:await He(m.name),{map:p,refusal:b}=et.withLens(w.unlensed??w,e.edit);if(b!==null)throw new C("unsupported",b);g=p,i.set(m.name,g)}return g},u=async(d,m,g,w)=>{if(dt.has(e.id))throw $t();const p=await l(w),b=p===null?-1:p.chromnames.indexOf(d);if(p===null||b<0)return null;const y=p.coords.chromOffset[b],A=[y+m,y+g],x=await p.matrix({rows:A,cols:A,balance:e.balance&&p.hasWeights});return x.nrows===g-m&&x.ncols===g-m?{n:g-m,values:x.values}:null},h=(Math.ceil(va*e.cell/o[0])+3*Oo+1)*o[0],f=[];for(const d of e.points){if(dt.has(e.id))throw $t();const m=c.lengthOf(d.sequence);if(m===null){f.push(null);continue}const g=d.bp,w=Math.max(0,g-h),p=Math.min(m,g+h),b=c.piecesIn(d.sequence,w,p).map(({offset:x,piece:E})=>`${x-g}:${E.sequence}:${E.start}:${E.end}:${E.strand}`).join(";"),y=[e.balance,e.cell,o.join(","),o.map(x=>g%x).join(","),w-g,p-g,b].join("|");let A=a.get(y);if(A===void 0){const x=await Hf(d,m,e.cell,o,u);A=x===null?null:{delta:x.bp-g,binsize:x.binsize,support:x.support},a.set(y,A)}f.push(A===null?null:{bp:g+A.delta,binsize:A.binsize,support:A.support})}return f}function Kg(e){const t=rt().stageMethod;if(t===void 0||t.picture!==e.picture)throw new C("unsupported","The picture these suggestions were asked of has been read again; they are counted against the new one.");const n=Bo.of(pn.of(e.edit),e.layout);return Vf({contacts:t.contacts,expected:t.expected,corners:t.corners,grid:n,...e.weights===void 0?{}:{weights:e.weights},...e.evidence===void 0?{}:{evidence:e.evidence}})}async function Xg(e){const t=rt().mc,n=t.unlensed??t;if(!n.hasGenomes)throw new C("unsupported","Only a metagenome has genomes a contig could belong to.");const s=n.coords.nContigs,o=new Map(n.chromnames.map((w,p)=>[w,p])),r=new Uint8Array(s);for(const w of e.contigs){const p=o.get(w);p!==void 0&&(r[p]=1)}const i=new Int32Array(n.nBins);for(let w=0;w<s;w++){const[p,b]=n.coords.contigBinExtent(w);i.fill(w,p,b)}const a=n.contigGenomeIds,c=n.genomeNames,l=new Float64Array(s),u=new Float64Array(s),h=new Map;for(let w=0;w<s;w++)r[w]===1&&h.set(w,new Float64Array(c.length));const f=ne(e.id);let d=0;if(await n.store.scanAll({onChunk:w=>{if(f.cancelled())return!1;for(let p=0;p<w.length;p++){const b=i[w.bin1[p]],y=i[w.bin2[p]];if(b===y)continue;const A=w.count[p];if(A>0){if(l[b]+=A,l[y]+=A,r[y]===1&&(u[b]+=A),r[b]===1){u[y]+=A;const x=h.get(b);x!==void 0&&a[y]>=0&&(x[a[y]]+=A)}if(r[y]===1){const x=h.get(y);x!==void 0&&a[b]>=0&&(x[a[b]]+=A)}}}return d+=w.length,!0},onProgress:(w,p)=>f.onProgress(w,p,"reading every contact for where the contigs belong")}),f.cancelled())throw $t();const m=[];for(const[w,p]of h){const b=[...p].map((y,A)=>({genome:c[A],contacts:y})).filter(y=>y.contacts>0).sort((y,A)=>A.contacts-y.contacts).slice(0,6);m.push({contig:n.chromnames[w],total:l[w],own:u[w],partners:b})}const g=[];for(let w=0;w<s;w++){if(r[w]===1||u[w]<3)continue;const p=a[w];g.push({contig:n.chromnames[w],genome:p>=0?c[p]:"__unbinned__",length:n.coords.contigLengths[w],contacts:u[w],total:l[w]})}return g.sort((w,p)=>p.contacts/p.total-w.contacts/w.total||p.contacts-w.contacts),{inside:m,outside:g.slice(0,100),pixels:d}}function Zg(e,t,n){if(n===void 0)return e.nnz??(t===null?null:t[t.length-1]);if(t===null)return null;let s=0;for(const o of n){const[r,i]=e.coords.contigBinExtent(o);s+=t[i]-t[r]}return s}function Jg(e,t,n){if(e.entryGroup!=="resolutions")return;const s=e.coords.contigLengths,o=n??Array.from({length:s.length},(c,l)=>l),r=c=>{let l=0;for(const u of o)l+=Math.ceil(s[u]/c);return l},i=e.entries.map(c=>({name:c,size:Number(c)})).filter(c=>Number.isInteger(c.size)&&c.size>0).sort((c,l)=>c.size-l.size);if(i.length===0)return;const a=i.find(c=>r(c.size)<=t)??i[i.length-1];return a.size===e.binsize?void 0:a.name}async function t0(e){const t=rt().mc,n=await He(e.rung),s=Gs(t,n,e.cols??e.rows),o=Gs(t,n,e.rows),r=tc(e.binsPerCell,e.contigsPerCell),i={rows:e.rows,cols:e.cols??e.rows};if(e.wrap!==void 0){const l=Gs(t,n,e.wrap);if(Hr(o,l)||Hr(s,l))return Dn(n,t,i,await fd(n,e,o,s,l,e0(n,e.id,e.budgetBytes)))}if(r.binsPerCell>1||r.contigsPerCell>1)return Dn(n,t,i,await bi(n,e,Oe(n,o,r),Oe(n,s,r),r));const a=Ja(n,o,s,e.budgetBytes);if(a!==null)return Dn(n,t,i,await bi(n,e,Oe(n,o,a),Oe(n,s,a),a));const c=await n.matrix({rows:o,cols:s,...e.balance===!0?{balance:!0}:{},...e.value===void 0?{}:{value:e.value},...e.budgetBytes===void 0?{}:{budgetBytes:e.budgetBytes}},Xa(o,s));return Dn(n,t,i,qg(n,c,e.genomes===!0))}function e0(e,t,n){return{planFor:(s,o,r)=>{const i=a=>{const c=Math.max(1,Math.min(a,s[1]-s[0]));return[s[0],s[0]+c]};return Ja(e,i(o),i(r),n)},snap:(s,o)=>Oe(e,s,o),hint:(s,o)=>Xa(s,o),throwIfCancelled:()=>{if(dt.has(t))throw $t()},hooks:ne(t)}}function Dn(e,t,n,s){return e===t?s:{...s,binsize:e.binsize,source:{rows:n.rows,cols:n.cols}}}async function bi(e,t,n,s,o){const r=t.id,i=await e.pooledMatrix({rows:n,cols:s,...t.balance===!0?{balance:!0}:{},...t.value===void 0?{}:{value:t.value}},o,ne(r));if(dt.has(r))throw $t();const a=l=>bn(l,u=>e.chromnames[u]??String(u),void 0,u=>e.coords.contigLengths[u],u=>e.coords.contigStartBin(u)),c=t.genomes===!0&&e.hasGenomes;return{nrows:i.nrows,ncols:i.ncols,values:i.values instanceof Float32Array?i.values:Float32Array.from(i.values),rowExtent:n,colExtent:s,rowGroups:lo(e,yi(e,a(i.rowIds),n,i.binsPerCell),i.rowMembers),colGroups:lo(e,yi(e,a(i.colIds),s,i.binsPerCell),i.colMembers),...c?{rowGenomes:dn(e,i.rowIds),colGenomes:dn(e,i.colIds)}:{},level:"bin",binsPerCell:i.binsPerCell,contigsPerCell:i.contigsPerCell,rowContigs:as(e,n),colContigs:as(e,s)}}function lo(e,t,n){return n.contigsPerCell<=1?t:t.map(s=>{const o=n.memberStart[s.start],r=n.memberStart[s.end],i=[];for(let a=o;a<r;a++){const c=n.members[a];a>o&&c===n.members[a-1]||i.push({label:e.chromnames[c]??String(c),unitLength:e.coords.contigLengths[c]??0})}return i.length>1?{...s,merged:i}:s})}function yi(e,t,[n],s){if(t.length===0||s<=1)return t;const[o]=e.coords.contigBinExtent(e.coords.contigOfBin(n)),r=Math.floor((n-o)/s);return r<=0?t:[{...t[0],unitStart:n+t[0].start-r},...t.slice(1)]}function as(e,[t,n]){return n<=t?0:e.coords.contigOfBin(n-1)-e.coords.contigOfBin(t)+1}function Ja(e,t,n,s){const o=t[0]===n[0]&&t[1]===n[1]?[t]:[t,n],r=Hc(s);if(o.every(([l,u])=>u-l<=r))return null;for(const[l,u]of o){const h=e.coords.contigOfBin(u-1)-e.coords.contigOfBin(l)+1;if(h>qt)return{binsPerCell:1,contigsPerCell:Math.ceil(h/qt)}}let i=2,a=2;const c=l=>o.every(u=>n0(e,Oe(e,u,{binsPerCell:l,contigsPerCell:1}),l));for(;!c(a);)a*=2;for(;i<a;){const l=i+a>>1;c(l)?a=l:i=l+1}return{binsPerCell:i,contigsPerCell:1}}function n0(e,[t,n],s){return s0(e,[t,n],s)<=qt}function s0(e,[t,n],s){if(n<=t)return 0;let o=0;const r=e.coords.contigOfBin(n-1);for(let i=e.coords.contigOfBin(t);i<=r;i++){const[a,c]=e.coords.contigBinExtent(i);o+=Math.ceil((Math.min(n,c)-Math.max(t,a))/s)}return o}function Oe(e,[t,n],s){if(n<=t)return[t,n];const[o]=e.coords.contigBinExtent(e.coords.contigOfBin(t)),[r,i]=e.coords.contigBinExtent(e.coords.contigOfBin(n-1));if(s.contigsPerCell>1)return[o,i];const a=s.binsPerCell;return a<=1?[t,n]:[o+Math.floor((t-o)/a)*a,Math.min(i,r+Math.ceil((n-r)/a)*a)]}function tc(e,t){return{binsPerCell:Math.max(1,Math.trunc(e??1)),contigsPerCell:Math.max(1,Math.trunc(t??1))}}async function o0(e){const{mc:t}=rt(),n=e.cols??e.rows,s=await t.aggregateSparse({rows:e.rows,cols:n,...e.balance===!0?{balance:!0}:{},...e.value===void 0?{}:{value:e.value}},e.level,ne(e.id));if(dt.has(e.id))throw $t();const o=td(t,s),r=e.genomes===!0&&t.hasGenomes&&e.level==="contig";return{nrows:s.nrows,ncols:s.ncols,values:Float32Array.from(s.values),rowExtent:e.rows,colExtent:n,rowGroups:o.rows,colGroups:o.cols,...r?{rowGenomes:dn(t,s.rowIds),colGenomes:dn(t,s.colIds)}:{},level:e.level,contigsPerCell:s.contigsPerCell,rowContigs:as(t,e.rows),colContigs:as(t,n)}}async function r0(e){const{mc:t}=rt(),n=e.id,s=[],o=i0(t,e.unit,e.names,e.naming,s);if(o.length===0)throw new C("unknown-label",`None of the ${e.unit==="genome"?"genomes":"sequences"} named are in this file, so there is nothing to draw. They may belong to another map.`,{unit:e.unit,names:e.names});const r=tc(e.binsPerCell,e.contigsPerCell),i={binsPerCell:Math.max(1,r.binsPerCell),contigsPerCell:1},a=e.unit==="genome"&&t.hasGenomes,c=await t.selectionMatrix(o,i,{...ne(n),...e.balance===!0?{balance:!0}:{},...e.value===void 0?{}:{value:e.value},...a?{byGenome:!0}:{},...e.budgetBytes===void 0?{}:{cellCap:Math.max(1,Math.floor(Math.sqrt(e.budgetBytes/4)))}});if(dt.has(n))throw $t();const l=bn(c.ids,d=>t.chromnames[d]??String(d),void 0,d=>t.coords.contigLengths[d]),u=t.hasGenomes?dn(t,c.ids):void 0,h=Jf(e.unit,u),f=lo(t,l,c.pooling);return{nrows:c.nrows,ncols:c.ncols,values:Float32Array.from(c.values),rowExtent:[0,c.nrows],colExtent:[0,c.ncols],rowGroups:f,colGroups:f,...u===void 0?{}:{rowGenomes:u,colGenomes:u},...h?{genomeBoundaries:!0}:{},level:"bin",binsPerCell:c.binsPerCell,contigsPerCell:c.contigsPerCell,rowContigs:o.length,colContigs:o.length,...s.length===0?{}:{matched:s}}}function i0(e,t,n,s,o){const r=new Set;for(const i of n){if(t==="contig"){const c=e.chromnames.indexOf(i);if(c>=0){r.add(c);continue}const l=e.names.find(i,s===void 0?{}:{from:s});if(l!==null){const u=e.chromnames.indexOf(l.name);u>=0&&(r.add(u),o?.push(l))}continue}const a=e.genomeNames.indexOf(i);if(!(a<0))for(let c=0;c<e.nContigs;c++)e.contigGenomeIds[c]===a&&r.add(c)}return[...r].map(i=>({id:i,extent:e.contigExtent(i)})).sort((i,a)=>i.extent[0]-a.extent[0])}async function ec(e){const{mc:t}=rt(),n=e.id,s=e.level??"genome";if(s==="genome"&&!t.hasGenomes)throw new C("unsupported","This file is a plain cooler and has no genomes, so there is no genome × genome view of it. The contig level is the same scan over the axes this file does have.",{level:s});const o=s==="genome"?t.displayGenomes():a0(t),r=Math.max(1,Math.trunc(e.maxUnits??rd(wn()))),i=s==="contig"&&t.hasGenomes?p=>t.contigGenomeIds[o[p]]:void 0,a=id(o.length,r,i),c=a.slots,l=s==="genome"?t.nGenomes:t.nContigs,u=new Int32Array(l).fill(-1);for(let p=0;p<o.length;p++)u[o[p]]=a.slotOf[p];const h=s==="genome"?nd(t):ed(t),f=t.storageMode==="symmetric-upper",d=f?new ld(c):null,m=f?null:new Float64Array(c*c);if(await t.scanPixels({chunkSize:Bg,onChunk:p=>{if(dt.has(n))return!1;if(d!==null)for(let b=0;b<p.length;b++){const y=u[h[p.bin1[b]]];if(y<0)continue;const A=u[h[p.bin2[b]]];A<0||d.add(y,A,p.count[b])}else for(let b=0;b<p.length;b++){const y=u[h[p.bin1[b]]];if(y<0)continue;const A=u[h[p.bin2[b]]];A<0||(m[y*c+A]+=p.count[b])}return!0},onProgress:(p,b)=>ce({type:"progress",id:n,done:p,total:b})}),dt.has(n))throw $t();const g=s==="genome"?t.genomeNames:t.chromnames,w=Ai(o,a,p=>g[p]);return{level:s,labels:w.labels,unitNames:w.unitNames,...s==="contig"&&t.hasGenomes?{groups:Ai(o,a,p=>t.genomeNames[t.contigGenomeIds[p]]).unitNames}:{},values:d!==null?d.toSquare():Float32Array.from(m),n:c,source:"scan",pooled:a.pooled,unitsPerSlot:a.pooled?o.length/c:1,totalUnits:o.length}}function Ai(e,t,n){const s=new Array(t.slots),o=new Int32Array(t.slots);for(let i=0;i<e.length;i++){const a=t.slotOf[i];o[a]===0&&(s[a]=e[i]),o[a]+=1}const r=Array.from({length:t.slots},(i,a)=>n(s[a])??String(s[a]));return{labels:r.map((i,a)=>o[a]>1?`${i} +${o[a]-1}`:i),unitNames:r}}function a0(e){const t=e.genomeNames.indexOf(ke),n=[];for(let s=0;s<e.nContigs;s++)(!e.hasGenomes||e.contigGenomeIds[s]!==t)&&n.push(s);return n}async function c0(e){const{mc:t,resample:n}=rt();if(n!==null)return ec({id:e.id,level:"genome"});const s=await fetch(e.url);if(!s.ok)throw new C("remote-cors",`The genome edge list at ${e.url} could not be read (HTTP ${s.status}).`,{url:e.url,status:s.status});const o=await s.text(),r=new Set(t.displayGenomes().map(f=>t.genomeNames[f])),i=[],a=new Set,c=[];for(const f of o.split(`
9
+ `)){const d=f.trim();if(d===""||d.startsWith("#"))continue;const m=d.split(" ");if(m.length<3)continue;const g=Number(m[2]);if(!Number.isFinite(g))continue;const[w,p]=m;if(!(!r.has(w)||!r.has(p))){for(const b of[w,p])a.has(b)||(a.add(b),i.push(b));c.push([w,p,g])}}i.sort();const l=new Map(i.map((f,d)=>[f,d])),u=i.length,h=new Float32Array(u*u);for(const[f,d,m]of c){const g=l.get(f),w=l.get(d);g===void 0||w===void 0||(h[g*u+w]=m,h[w*u+g]=m)}return{level:"genome",labels:i,unitNames:i,values:h,n:u,source:"edge-list",pooled:!1,unitsPerSlot:1,totalUnits:r.size}}async function l0(e){const t=e.id,n=await rt().mc.validateDeep({cancelled:()=>dt.has(t),onProgress:(s,o)=>ce({type:"progress",id:t,done:s,total:o})});if(dt.has(t))throw $t();return n}async function u0(e){const t=rt(),n=e.contacts===null?null:{contacts:e.contacts,...e.seed===void 0?{}:{seed:e.seed},...e.alpha===void 0?{}:{alpha:e.alpha}};t.resample=n;for(const i of t.rungs.values())i.resample(n).catch(()=>{});const s=gs(e.id),o=await t.mc.resample(n,{onProgress:(i,a)=>s(i,a,"counting contacts"),cancelled:()=>dt.has(e.id)}),r=await t.mc.takenCensus();return{mode:o?.mode??"none",contacts:n?.contacts??null,total:r?.total??null,census:r===null?null:{...r,a:r.a.slice(),b:r.b.slice(),sum:r.sum.slice()}}}async function h0(e){const t=rt(),n=t.mc.declaredContacts;if(n!==null)return{total:n};const s=t.mc.entries.filter(i=>/^\d+$/.test(i)).sort((i,a)=>Number(a)-Number(i)),o=s.length>0?await He(s[0]):t.mc,r=gs(e.id);return{total:await o.countContacts({onProgress:(i,a)=>r(i,a,"counting contacts"),pause:i=>co.quiet(i)})}}function f0(){const{source:e}=rt();return{total:e.stats(),lastOp:{...Va},calls:Ya}}function d0(e){return e==="matrix"||e==="aggregate"||e==="overview"||e==="selection"}async function m0(e){switch(e.kind){case"open":return Rg(e);case"exportMcool":return _g(e.id);case"exportLifted":return Tg(e.id,e.edit);case"genomes":return Pg();case"contigs":return Lg();case"cells":return Dg();case"selectCells":return Ug(e);case"binColumns":return Gg();case"binColumn":return Hg(e);case"range":return tf(await He(e.rung),e.range,e.naming,e.circular);case"matrix":return t0(e);case"aggregate":return o0(e);case"selection":return r0(e);case"overview":return ec(e);case"overviewSidecar":return c0(e);case"validateDeep":return l0(e);case"resample":return u0(e);case"contacts":return h0(e);case"stats":return f0();case"picture":return Wg(e);case"suggest":return Kg(e);case"stageWindow":return Qg(e);case"refine":return Vg(e);case"genomeLinks":return Xg(e);case"cancel":return dt.add(e.target),null;case"close":return Ka(Ct),Ct?.mc.close(),Ct=null,dt.clear(),gn(),null}}async function g0(e){Ya++;const t=e.kind==="contacts"||e.kind==="matrix"&&e.background===!0;t&&e.kind==="matrix"&&await co.quiet(()=>dt.has(e.id));const n=t?null:co.begin(),s=Ct?.source.stats(),o=w0(e.id);try{const r=await m0(e);if(d0(e.kind)&&s&&Ct){const i=Ct.source.stats();Va={requests:i.requests-s.requests,bytes:i.bytes-s.bytes}}ce({type:"result",id:e.id,kind:e.kind,payload:r},gd(r))}catch(r){ce({type:"error",id:e.id,error:md(r)})}finally{n?.(),o(),dt.delete(e.id)}}function w0(e){const t=Ct?.mc.store;if(!(t instanceof rn)||t.names.length<2)return()=>{};const n=gs(e),s=(o,r)=>n(o,r,"summing cells");return t.onCells=s,()=>{t.onCells===s&&(t.onCells=null)}}Qa.onmessage=e=>{g0(e.data)};const p0=vg();setInterval(()=>ce({type:"busy",fraction:p0.busy()}),Eg);