chromosomix 0.18.0 → 0.19.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.
@@ -5,5 +5,5 @@ const Vn="HDF5::MetaCooler";const Mi="HDF5::MMetaCooler",uo="HDF5::Cooler",ln="H
5
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
6
  `).join(""),l=a.map(([g])=>g).join(";"),u=[e.method.toUpperCase(),Nd(t.pathname),Bd(t.searchParams),c,l,r].join(`
7
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.18.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(`
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.19.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
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);
@@ -1,4 +1,4 @@
1
- import{bq as Gl,br as Gn,bs as Oa,bt as Vl,bu as Hl,bv as kl,bw as Wl}from"./index-BZqg8J4S.js";/**
1
+ import{by as Gl,bz as Gn,bA as Oa,bB as Vl,bC as Hl,bD as kl,bE as Wl}from"./index-CPxipgOR.js";/**
2
2
  * @license
3
3
  * Copyright 2010-2026 Three.js Authors
4
4
  * SPDX-License-Identifier: MIT