jbrowse-plugin-graphgenomeviewer 10.12.0 → 10.14.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.
- package/README.md +1 -1
- package/dist/chunks/AddTrackWorkflow-5I2MZDHJ.js +2 -0
- package/dist/chunks/AddTrackWorkflow-5I2MZDHJ.js.map +7 -0
- package/dist/chunks/{ChooseSamplesDialog-5PTJ6ZDV.js → ChooseSamplesDialog-VWZXPW22.js} +2 -2
- package/dist/chunks/{ChooseWalksDialog-DN6J7FGD.js → ChooseWalksDialog-UO6YQB2O.js} +2 -2
- package/dist/chunks/{GbzBaseSyntenyAdapter-YF3NLRTJ.js → GbzBaseSyntenyAdapter-5CIIRXKR.js} +2 -2
- package/dist/chunks/{GbzBaseSyntenyAdapter-YF3NLRTJ.js.map → GbzBaseSyntenyAdapter-5CIIRXKR.js.map} +2 -2
- package/dist/chunks/{GraphGenomeView-DMC5QM6K.js → GraphGenomeView-2O2E42B4.js} +2 -2
- package/dist/chunks/GraphSettingsDialog-3OG5GCLT.js +2 -0
- package/dist/chunks/{HighlightColorDialog-SHTLKIUR.js → HighlightColorDialog-Y2CSK6AP.js} +2 -2
- package/dist/chunks/LinearGraphDisplay-4EYMXR3M.js +2 -0
- package/dist/chunks/{MinigraphBubbleAdapter-2YICZ5GZ.js → MinigraphBubbleAdapter-XZJSCUDV.js} +2 -2
- package/dist/chunks/RgfaTabixAdapter-ONEIQRTJ.js +2 -0
- package/dist/chunks/RgfaTabixAdapter-ONEIQRTJ.js.map +7 -0
- package/dist/chunks/WalkFormsAdapter-XD3B3U2D.js +2 -0
- package/dist/chunks/WalkFormsAdapter-XD3B3U2D.js.map +7 -0
- package/dist/chunks/WalkTabixSyntenyAdapter-SNRXXD45.js +2 -0
- package/dist/chunks/WalkTabixSyntenyAdapter-SNRXXD45.js.map +7 -0
- package/dist/chunks/chunk-3352MMV6.js +2 -0
- package/dist/chunks/{chunk-T5QLBT77.js.map → chunk-3352MMV6.js.map} +3 -3
- package/dist/chunks/chunk-45ZFQDNY.js +2 -0
- package/dist/chunks/chunk-45ZFQDNY.js.map +7 -0
- package/dist/chunks/{chunk-HE5BVBEF.js → chunk-52Z3M7SW.js} +1 -1
- package/dist/chunks/{chunk-HE5BVBEF.js.map → chunk-52Z3M7SW.js.map} +1 -1
- package/dist/chunks/{chunk-2KAWXEZ7.js → chunk-66HYO4UP.js} +2 -2
- package/dist/chunks/{chunk-2KAWXEZ7.js.map → chunk-66HYO4UP.js.map} +2 -2
- package/dist/chunks/{chunk-VN2AFDYR.js → chunk-76QQ3Q56.js} +2 -2
- package/dist/chunks/{chunk-RSCG3J6K.js → chunk-ALUAL23O.js} +1 -1
- package/dist/chunks/{chunk-RSCG3J6K.js.map → chunk-ALUAL23O.js.map} +1 -1
- package/dist/chunks/chunk-B2EPNVM7.js +2 -0
- package/dist/chunks/chunk-B2EPNVM7.js.map +7 -0
- package/dist/chunks/{chunk-TAU773OE.js → chunk-EF34SRHG.js} +2 -2
- package/dist/chunks/chunk-GRSE4XMY.js +4 -0
- package/dist/chunks/chunk-GRSE4XMY.js.map +7 -0
- package/dist/chunks/{chunk-L3WMRCZB.js → chunk-J2DBFC7I.js} +2 -2
- package/dist/chunks/{chunk-L3WMRCZB.js.map → chunk-J2DBFC7I.js.map} +1 -1
- package/dist/chunks/chunk-KL2D2DTD.js +4 -0
- package/dist/chunks/chunk-KL2D2DTD.js.map +7 -0
- package/dist/chunks/chunk-NFYJ7H66.js +2 -0
- package/dist/chunks/chunk-NFYJ7H66.js.map +7 -0
- package/dist/chunks/{chunk-5IZ6O334.js → chunk-NHCD6IZL.js} +2 -2
- package/dist/chunks/chunk-ODX7AL6K.js +4 -0
- package/dist/chunks/chunk-ODX7AL6K.js.map +7 -0
- package/dist/chunks/{chunk-UQRQBSMW.js → chunk-P4IMSFPU.js} +2 -2
- package/dist/chunks/{chunk-J2PN6CG3.js → chunk-PCP5Y77D.js} +2 -2
- package/dist/chunks/{chunk-J2PN6CG3.js.map → chunk-PCP5Y77D.js.map} +2 -2
- package/dist/chunks/chunk-QNGSRFA7.js +8 -0
- package/dist/chunks/chunk-QNGSRFA7.js.map +7 -0
- package/dist/chunks/chunk-RO3UPSD2.js +2 -0
- package/dist/chunks/chunk-RO3UPSD2.js.map +7 -0
- package/dist/chunks/chunk-SHPBCGXL.js +2 -0
- package/dist/chunks/chunk-SHPBCGXL.js.map +7 -0
- package/dist/chunks/{chunk-AQQHLLOF.js → chunk-SJPFWJFH.js} +2 -2
- package/dist/chunks/{chunk-NYBFFFFQ.js → chunk-U4ZQHJHX.js} +2 -2
- package/dist/chunks/chunk-U4ZQHJHX.js.map +7 -0
- package/dist/chunks/chunk-WKN2JNDM.js +9 -0
- package/dist/chunks/chunk-WKN2JNDM.js.map +7 -0
- package/dist/chunks/{chunk-BMQ36R2W.js → chunk-Y4FOBBLT.js} +1 -1
- package/dist/chunks/{chunk-BMQ36R2W.js.map → chunk-Y4FOBBLT.js.map} +1 -1
- package/dist/chunks/chunk-Y74MVEM7.js +2 -0
- package/dist/chunks/chunk-Y74MVEM7.js.map +7 -0
- package/dist/chunks/{chunk-WRXZ2CHO.js → chunk-YUTTHEWC.js} +2 -2
- package/dist/chunks/{chunk-WRXZ2CHO.js.map → chunk-YUTTHEWC.js.map} +1 -1
- package/dist/chunks/{renderSvg-76L4L63F.js → renderSvg-YR7AUBB7.js} +2 -2
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +1 -1
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +2 -2
- package/package.json +3 -3
- package/src/GetSubgraph.test.ts +32 -0
- package/src/GetSubgraph.ts +35 -5
- package/src/GraphAddTrackWorkflow/walkReference.ts +1 -1
- package/src/GraphGenomeView/components/HoverTooltip.test.tsx +122 -1
- package/src/GraphGenomeView/components/HoverTooltip.tsx +51 -9
- package/src/GraphGenomeView/components/PaneContextMenu.tsx +1 -1
- package/src/GraphGenomeView/model.color.test.ts +4 -3
- package/src/GraphGenomeView/pane/fitViews.ts +23 -4
- package/src/GraphGenomeView/pane/graphViews.ts +38 -12
- package/src/GraphGenomeView/pane/hostViews.ts +22 -26
- package/src/GraphGenomeView/pane/loadActions.ts +65 -28
- package/src/GraphGenomeView/pane/paneBase.ts +4 -2
- package/src/GraphGenomeView/pane/renderingActions.ts +3 -1
- package/src/GraphGenomeView/pane/settingActions.ts +5 -2
- package/src/GraphGenomeView/pane/spanIn.test.ts +55 -0
- package/src/GraphGenomeView/pane/tubeMapViews.ts +32 -3
- package/src/GraphGenomeView/runsLoad.test.ts +149 -0
- package/src/GraphGenomeView/threadFoldCut.test.ts +1 -1
- package/src/GraphGenomeView/threadFoldCut.ts +47 -3
- package/src/GraphGenomeView/unloadedWalks.ts +1 -1
- package/src/LinearGraphDisplay/LinearGraphDisplay.test.ts +22 -3
- package/src/RgfaTabixAdapter/RgfaTabixAdapter.test.ts +6 -6
- package/src/RgfaTabixAdapter/RgfaTabixAdapter.ts +21 -10
- package/src/RgfaTabixAdapter/configSchema.ts +3 -2
- package/src/RgfaTabixAdapter/walkCut.ts +11 -2
- package/src/RgfaTabixAdapter/walkFiles.test.ts +241 -27
- package/src/RgfaTabixAdapter/walkReader.ts +63 -14
- package/src/WalkFormsAdapter/WalkFormsAdapter.test.ts +8 -12
- package/src/WalkFormsAdapter/WalkFormsAdapter.ts +38 -24
- package/src/WalkFormsAdapter/configSchema.ts +1 -1
- package/src/WalkFormsAdapter/formRows.test.ts +2 -2
- package/src/WalkFormsAdapter/formRows.ts +2 -2
- package/src/WalkTabixSyntenyAdapter/WalkTabixSyntenyAdapter.test.ts +4 -4
- package/src/WalkTabixSyntenyAdapter/WalkTabixSyntenyAdapter.ts +13 -4
- package/src/WalkTabixSyntenyAdapter/configSchema.ts +3 -2
- package/src/WalkTabixSyntenyAdapter/placementRecords.ts +1 -1
- package/src/WalkTabixSyntenyAdapter/walkLanes.ts +1 -5
- package/src/launchFromGraph/contributors.test.ts +53 -0
- package/src/launchFromGraph/contributors.ts +16 -3
- package/src/panSNTabix.ts +5 -5
- package/src/slotDefaults.test.ts +2 -2
- package/src/synteny/laneZoomNotice.test.ts +2 -2
- package/src/tabixRange.ts +1 -1
- package/src/version.ts +1 -1
- package/dist/chunks/AddTrackWorkflow-CNJLS2Z5.js +0 -2
- package/dist/chunks/AddTrackWorkflow-CNJLS2Z5.js.map +0 -7
- package/dist/chunks/GraphSettingsDialog-QK7RSQN4.js +0 -2
- package/dist/chunks/LinearGraphDisplay-BKJN7GDT.js +0 -2
- package/dist/chunks/RgfaTabixAdapter-M6EGHAPH.js +0 -2
- package/dist/chunks/RgfaTabixAdapter-M6EGHAPH.js.map +0 -7
- package/dist/chunks/WalkFormsAdapter-NWXXI7AK.js +0 -2
- package/dist/chunks/WalkFormsAdapter-NWXXI7AK.js.map +0 -7
- package/dist/chunks/WalkTabixSyntenyAdapter-ELABT623.js +0 -2
- package/dist/chunks/WalkTabixSyntenyAdapter-ELABT623.js.map +0 -7
- package/dist/chunks/chunk-EZPNVTU4.js +0 -3
- package/dist/chunks/chunk-EZPNVTU4.js.map +0 -7
- package/dist/chunks/chunk-ML2VXH7M.js +0 -9
- package/dist/chunks/chunk-ML2VXH7M.js.map +0 -7
- package/dist/chunks/chunk-MUKEETG2.js +0 -2
- package/dist/chunks/chunk-MUKEETG2.js.map +0 -7
- package/dist/chunks/chunk-NYBFFFFQ.js.map +0 -7
- package/dist/chunks/chunk-QVDH7CGO.js +0 -4
- package/dist/chunks/chunk-QVDH7CGO.js.map +0 -7
- package/dist/chunks/chunk-QYLXM2EJ.js +0 -8
- package/dist/chunks/chunk-QYLXM2EJ.js.map +0 -7
- package/dist/chunks/chunk-T5QLBT77.js +0 -2
- package/dist/chunks/chunk-TLSXQQBH.js +0 -2
- package/dist/chunks/chunk-TLSXQQBH.js.map +0 -7
- package/dist/chunks/chunk-WGTN5VTX.js +0 -4
- package/dist/chunks/chunk-WGTN5VTX.js.map +0 -7
- package/dist/chunks/chunk-X5CHZ2DT.js +0 -2
- package/dist/chunks/chunk-X5CHZ2DT.js.map +0 -7
- package/dist/chunks/chunk-XBSA77ZG.js +0 -2
- package/dist/chunks/chunk-XBSA77ZG.js.map +0 -7
- package/dist/chunks/chunk-YC6HAJTO.js +0 -2
- package/dist/chunks/chunk-YC6HAJTO.js.map +0 -7
- package/dist/chunks/chunk-ZT67PHLW.js +0 -2
- package/dist/chunks/chunk-ZT67PHLW.js.map +0 -7
- /package/dist/chunks/{ChooseSamplesDialog-5PTJ6ZDV.js.map → ChooseSamplesDialog-VWZXPW22.js.map} +0 -0
- /package/dist/chunks/{ChooseWalksDialog-DN6J7FGD.js.map → ChooseWalksDialog-UO6YQB2O.js.map} +0 -0
- /package/dist/chunks/{GraphGenomeView-DMC5QM6K.js.map → GraphGenomeView-2O2E42B4.js.map} +0 -0
- /package/dist/chunks/{GraphSettingsDialog-QK7RSQN4.js.map → GraphSettingsDialog-3OG5GCLT.js.map} +0 -0
- /package/dist/chunks/{HighlightColorDialog-SHTLKIUR.js.map → HighlightColorDialog-Y2CSK6AP.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-BKJN7GDT.js.map → LinearGraphDisplay-4EYMXR3M.js.map} +0 -0
- /package/dist/chunks/{MinigraphBubbleAdapter-2YICZ5GZ.js.map → MinigraphBubbleAdapter-XZJSCUDV.js.map} +0 -0
- /package/dist/chunks/{chunk-VN2AFDYR.js.map → chunk-76QQ3Q56.js.map} +0 -0
- /package/dist/chunks/{chunk-TAU773OE.js.map → chunk-EF34SRHG.js.map} +0 -0
- /package/dist/chunks/{chunk-5IZ6O334.js.map → chunk-NHCD6IZL.js.map} +0 -0
- /package/dist/chunks/{chunk-UQRQBSMW.js.map → chunk-P4IMSFPU.js.map} +0 -0
- /package/dist/chunks/{chunk-AQQHLLOF.js.map → chunk-SJPFWJFH.js.map} +0 -0
- /package/dist/chunks/{renderSvg-76L4L63F.js.map → renderSvg-YR7AUBB7.js.map} +0 -0
package/README.md
CHANGED
|
@@ -122,7 +122,7 @@ Supporting utility libraries
|
|
|
122
122
|
layout and drawing engine
|
|
123
123
|
- [@jbrowse/tubemap-core](https://github.com/GMOD/tubemap-core) (npm): tube map
|
|
124
124
|
layout
|
|
125
|
-
- [@
|
|
125
|
+
- [@gmod/gfa-tabix](https://github.com/GMOD/gfa-tabix-js) (npm): walk file
|
|
126
126
|
reader
|
|
127
127
|
- [@gmod/gbz-base](https://github.com/GMOD/gbz-base-js) (npm): `.gbz.db` reader
|
|
128
128
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as D,c as U,d as V,e as X,f as q,h as K}from"./chunk-YROUE32O.js";import{d as Q}from"./chunk-D3QZGLZ3.js";import{c as M,d as P}from"./chunk-WKD7ALOU.js";import{f as H}from"./chunk-U4ZQHJHX.js";import"./chunk-QNGSRFA7.js";import"./chunk-TMM73K4C.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-52Z3M7SW.js";import{b as R,h as A,j as v,n as x}from"./chunk-5L276I7O.js";import{j as r}from"./chunk-PCP5Y77D.js";import{B as j,C as z,D as J,G as h,a as E,f as I,g as d,o as B,t as N,u as _,v as O}from"./chunk-H42TSPVA.js";import{b as t,c as T,d as W}from"./chunk-DUU6T2I5.js";var i=JBrowseExports["@jbrowse/core/util/tss-react"],le=o=>i!=null&&o in Object(i)?i[o]:Object.assign(function(){throw new Error("This JBrowse does not provide '"+o+"' from '@jbrowse/core/util/tss-react' to plugins: GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse")},{jbrowseHostMissing:o});var Y=le("makeStyles"),de=i&&i.__esModule?i.default:i;async function Z(o,a,s){try{let{references:p}=await H(o,a,s).getHeader({signal:AbortSignal.timeout(D)});return p[0]}catch{return}}var pe=Y()(o=>({paper:{margin:o.spacing(),padding:o.spacing()},field:{marginTop:o.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),ce=["RgfaTabixAdapter","WalkTabixSyntenyAdapter","GbzBaseSyntenyAdapter","MinigraphBubbleAdapter"],me=W(function({model:a}){let{classes:s}=pe(),p=v(a),u=M(a),[n,$]=r("RgfaTabixAdapter"),[l,ee]=r(),[f,F]=r(),[G,te]=r(),g=n==="GbzBaseSyntenyAdapter",c=n==="WalkTabixSyntenyAdapter",[b,ae]=r(""),[S,oe]=r(""),[y,re]=r("Pangenome graph"),[C,k]=r(),[w,L]=r(!1);async function se(){if(!l||!a.assembly)return;k(void 0),L(!0);let{pluginManager:e}=A(a),[ne,ie]=await Promise.all([n==="RgfaTabixAdapter"?U(l,e):void 0,c&&!b.trim()?Z(l,f,e):void 0]);if(L(!1),!(!P(a)||!a.assembly))try{let m=y.trim();R({model:a,session:p,conf:K({choice:n,loc:l,indexLoc:f,readsLoc:g?G:void 0,manifest:ne,assembly:a.assembly,sample:b,haplotypes:c?Q(S):void 0,walkReference:ie,trackId:x({name:m}),name:m})})}catch(m){k(m)}}return T(j,{className:s.paper,children:[C?t(I,{error:C}):null,T(N,{children:[t(O,{children:"File type"}),t(J,{value:n,onChange:e=>{$(e.target.value),F(void 0),k(void 0)},children:ce.map(e=>t(_,{value:e,control:t(z,{}),label:V[e]},e))})]}),t(d,{location:l,name:X[n],rootModel:u,setLocation:ee}),t(d,{location:f,name:q[n],rootModel:u,setLocation:F}),g?t(d,{location:G,name:"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)",rootModel:u,setLocation:te}):null,t(h,{className:s.field,value:b,onChange:e=>{ae(e.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:g?"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample":c?"Optional. The PanSN sample this assembly is in the graph; blank takes it from the file name, GRCh38 in chr22.GRCh38.walks.gz":"Optional. The PanSN prefix the graph gives this assembly, e.g. GRCh38 for HPRC's GRCh38#0#chr1; leave blank when the graph's stable names are bare",placeholder:"GRCh38",fullWidth:!0}),c?t(h,{className:s.field,value:S,onChange:e=>{oe(e.target.value)},label:"Haplotypes",slotProps:{htmlInput:{"data-testid":"graph-haplotypes-input"}},helperText:"Optional. The haplotypes the track cuts for until you pick others in its menu, as PanSN names separated by commas (HG002#1, or HG002 for both); blank is every haplotype in the file",placeholder:"HG002, HG00733",fullWidth:!0}):null,t(h,{className:s.field,value:y,label:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:e=>{re(e.target.value)}}),t(E,{session:p,helperText:"Select assembly to add track to",selected:a.assembly,onChange:e=>{a.setAssembly(e)},fullWidth:!0}),t(B,{variant:"contained",className:s.submit,disabled:!l||!y.trim()||!a.assembly||w,onClick:()=>{se()},children:w?"Reading\u2026":"Submit"})]})}),Ae=me;export{Ae as default};
|
|
2
|
+
//# sourceMappingURL=AddTrackWorkflow-5I2MZDHJ.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["jbrowse-host:@jbrowse/core/util/tss-react", "../../src/GraphAddTrackWorkflow/walkReference.ts", "../../src/GraphAddTrackWorkflow/AddTrackWorkflow.tsx"],
|
|
4
|
+
"sourcesContent": ["const host = JBrowseExports[\"@jbrowse/core/util/tss-react\"]\nconst read = name =>\n host != null && name in Object(host)\n ? host[name]\n : Object.assign(\n function () {\n throw new Error(\"This JBrowse does not provide '\" + name + \"' from '\" + \"@jbrowse/core/util/tss-react\" + \"' to plugins: \" + \"GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse\")\n },\n { jbrowseHostMissing: name },\n )\nexport const cx = /* @__PURE__ */ read(\"cx\")\nexport const keyframes = /* @__PURE__ */ read(\"keyframes\")\nexport const makeStyles = /* @__PURE__ */ read(\"makeStyles\")\nexport default host && host.__esModule ? host.default : host", "import { FETCH_TIMEOUT_MS } from './graphManifest'\nimport { openWalkFile } from '../panSNTabix'\n\nimport type PluginManager from '@jbrowse/core/PluginManager'\nimport type { FileLocation } from '@jbrowse/core/util'\n\n// The reference sample a walk file's header names, which its file name only\n// suggests. Undefined for a header that is missing or unreadable, so the form\n// falls back to the file name.\nexport async function readWalkReference(\n loc: FileLocation,\n indexLoc: FileLocation | undefined,\n pluginManager?: PluginManager,\n) {\n try {\n const { references } = await openWalkFile(\n loc,\n indexLoc,\n pluginManager,\n ).getHeader({ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })\n return references[0]\n } catch {\n return undefined\n }\n}\n", "import { useState } from 'react'\n\nimport { AssemblySelector, ErrorMessage, FileSelector } from '@jbrowse/core/ui'\nimport {\n addTrackFromWidget,\n getEnv,\n getSession,\n makeTrackId,\n} from '@jbrowse/core/util'\nimport { makeStyles } from '@jbrowse/core/util/tss-react'\nimport { getRoot, isAlive } from '@jbrowse/mobx-state-tree'\nimport {\n Button,\n FormControl,\n FormControlLabel,\n FormLabel,\n Paper,\n Radio,\n RadioGroup,\n TextField,\n} from '@mui/material'\nimport { observer } from 'mobx-react'\n\nimport {\n GRAPH_FILE_FIELDS,\n GRAPH_FILE_LABELS,\n GRAPH_INDEX_FIELDS,\n buildTrackConfig,\n} from './buildTrackConfig'\nimport { readGraphManifest } from './graphManifest'\nimport { readWalkReference } from './walkReference'\nimport { parseHaplotypes } from '../graphTrackConfig'\n\nimport type { GraphFileChoice } from './buildTrackConfig'\nimport type {\n AbstractRootModel,\n AddTrackWorkflowModel,\n FileLocation,\n} from '@jbrowse/core/util'\n\nconst useStyles = makeStyles()(theme => ({\n paper: {\n margin: theme.spacing(),\n padding: theme.spacing(),\n },\n field: {\n marginTop: theme.spacing(2),\n },\n submit: {\n marginTop: 25,\n marginBottom: 100,\n display: 'block',\n },\n}))\n\nconst CHOICES: GraphFileChoice[] = [\n 'RgfaTabixAdapter',\n 'WalkTabixSyntenyAdapter',\n 'GbzBaseSyntenyAdapter',\n 'MinigraphBubbleAdapter',\n]\n\nconst GraphAddTrackWidget = observer(function GraphAddTrackWidget({\n model,\n}: {\n model: AddTrackWorkflowModel\n}) {\n const { classes } = useStyles()\n const session = getSession(model)\n const rootModel = getRoot<AbstractRootModel>(model)\n const [choice, setChoice] = useState<GraphFileChoice>('RgfaTabixAdapter')\n const [loc, setLoc] = useState<FileLocation>()\n const [indexLoc, setIndexLoc] = useState<FileLocation>()\n const [readsLoc, setReadsLoc] = useState<FileLocation>()\n const gbz = choice === 'GbzBaseSyntenyAdapter'\n const walks = choice === 'WalkTabixSyntenyAdapter'\n const [sample, setSample] = useState('')\n const [haplotypes, setHaplotypes] = useState('')\n const [trackName, setTrackName] = useState('Pangenome graph')\n const [error, setError] = useState<unknown>()\n const [submitting, setSubmitting] = useState(false)\n\n async function handleSubmit() {\n if (!loc || !model.assembly) {\n return\n }\n setError(undefined)\n setSubmitting(true)\n const { pluginManager } = getEnv(model)\n const [manifest, walkReference] = await Promise.all([\n choice === 'RgfaTabixAdapter'\n ? readGraphManifest(loc, pluginManager)\n : undefined,\n walks && !sample.trim()\n ? readWalkReference(loc, indexLoc, pluginManager)\n : undefined,\n ])\n setSubmitting(false)\n if (!isAlive(model) || !model.assembly) {\n return\n }\n try {\n const name = trackName.trim()\n addTrackFromWidget({\n model,\n session,\n conf: buildTrackConfig({\n choice,\n loc,\n indexLoc,\n readsLoc: gbz ? readsLoc : undefined,\n manifest,\n assembly: model.assembly,\n sample,\n haplotypes: walks ? parseHaplotypes(haplotypes) : undefined,\n walkReference,\n trackId: makeTrackId({ name }),\n name,\n }),\n })\n } catch (e) {\n setError(e)\n }\n }\n\n return (\n <Paper className={classes.paper}>\n {error ? <ErrorMessage error={error} /> : null}\n <FormControl>\n <FormLabel>File type</FormLabel>\n <RadioGroup\n value={choice}\n onChange={event => {\n setChoice(event.target.value as GraphFileChoice)\n setIndexLoc(undefined)\n setError(undefined)\n }}\n >\n {CHOICES.map(option => (\n <FormControlLabel\n key={option}\n value={option}\n control={<Radio />}\n label={GRAPH_FILE_LABELS[option]}\n />\n ))}\n </RadioGroup>\n </FormControl>\n <FileSelector\n location={loc}\n name={GRAPH_FILE_FIELDS[choice]}\n rootModel={rootModel}\n setLocation={setLoc}\n />\n <FileSelector\n location={indexLoc}\n name={GRAPH_INDEX_FIELDS[choice]}\n rootModel={rootModel}\n setLocation={setIndexLoc}\n />\n {gbz ? (\n <FileSelector\n location={readsLoc}\n name=\"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)\"\n rootModel={rootModel}\n setLocation={setReadsLoc}\n />\n ) : null}\n <TextField\n className={classes.field}\n value={sample}\n onChange={event => {\n setSample(event.target.value)\n }}\n label=\"Sample name in the graph\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-sample-input' } }}\n helperText={\n gbz\n ? \"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample\"\n : walks\n ? 'Optional. The PanSN sample this assembly is in the graph; blank takes it from the file name, GRCh38 in chr22.GRCh38.walks.gz'\n : \"Optional. The PanSN prefix the graph gives this assembly, e.g. GRCh38 for HPRC's GRCh38#0#chr1; leave blank when the graph's stable names are bare\"\n }\n placeholder=\"GRCh38\"\n fullWidth\n />\n {walks ? (\n <TextField\n className={classes.field}\n value={haplotypes}\n onChange={event => {\n setHaplotypes(event.target.value)\n }}\n label=\"Haplotypes\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-haplotypes-input' } }}\n helperText=\"Optional. The haplotypes the track cuts for until you pick others in its menu, as PanSN names separated by commas (HG002#1, or HG002 for both); blank is every haplotype in the file\"\n placeholder=\"HG002, HG00733\"\n fullWidth\n />\n ) : null}\n <TextField\n className={classes.field}\n value={trackName}\n label=\"Track name\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-track-name-input' } }}\n onChange={event => {\n setTrackName(event.target.value)\n }}\n />\n <AssemblySelector\n session={session}\n helperText=\"Select assembly to add track to\"\n selected={model.assembly}\n onChange={arg => {\n model.setAssembly(arg)\n }}\n fullWidth\n />\n <Button\n variant=\"contained\"\n className={classes.submit}\n disabled={!loc || !trackName.trim() || !model.assembly || submitting}\n onClick={() => {\n void handleSubmit()\n }}\n >\n {submitting ? 'Reading\u2026' : 'Submit'}\n </Button>\n </Paper>\n )\n})\n\nexport default GraphAddTrackWidget\n"],
|
|
5
|
+
"mappings": "2nBAAA,IAAMA,EAAO,eAAe,8BAA8B,EACpDC,GAAOC,GACXF,GAAQ,MAAQE,KAAQ,OAAOF,CAAI,EAC/BA,EAAKE,CAAI,EACT,OAAO,OACL,UAAY,CACV,MAAM,IAAI,MAAM,kCAAoCA,EAAO,8IAA6J,CAC1N,EACA,CAAE,mBAAoBA,CAAK,CAC7B,EAGC,IAAMC,EAA6BC,GAAK,YAAY,EACpDC,GAAQC,GAAQA,EAAK,WAAaA,EAAK,QAAUA,ECJxD,eAAsBC,EACpBC,EACAC,EACAC,EACA,CACA,GAAI,CACF,GAAM,CAAE,WAAAC,CAAW,EAAI,MAAMC,EAC3BJ,EACAC,EACAC,CACF,EAAE,UAAU,CAAE,OAAQ,YAAY,QAAQG,CAAgB,CAAE,CAAC,EAC7D,OAAOF,EAAW,CAAC,CACrB,MAAQ,CACN,MACF,CACF,CCgBA,IAAMG,GAAYC,EAAW,EAAEC,IAAU,CACvC,MAAO,CACL,OAAQA,EAAM,QAAQ,EACtB,QAASA,EAAM,QAAQ,CACzB,EACA,MAAO,CACL,UAAWA,EAAM,QAAQ,CAAC,CAC5B,EACA,OAAQ,CACN,UAAW,GACX,aAAc,IACd,QAAS,OACX,CACF,EAAE,EAEIC,GAA6B,CACjC,mBACA,0BACA,wBACA,wBACF,EAEMC,GAAsBC,EAAS,SAA6B,CAChE,MAAAC,CACF,EAEG,CACD,GAAM,CAAE,QAAAC,CAAQ,EAAIP,GAAU,EACxBQ,EAAUC,EAAWH,CAAK,EAC1BI,EAAYC,EAA2BL,CAAK,EAC5C,CAACM,EAAQC,CAAS,EAAIC,EAA0B,kBAAkB,EAClE,CAACC,EAAKC,EAAM,EAAIF,EAAuB,EACvC,CAACG,EAAUC,CAAW,EAAIJ,EAAuB,EACjD,CAACK,EAAUC,EAAW,EAAIN,EAAuB,EACjDO,EAAMT,IAAW,wBACjBU,EAAQV,IAAW,0BACnB,CAACW,EAAQC,EAAS,EAAIV,EAAS,EAAE,EACjC,CAACW,EAAYC,EAAa,EAAIZ,EAAS,EAAE,EACzC,CAACa,EAAWC,EAAY,EAAId,EAAS,iBAAiB,EACtD,CAACe,EAAOC,CAAQ,EAAIhB,EAAkB,EACtC,CAACiB,EAAYC,CAAa,EAAIlB,EAAS,EAAK,EAElD,eAAemB,IAAe,CAC5B,GAAI,CAAClB,GAAO,CAACT,EAAM,SACjB,OAEFwB,EAAS,MAAS,EAClBE,EAAc,EAAI,EAClB,GAAM,CAAE,cAAAE,CAAc,EAAIC,EAAO7B,CAAK,EAChC,CAAC8B,GAAUC,EAAa,EAAI,MAAM,QAAQ,IAAI,CAClDzB,IAAW,mBACP0B,EAAkBvB,EAAKmB,CAAa,EACpC,OACJZ,GAAS,CAACC,EAAO,KAAK,EAClBgB,EAAkBxB,EAAKE,EAAUiB,CAAa,EAC9C,MACN,CAAC,EAED,GADAF,EAAc,EAAK,EACf,GAACQ,EAAQlC,CAAK,GAAK,CAACA,EAAM,UAG9B,GAAI,CACF,IAAMmC,EAAOd,EAAU,KAAK,EAC5Be,EAAmB,CACjB,MAAApC,EACA,QAAAE,EACA,KAAMmC,EAAiB,CACrB,OAAA/B,EACA,IAAAG,EACA,SAAAE,EACA,SAAUI,EAAMF,EAAW,OAC3B,SAAAiB,GACA,SAAU9B,EAAM,SAChB,OAAAiB,EACA,WAAYD,EAAQsB,EAAgBnB,CAAU,EAAI,OAClD,cAAAY,GACA,QAASQ,EAAY,CAAE,KAAAJ,CAAK,CAAC,EAC7B,KAAAA,CACF,CAAC,CACH,CAAC,CACH,OAASK,EAAG,CACVhB,EAASgB,CAAC,CACZ,CACF,CAEA,OACEC,EAACC,EAAA,CAAM,UAAWzC,EAAQ,MACvB,UAAAsB,EAAQoB,EAACC,EAAA,CAAa,MAAOrB,EAAO,EAAK,KAC1CkB,EAACI,EAAA,CACC,UAAAF,EAACG,EAAA,CAAU,qBAAS,EACpBH,EAACI,EAAA,CACC,MAAOzC,EACP,SAAU0C,GAAS,CACjBzC,EAAUyC,EAAM,OAAO,KAAwB,EAC/CpC,EAAY,MAAS,EACrBY,EAAS,MAAS,CACpB,EAEC,SAAA3B,GAAQ,IAAIoD,GACXN,EAACO,EAAA,CAEC,MAAOD,EACP,QAASN,EAACQ,EAAA,EAAM,EAChB,MAAOC,EAAkBH,CAAM,GAH1BA,CAIP,CACD,EACH,GACF,EACAN,EAACU,EAAA,CACC,SAAU5C,EACV,KAAM6C,EAAkBhD,CAAM,EAC9B,UAAWF,EACX,YAAaM,GACf,EACAiC,EAACU,EAAA,CACC,SAAU1C,EACV,KAAM4C,EAAmBjD,CAAM,EAC/B,UAAWF,EACX,YAAaQ,EACf,EACCG,EACC4B,EAACU,EAAA,CACC,SAAUxC,EACV,KAAK,4FACL,UAAWT,EACX,YAAaU,GACf,EACE,KACJ6B,EAACa,EAAA,CACC,UAAWvD,EAAQ,MACnB,MAAOgB,EACP,SAAU+B,GAAS,CACjB9B,GAAU8B,EAAM,OAAO,KAAK,CAC9B,EACA,MAAM,2BACN,UAAW,CAAE,UAAW,CAAE,cAAe,oBAAqB,CAAE,EAChE,WACEjC,EACI,mKACAC,EACE,+HACA,qJAER,YAAY,SACZ,UAAS,GACX,EACCA,EACC2B,EAACa,EAAA,CACC,UAAWvD,EAAQ,MACnB,MAAOkB,EACP,SAAU6B,GAAS,CACjB5B,GAAc4B,EAAM,OAAO,KAAK,CAClC,EACA,MAAM,aACN,UAAW,CAAE,UAAW,CAAE,cAAe,wBAAyB,CAAE,EACpE,WAAW,uLACX,YAAY,iBACZ,UAAS,GACX,EACE,KACJL,EAACa,EAAA,CACC,UAAWvD,EAAQ,MACnB,MAAOoB,EACP,MAAM,aACN,UAAW,CAAE,UAAW,CAAE,cAAe,wBAAyB,CAAE,EACpE,SAAU2B,GAAS,CACjB1B,GAAa0B,EAAM,OAAO,KAAK,CACjC,EACF,EACAL,EAACc,EAAA,CACC,QAASvD,EACT,WAAW,kCACX,SAAUF,EAAM,SAChB,SAAU0D,GAAO,CACf1D,EAAM,YAAY0D,CAAG,CACvB,EACA,UAAS,GACX,EACAf,EAACgB,EAAA,CACC,QAAQ,YACR,UAAW1D,EAAQ,OACnB,SAAU,CAACQ,GAAO,CAACY,EAAU,KAAK,GAAK,CAACrB,EAAM,UAAYyB,EAC1D,QAAS,IAAM,CACRE,GAAa,CACpB,EAEC,SAAAF,EAAa,gBAAa,SAC7B,GACF,CAEJ,CAAC,EAEMmC,GAAQ9D",
|
|
6
|
+
"names": ["host", "read", "name", "makeStyles", "read", "tss_react_default", "host", "readWalkReference", "loc", "indexLoc", "pluginManager", "references", "openWalkFile", "FETCH_TIMEOUT_MS", "useStyles", "makeStyles", "theme", "CHOICES", "GraphAddTrackWidget", "observer", "model", "classes", "session", "getSession", "rootModel", "getRoot", "choice", "setChoice", "useState", "loc", "setLoc", "indexLoc", "setIndexLoc", "readsLoc", "setReadsLoc", "gbz", "walks", "sample", "setSample", "haplotypes", "setHaplotypes", "trackName", "setTrackName", "error", "setError", "submitting", "setSubmitting", "handleSubmit", "pluginManager", "getEnv", "manifest", "walkReference", "readGraphManifest", "readWalkReference", "isAlive", "name", "addTrackFromWidget", "buildTrackConfig", "parseHaplotypes", "makeTrackId", "e", "jsxs", "Paper", "jsx", "ErrorMessage", "FormControl", "FormLabel", "RadioGroup", "event", "option", "FormControlLabel", "Radio", "GRAPH_FILE_LABELS", "FileSelector", "GRAPH_FILE_FIELDS", "GRAPH_INDEX_FIELDS", "TextField", "AssemblySelector", "arg", "Button", "AddTrackWorkflow_default"]
|
|
7
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as i}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=ChooseSamplesDialog-
|
|
1
|
+
import{a as i}from"./chunk-NHCD6IZL.js";import"./chunk-PCP5Y77D.js";import"./chunk-H42TSPVA.js";import{b as a,d as s}from"./chunk-DUU6T2I5.js";var t=s(function({model:o,onClose:p}){let{samples:l}=o.walkRowSampleChoices;return a(i,{title:"Choose samples",label:"Samples",testId:"graph-choose-samples",caption:`${l.length.toLocaleString()} samples in this cut. Their walks show in pairs, in the order picked.`,options:l,initial:o.walkRowSamples??[],confirmLabel:e=>e.length>0?"Show these samples":"Show every sample",onPick:e=>{o.setWalkRowSamples(e.length>0?e:void 0)},onClose:p})}),h=t;export{h as default};
|
|
2
|
+
//# sourceMappingURL=ChooseSamplesDialog-VWZXPW22.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as t}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=ChooseWalksDialog-
|
|
1
|
+
import{a as t}from"./chunk-NHCD6IZL.js";import"./chunk-PCP5Y77D.js";import"./chunk-H42TSPVA.js";import{b as l,d as i}from"./chunk-DUU6T2I5.js";var h=i(function({model:o,onClose:s}){let{walkChoices:a}=o;return l(t,{title:"Choose haplotypes",label:"Haplotypes",testId:"graph-choose-walks",caption:`${a.length.toLocaleString()} haplotypes in this cut. The ones picked are highlighted in this order, and the rest fades.`,options:a.map(e=>e.name),initial:o.walkLayers.map(e=>e.walk),optionLabel:e=>o.walkLabel(e),confirmLabel:e=>e.length>0?"Highlight these":"Clear highlights",onPick:e=>{o.liftAmongChoices(e)},onClose:s})}),k=h;export{k as default};
|
|
2
|
+
//# sourceMappingURL=ChooseWalksDialog-UO6YQB2O.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as fe,b as $,c as ke,d as V,e as ee,f as pn,g as Xe,h as Ye,i as un,j as gn,k as Fe,l as Te,m as Ne,n as wn,o as mn,p as yn,q as bn,r as xn,s as Rn,t as $n,u as Hn,v as Cn}from"./chunk-TAU773OE.js";import{a as Nn}from"./chunk-TLSXQQBH.js";import{a as vn}from"./chunk-V55TK2NP.js";import"./chunk-JM4W4PKP.js";import{a as bs,b as Ln,c as Mn,d as Ht}from"./chunk-UQRQBSMW.js";import{a as In,g as kn,h as Lt,i as Mt}from"./chunk-WGTN5VTX.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZT67PHLW.js";import"./chunk-RSCG3J6K.js";import{W as En,c as Sn}from"./chunk-MUKEETG2.js";import"./chunk-FQI75MV6.js";import{b as _e,d as An}from"./chunk-NYBFFFFQ.js";import{k as Pn}from"./chunk-QYLXM2EJ.js";import"./chunk-TMM73K4C.js";import{a as $e}from"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as Ke,h as dn,i as fn,j as ln}from"./chunk-EGZZ3ADM.js";import{a as Rt,g as Ae,h as Re,i as $t}from"./chunk-HE5BVBEF.js";import{e as hn,q as At}from"./chunk-5L276I7O.js";var ze=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},On=255,xs=256,Je=class{source;sigma;threshold;constructor(e,t){this.source=new ze(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<On?Math.floor(xs/this.sigma):0}next(){if(this.sigma>=On){let s=this.source.int(),r=this.source.int();return s===void 0||r===void 0?void 0:{value:s,len:r+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let s=this.source.int();if(s===void 0)return;n+=s}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Bn(a){let e=new ze(a),t=e.int();if(t===void 0||t===0)return[];let n=[],s=0;for(let r=0;r<t;r++){let o=e.int(),i=e.int();if(o===void 0||i===void 0)throw new Error("GBWT edge list ends early");s+=o,n.push({node:s,offset:i})}return n}var et=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Je(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(s=>s.offset),n=0;for(let s of this.runs()){let r=this.edge(s.value),o=t[s.value];if(n+s.len>e)return r.node===0?void 0:{node:r.node,offset:o+(e-n)};t[s.value]=o+s.len,n+=s.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let s=t+n>>1,r=this.edges[s];if(r.node===e)return s;r.node<e?t=s+1:n=s}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let s=0;for(let r of this.runs())if(s+=r.len,r.value===t&&(n+=r.len,n>e.offset))return s-(n-e.offset)}predecessorAt(e){let t=this.edges.map(s=>({node:s.node===0?0:ee(s.node),count:0}));for(let s of this.runs()){let r=t[s.value];r&&(r.count+=s.len)}for(let s=1;s<t.length;s++){let r=t[s-1],o=t[s];$(r.node)===$(o.node)&&(t[s-1]=o,t[s]=r)}let n=0;for(let s of t)if(n+=s.count,n>e)return s.node===0?void 0:s.node}decompressArrays(){let e=this.edges.map(o=>o.offset),t=0;for(let o of this.runs())t+=o.len;let n=new Int32Array(t),s=new Int32Array(t),r=0;for(let o of this.runs()){let i=this.edge(o.value),c=e[o.value];for(let d=0;d<o.len;d++)n[r]=i.node,s[r]=c,c+=1,r+=1;e[o.value]=c}return{nodes:n,offsets:s}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let s=this.edge(n.value);for(let r=0;r<n.len;r++)t.push({node:s.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var Ss=Uint32Array.from([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]),we=(a,e)=>a>>>e|a<<32-e;function Fn(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let d=0;d<e;d++){for(let S=0;S<16;S++)o[S]=n.getUint32(d*64+S*4);for(let S=16;S<64;S++){let I=o[S-15],N=o[S-2],y=we(I,7)^we(I,18)^I>>>3,E=we(N,17)^we(N,19)^N>>>10;o[S]=o[S-16]+y+o[S-7]+E}let h=r[0],f=r[1],p=r[2],w=r[3],u=r[4],l=r[5],b=r[6],x=r[7];for(let S=0;S<64;S++){let I=we(u,6)^we(u,11)^we(u,25),N=u&l^~u&b,y=x+I+N+Ss[S]+o[S]|0,E=we(h,2)^we(h,13)^we(h,22),R=h&f^h&p^f&p;x=b,b=l,l=u,u=w+y|0,w=p,p=f,f=h,h=y+E+R|0}[h,f,p,w,u,l,b,x].forEach((S,I)=>{r[I]=r[I]+S})}let i=new Uint8Array(32),c=new DataView(i.buffer);for(let d=0;d<8;d++)c.setUint32(d*4,r[d]);return i}function Tn(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[r,o]=s;if(s.length!==2||!r||!o)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(r);i||(i=new Set,t.set(r,i)),i.add(o)}return t}function qn(a){return{name:a.get("pggname"),subgraph:Tn(a.get("subgraph"),"subgraph"),translation:Tn(a.get("translation"),"translation")}}function _n(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let r of n)s.add(r)}}function Dn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),_n(t.subgraph,e.subgraph),_n(t.translation,e.translation)),t}function zn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function Gn(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of zn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of zn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function jn(a){let e=a.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of a)t.set(o,n),n+=o.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Fn(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Is="_gbwt_ref";function pe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Es=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,ks=/^([^#]+?)(?:\[\d+-\d+\])?$/;function vs(a){let e=Es.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=ks.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Le(a){return typeof a=="string"?vs(a):a}function Me(a,e){return{sample:a.sample??Is,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var Ps=4096;function Ot(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ps?n[1]=t:e.push([t,t])}return e}var Ns=32768,Un={mostChosenPaths:32},Ct=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},oe=class extends Error{};function tt(a,e,t,n){return a==="forward"?e+t:e-n}function Wn(a,e,t,n){return a==="forward"?e-n:e+t}function Qn(a){return Ne(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function qe(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Vn(a){let{db:e,records:t,signal:n}=a,s=performance.now(),r=()=>{let m=performance.now(),k=m-s;return s=m,k},o={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(m,k)=>{let A=`${m}: ${k}`;o.walks[A]=(o.walks[A]??0)+1},c=await e.haplotypeSampleInterval()??4096,d=new Map,h=async m=>{let k=t.get(m)??d.get(m);if(k)return k;let A=await e.getRecord(m);if(o.graphFetches+=1,!A)throw new Error(`Node record ${m} is missing from the database`);return d.set(m,A),A},f=m=>t.get(m).sequenceLen,p=await e.pathsByHandle(),w=m=>{let k=p.get(m);return k!==void 0&&a.keep(k.name)},u=[],l=new Ct,b=new Map,x=new Set,S=new Set,I=async m=>{let k=(await h(m.node)).gbwt().lf(m.offset);return k===void 0||k.node===0?void 0:k},N=async(m,k)=>{let A=(await h(ee(m.node))).gbwt().predecessorAt(m.offset);if(A===void 0||k!==void 0&&!k.has(A))return;let L=(await h(A)).gbwt().offsetTo(m);if(L===void 0)throw new Error(`No offset in ${A} leads to ${m.node}:${m.offset}`);return{node:A,offset:L}},y=(m,k,A,L)=>{let B=A.map(U=>U.pos.node),j=A.map(U=>U.pos.offset),Y=0;for(let U of B)Y+=f(U);let C=k==="forward"?A[0].left:A[A.length-1].left,M=u.length;u.push({pathHandle:m,orientation:k,handles:B,offsets:j,len:Y,hapStart:C,hapEnd:C+Y,canonical:Ne(B[0],B[B.length-1]),source:L});for(let U of A)l.set(U.pos,M);let Q=b.get(m);return Q?Q.push(M):b.set(m,[M]),M},E=async(m,k,A,L)=>{let B=[],j=m;for(;;){n?.throwIfAborted();let C=await N(j.pos,t);if(!C)break;j={pos:C,left:Wn(A,j.left,f(j.pos.node),f(C.node))},B.push(j)}B.reverse();let Y=[m];for(j=m;;){n?.throwIfAborted();let C=await I(j.pos);if(!C||!t.has(C.node))break;j={pos:C,left:tt(A,j.left,f(j.pos.node),f(C.node))},Y.push(j)}return y(k,A,[...B,...Y],L)},R=async(m,k,A,L)=>u[l.get(m.pos)??await E(m,k,A,L)],F=m=>{let k=m.handles[m.handles.length-1];return{pos:{node:k,offset:m.offsets[m.offsets.length-1]},left:m.orientation==="forward"?m.hapEnd-f(k):m.hapStart}},T=m=>{let k=m.handles[0];return{pos:{node:k,offset:m.offsets[0]},left:m.orientation==="forward"?m.hapStart:m.hapEnd-f(k)}},D=await E({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),O=u[D],H=()=>{if(o.fallback!==void 0)return{reference:O,pieces:[],stats:o};let m=new Map;u.forEach((A,L)=>{L!==D&&m.set(qe(A),[...m.get(qe(A))??[],A])});let k=[];for(let A of m.values()){let L=new Set;for(let B of A)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),k.push(B),o.sources[B.source]+=1)}return o.sources.reference=1,o.pieces=k.length+1,{reference:O,pieces:k,stats:o}},v=async(m,k)=>{let A=k?x:S,L=k?S:x,B=m;for(;;){if(A.has(B))return;A.add(B);let j=u[B],Y=k?F(j):T(j),C=0,M;for(;M===void 0;){n?.throwIfAborted();let Q=k?await I(Y.pos):await N(Y.pos);if(!Q){M="endmarker";break}let U=(await h(Y.pos.node)).sequenceLen,ge=(await h(Q.node)).sequenceLen,se=k?tt(j.orientation,Y.left,U,ge):Wn(j.orientation,Y.left,U,ge);if(t.has(Q.node)){let J=l.get(Q);J===void 0?(B=await E({pos:Q,left:se},j.pathHandle,j.orientation,"chain"),L.add(B),M="landed"):(L.add(J),M="merge")}else C>Ns?M="bound":(C+=ge,Y={pos:Q,left:se})}if(i("chain",M),M!=="landed")return}},G=async m=>{if(a.context>m.context)throw new oe(`the context of ${a.context} bp exceeds the ${m.context} bp the haplotype index's stray rows cover`);let k=o.spacing;if(k===void 0)throw new oe("the haplotype index has no anchors");let{bin:A,bound:L}=m,{fills:B,inserted:j}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new oe("the haplotype index's stray rows cover contained snarls only");for(let g of B){if(g.inserted>0&&g.low===g.high)throw new oe(`the haplotype index's stray rows leave out the snarl bounded by node ${g.low} at both ends`);if(g.inserted>0&&(m.snarlNodes===void 0||g.nodes>m.snarlNodes))throw new oe(m.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${g.nodes} nodes exceeds the ${m.snarlNodes} the haplotype index's stray rows cover`)}let Y=Math.floor(a.window.start/A),C=Math.floor((a.window.end-1)/A),M=Y*A,Q=(C+1)*A,U=new Map,ge=async(g,P)=>{let q=await e.haplotypeAnchorsBetween(a.referenceHandle,g*k,P*k);for(let _ of q)U.set(_.anchorOffset/k,_)},se=Math.max(0,Math.floor((M-L)/k)-1),J=Math.ceil((Q+L)/k)+1,[{listed:Ve,strays:ie}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,Y,C),ge(se,J)]);for(let g of t.keys()){let P=$(g);if(!V(g)&&!Ve(P)&&!j.has(P))throw new oe(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}o.scans=Ot([...t.keys()].sort((g,P)=>g-P));let he=Promise.all(o.scans.map(([g,P])=>e.haplotypeSamplesInRange(g,P)));for(he.catch(()=>{});se>0&&(U.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=M-L;)se-=1,await ge(se,se);for(;U.has(J)&&U.get(J).pathOffset<=Q+L;)J+=1,await ge(J,J);let ue=[...U.keys()].sort((g,P)=>g-P),be=U.get(ue[0]??-1);if(!be)throw new oe("the haplotype index has no anchors on this path");let de=g=>U.get(g).pathOffset,Ce=new Map;for(let g of ue){let P=$(U.get(g).node);Ce.set(P,[...Ce.get(P)??[],g])}let vt=[...Ce.keys()],Xt=vt.map(g=>U.get(Ce.get(g)[0]).visits);if(!Xt[vt.indexOf($(be.node))].some(g=>g.pathHandle===a.referenceHandle&&g.orientation==="forward"&&g.pathOffset===be.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${be.pathOffset} (node ${$(be.node)}); it does not match this graph`);let Yt=ue.filter(g=>de(g)<=a.window.start),gs=ue.filter(g=>de(g)>=a.window.end);o.anchors=[de(Yt[Yt.length-1]??ue[0]),de(gs[0]??ue[ue.length-1])],o.anchorsRead=ue.length;let Pt=new Map,Jt=new Set;if(vt.forEach((g,P)=>{let q=Ce.get(g),_=q.length===1?q[0]:void 0;for(let z of Xt[P])Jt.add(z.pathHandle),z.orientation==="forward"&&w(z.pathHandle)&&Pt.set(z.pathHandle,[...Pt.get(z.pathHandle)??[],{k:_,row:z}])}),o.chosenPaths=[...Jt].filter(w).length,o.chosenPaths>Un.mostChosenPaths)throw new oe(`${o.chosenPaths} chosen paths pass the anchors, more than ${Un.mostChosenPaths}`);let Ze=[],Ee=Number.POSITIVE_INFINITY,xe=0;for(let[g,P]of Pt){P.sort((q,_)=>q.row.pathOffset-_.row.pathOffset);for(let q=0;q+1<P.length;q++){let _=P[q],z=P[q+1];if(_.k===void 0||z.k===void 0||Math.abs(_.k-z.k)!==1)continue;let[K,te]=de(_.k)<=de(z.k)?[_,z]:[z,_],ne=de(K.k),re=de(te.k);ne<Q&&re>=M?(Ze.push({pathHandle:g,from:_.row,to:z.row}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,re+L)):ne>=Q&&ne-Q<=L?(Ze.push({pathHandle:g,from:K.row,to:void 0}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,ne+L)):re<M&&M-re<=L&&(Ze.push({pathHandle:g,from:te.row,to:void 0}),Ee=Math.min(Ee,re-L),xe=Math.max(xe,re+L))}}let ws=new Set(B.map(g=>`${g.low}:${g.high}`)),ms=ie.filter(g=>w(g.pathHandle)&&(g.snarl===void 0||ws.has(`${g.snarl[0]}:${g.snarl[1]}`))).sort((g,P)=>g.pathHandle-P.pathHandle||g.pathStart-P.pathStart);o.strays={bins:C-Y+1,rows:ie.length,walked:0,outsideBp:0},xe>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ee),xe+1),o.ms.scan=r();let en=8*k+2*(a.window.end-a.window.start),tn=o.strays,Oe=0,nn=g=>{if(tn.outsideBp+=g,Oe+=g,Oe>en)throw new oe(`a walk of a chosen path near the window went past its cap of ${en} bp`)},Nt=new Map,sn=(g,P,q)=>(Nt.get(g)??[]).some(([_,z])=>_<=P&&q<z),rn=(g,P,q)=>{Nt.set(g,[...Nt.get(g)??[],[P,q]])},on=async(g,P,q,_,z)=>{let K=P,te=q,ne=te;for(;K&&te<=_;){n?.throwIfAborted();let re;if(t.has(K.node)){let Be=await R({pos:K,left:te},g,"forward",z),cn=F(Be);K=cn.pos,te=cn.left,re=f(K.node),ne=Math.max(ne,Be.hapEnd)}else re=(await h(K.node)).sequenceLen,nn(re),ne=Math.max(ne,te+re);K=await I(K),te+=re}return ne},ys=async(g,P,q,_)=>{let z={pos:P,left:q},K=q;for(;z.left>_;){n?.throwIfAborted();let te=await N(z.pos);if(!te)break;let ne=(await h(te.node)).sequenceLen,re=z.left-ne;if(t.has(te.node)){let Be=await R({pos:te,left:re},g,"forward","section");z=T(Be),K=Math.min(K,Be.hapStart)}else nn(ne),z={pos:te,left:re},K=Math.min(K,re)}return K};for(let{pathHandle:g,from:P,to:q}of Ze){let _=P.pathOffset,z=(q??P).pathOffset+L;if(sn(g,_-L,z))continue;let K={node:P.node,offset:P.offset};Oe=0;let te=await on(g,K,_,z,"section");Oe=0;let ne=await ys(g,K,_,_-L);rn(g,Math.min(ne,_-L),Math.max(te,z+1)),i(q?"section":"visit",q?"past the far anchor":"bound")}for(let g of ms){if(sn(g.pathHandle,g.pathStart,g.pathEnd))continue;Oe=0;let P=await on(g.pathHandle,{node:g.node,offset:g.offset},g.pathStart,g.pathEnd,"stray");rn(g.pathHandle,g.pathStart,Math.max(P,g.pathEnd+1)),tn.walked+=1}o.ms.walks=r();let an=[];for(let g of await he)for(let P of g)if(o.scanRows+=1,t.has(P.node)&&w(P.pathHandle)){if(!(b.get(P.pathHandle)??[]).some(q=>{let _=u[q];return _.hapStart<=P.pathOffset&&P.pathOffset<_.hapEnd}))throw new oe(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&an.push(P)}for(let g of an)await R({pos:{node:g.node,offset:g.offset},left:g.pathOffset},g.pathHandle,"reverse","twin");o.ms.check=r()},X=async()=>{let m=new Map,k=C=>{let M=qe(C),Q=m.get(M);Q?Q.add(C.orientation):m.set(M,new Set([C.orientation]))},A=0,L=()=>{for(;A<u.length;A++)k(u[A])};L();let B=C=>(m.get(qe(C))?.size??0)>1,j=2*c,Y=(C,M)=>M===D?w(a.referenceHandle)&&Qn(C):!C.canonical||Qn(C);for(let C=0;C<u.length;C++){let M=u[C];if(B(M)||!Y(M,C))continue;o.twins.tried+=1;let Q=M.orientation==="forward"?"reverse":"forward",U=F(M),ge=0,se;for(;!se&&ge<=j;){n?.throwIfAborted();let ie=await I(U.pos);if(!ie)break;let he=(await h(ie.node)).sequenceLen,ue=tt(M.orientation,U.left,(await h(U.pos.node)).sequenceLen,he),be=ee(ie.node);se=(await e.haplotypeSamplesInRange(be,be)).find(de=>de.pathHandle===M.pathHandle&&de.orientation===Q&&de.pathOffset===ue),ge+=he,U={pos:ie,left:ue}}let J=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},Ve=0;for(;J&&!B(M)&&Ve<=j+M.len;){if(n?.throwIfAborted(),t.has(J.pos.node)){let ie=await R(J,M.pathHandle,Q,"twin"),he=u.indexOf(ie);await v(he,!0),await v(he,!1),L(),J=F(ie)}if(!B(M)){let ie=(await h(J.pos.node)).sequenceLen;Ve+=ie;let he=await I(J.pos);J=he?{pos:he,left:tt(Q,J.left,ie,(await h(he.node)).sequenceLen)}:void 0}}if(L(),!B(M))throw new oe(`piece ${qe(M)} was found in one orientation where extractPaths keeps the other`);o.twins.found+=1}o.ms.twins=r()};try{let m=await e.haplotypeStrayOptions();if(m===void 0)throw new oe("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await G(m),await X()}catch(m){if(!(m instanceof oe))throw m;o.fallback=m.message}return H()}function Zn(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var ae=class extends Error{name="SubgraphLimitError";limit;windowBp;walkedBp;constructor(e,t){super(t===void 0?`Subgraph size limit of ${e} nodes exceeded`:`Subgraph size limit of ${e} nodes exceeded ${t.walkedBp} bp into a ${t.windowBp} bp window`),this.limit=e,this.windowBp=t?.windowBp,this.walkedBp=t?.walkedBp}};function Bt(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var Ge=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let r=s.length-1;for(;r>0;){let o=r-1>>1;if(Bt(s[r],s[o]))[s[r],s[o]]=[s[o],s[r]],r=o;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let r=2*s+1,o=r+1,i=s;if(r<e.length&&Bt(e[r],e[i])&&(i=r),o<e.length&&Bt(e[o],e[i])&&(i=o),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function As(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],r)=>{e[r]=n,t[r]=s}),{pathAt:e,refAt:t,count:a.length}}function Rs(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ve(a){return`${a.node}:${a.offset}`}function De(a){return a.map(e=>ee(e)).reverse()}function $s(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Ls(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],r=n.edits.map(([d,h])=>[d,h]);Xn(r,t.insertion,t.deletion);for(let[d,h]of s.edits)Z(r,d,h);let o=a.identity.walkForward,[i,c]=o?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:r,weight:void 0,path:[...i.path,...c.path],start:i.start,pieces:[...i.pieces,...c.pieces],soloAligned:[...i.soloAligned,...c.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:o}}}function Ms(a,e,t){if(a.some(o=>o.weight!==void 0))return a;let n=new Map;a.forEach((o,i)=>{if(o.identity){let c=n.get(o.identity.pathHandle);c?c.push(i):n.set(o.identity.pathHandle,[i])}});let s=new Map,r=new Set;for(let o of n.values()){o.sort((h,f)=>a[h].identity.hapStart-a[f].identity.hapStart);let i=o[0],c=a[i],d=[];for(let h of o.slice(1)){let f=a[h],p=d.length===0?$s(c,f):void 0;if(p){c=Ls(c,f,p),r.add(h);continue}if(!e(f)){d.push(h);continue}let w=e(c)?t([c,...d.map(u=>a[u]),f]):void 0;if(w){c=w;for(let u of[...d,h])r.add(u)}else s.set(i,c),i=h,c=f;d=[]}s.set(i,c)}return a.flatMap((o,i)=>r.has(i)?[]:[s.get(i)??o])}function nt(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Hs=32768;function Cs(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Hs?s[1]=n:t.push([n,n])}return t}var je=class a{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new a(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(fe(e,"forward"))}hasHandle(e){return this.records.has(e)}record(e){let t=this.records.get(e);if(!t)throw new Error(`Subgraph has no record for handle ${e}`);return t}sortedHandles(){return[...this.records.keys()].sort((e,t)=>e-t)}async addNode(e){if(this.signal?.throwIfAborted(),this.limit!==void 0&&this.nodeCount>=this.limit)throw new ae(this.limit);let t=await this.db.getRecord(fe(e,"forward")),n=await this.db.getRecord(fe(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${pe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let r=n,o=s;for(;;){await this.ensureNode($(o.node));let i=this.record(o.node);if(r+i.sequenceLen>t)return{position:{seqOffset:t,handle:o.node,nodeOffset:t-r,gbwtOffset:o.offset},name:e.name,handle:e.handle};r+=i.sequenceLen;let c=i.gbwt().lf(o.offset);if(!c)throw new Error(`The fragment of ${pe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);o=c}}async aroundPosition(e,t,n){let s=$(e);await this.ensureNode(s);let r=this.record(e),o=ke(e),i=new Ge;return i.push(t,s,Xe(o)),i.push(r.sequenceLen-t-1,s,Ye(o)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,r]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&r){let o=s.pos.node,i=r.pos.node;if(!await this.db.prefetchRecords([[Math.min(o,i),Math.max(o,i)+1]])){let d=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Cs(d.map(h=>h.pos.node)).map(([h,f])=>[h,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof ae&&s.windowBp===void 0?new ae(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},r=e.nodeOffset,o=t,i=new Ge;for(;;){let c=$(s.node),d=ke(s.node);this.walkedBp=t-o,await this.ensureNode(c);let h=this.record(s.node);if(r>=h.sequenceLen)throw new Error(`Offset ${r} in node ${c} of length ${h.sequenceLen}`);i.push(r,c,Xe(d));let f=h.sequenceLen-r;if(o<=f){i.push(o===f?0:f-o-1,c,Ye(d));break}i.push(0,c,Ye(d));let p=h.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,r=0,o-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new Ge;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let o of this.records.keys())s.add($(o));let r=0;for(;e.size>0;){let[o,i,c]=e.pop(),d=`${i}:${c}`;if(n.has(d))continue;n.add(d),s.delete(i),this.hasNode(i)||(await this.addNode(i),r+=1);let h=pn(c);if(!n.has(`${i}:${h}`)){let w=this.record(fe(i,un(c))),u=o+w.sequenceLen-1;u<=t&&e.push(u,i,h)}let f=this.record(fe(i,gn(c))),p=o+1;if(p<=t)for(let w of f.successors()){let u=$(w),l=Xe(ke(w));n.has(`${u}:${l}`)||e.push(p,u,l)}}for(let o of s)this.records.delete(fe(o,"forward")),this.records.delete(fe(o,"reverse"));return{inserted:r,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([$(e),$(t)]),r=[];for(;n.length>0;){let o=n.pop(),i=$(o);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let c of this.record(o).successors()){let d=$(c);s.has(d)||(n.push(c,ee(c)),s.add(d))}}return{inserted:r,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:r,nodes:o}=await this.fillBetween(n,s),i=$(n),c=$(s);this.snarlFills.push({low:Math.min(i,c),high:Math.max(i,c),nodes:o,inserted:r.length});for(let d of r)this.snarlNodes.add(d);t+=r.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let r=this.record(s),o=r.next;o!==void 0&&(n=!0,this.hasHandle(o)?Fe(s,o)&&t.push([s,o]):e==="overlapping"&&this.isSnarlEntryInSubgraph(r)&&t.push([s,o]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let r=t.get(n);if(!r){if(r=await this.db.getRecord(n),e?.(),!r)throw new Error(`Node record ${n} is missing from the database`);t.set(n,r)}return r}}async findCoveringSnarl(){let e=this.recordReader(),t=async c=>{let d=c.successors(),h=d[0];return h===void 0?!1:d.length>1||(await e(ee(h))).successors().length>1},n=async c=>{let d=await e(ee(c));return d.next!==void 0?await t(d)?{kind:"snarl-exit",snarl:[ee(c),d.next]}:{kind:"chain"}:(await e(c)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,r=this.sortedHandles().flatMap(c=>this.record(c).successors()),o,i=!1;for(;!i&&r.length>0;){let c=r.shift(),d=$(c);if(!this.hasHandle(c)&&!s.has(d)){s.add(d);let h=await n(c);if(h.kind==="snarl-exit")o=h.snarl,i=!0;else if(h.kind==="chain")i=!0;else for(let f of["forward","reverse"])r.push(...(await e(fe(d,f))).successors())}}return o}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),r=s.length,o=new Map;s.forEach((y,E)=>o.set(y,E));let i=new Int32Array(r+1),c=new Int32Array(r),d=[];for(let y=0;y<r;y++){let E=this.record(s[y]),R=E.gbwt().decompressArrays();c[y]=E.sequenceLen,d.push(R),i[y+1]=i[y]+R.nodes.length}let h=i[r],f=new Int32Array(h),p=new Int32Array(h),w=new Uint8Array(h);for(let y=0;y<r;y++){let E=d[y];f.set(E.nodes,i[y]),p.set(E.offsets,i[y])}d.length=0;for(let y=0;y<h;y++){let E=o.get(f[y]);E===void 0?f[y]=-1:(f[y]=E,w[i[E]+p[y]]=1)}let u=n===void 0?void 0:o.get(n.handle),l=n?.gbwtOffset,b,x=(y,E,R)=>{let F=[],T=0,D=0,O=-1,H=y,v=E;for(;;){H===u&&v===l&&(O=T),R&&(R.push(s[H]),F.push(v)),T+=1,D+=c[H];let G=i[H]+v,X=f[G];if(X<0)break;v=p[G],H=X}return{offsets:F,len:D,refAt:O,last:H}},S=(y,E,R,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:y,offsets:E,len:R,weight:void 0,identity:void 0})},I=new Int32Array(r);for(let y=0;y<r;y++){let E=s[y];if(!V(E)){let R=i[y],F=i[y+1]-R;for(let T=0;T<F;T++)if(w[R+T]===0){let D=[],{offsets:O,len:H,refAt:v,last:G}=x(y,T,D),X=s[G];if(v>=0||Ne(E,X)){if(S(D,O,H,v),!V(X)){let m=o.get(ee(X));I[m]=I[m]+1}}else this.twinStarts.add(ve({node:E,offset:T}))}}}for(let y=0;y<r;y++){let E=s[y];if(V(E)){let R=i[y],F=i[y+1]-R,T=0;for(let O=0;O<F;O++)w[R+O]===0&&(T+=1);let D=(u===void 0||b!==void 0)&&T===I[y];for(let O=0;O<F;O++)if(w[R+O]===0){let H=D?void 0:x(y,O,void 0);if(H&&(H.refAt>=0||Ne(E,s[H.last]))){let v=[],{offsets:G,len:X,refAt:m}=x(y,O,v);S(v,G,X,m)}else this.twinStarts.add(ve({node:E,offset:O}))}}}let N=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),N&&(this.refId=this.paths.indexOf(N)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let F of y.path.slice(0,b))E+=this.record(F).sequenceLen;let R=n.seqOffset-E;this.refInterval=[R,R+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:R,hapEnd:R+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Te(n)?De(n):void 0,r=d=>s!==void 0&&Ft(d,s)===0||Te(De(d)),o=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((d,h)=>Ft(d.path,h.path)||d.len-h.len||(d===t?-1:h===t?1:0));let i=[],c;for(let d of this.paths){let h=i[i.length-1],f=o&&d!==t&&r(d.path);this.twinDeferred||=f,h&&Ft(h.path,d.path)===0&&!f?h.weight=(h.weight??1)+(d.weight??1):(d===t&&(c=i.length),i.push({...d,weight:d.weight??1}))}this.paths=i,this.refId=c}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=o=>`${o.pathHandle}:${o.hapStart}-${o.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let o of this.paths)o!==e&&o.identity?.orientation==="forward"&&s.add(n(o.identity));let r=this.paths.filter(o=>o===e||o.identity?.orientation!=="reverse"||!s.has(n(o.identity)));r.length<this.paths.length&&(this.paths=r,this.refId=e===void 0?void 0:r.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(o=>o.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((o,i)=>i!==this.refId&&o.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((o,i)=>i===this.refId||o.identity!==void 0&&e(o.identity.name)),r=new Set;for(let o of s)for(let i of o.path)r.add($(i));for(let o of[...this.records.keys()])r.has($(o))||this.records.delete(o);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let r=e.position.seqOffset,o=await Vn({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:r-e.position.nodeOffset,window:{start:r,end:r+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(h,f,p)=>this.prefetchReferenceRange(h,f,p)});if(this.stats.keep=o.stats,o.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),c=h=>({path:h.handles,offsets:h.offsets,len:h.len,weight:void 0,identity:{pathHandle:h.pathHandle,name:h===o.reference?e.name:i.get(h.pathHandle).name,orientation:h.orientation,hapStart:h.hapStart,hapEnd:h.hapEnd}}),d=[o.reference,...o.pieces].sort(Zn);return this.paths=d.map(c),this.refId=d.indexOf(o.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[o.reference.hapStart,o.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Ot(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ve(l),l);let r=l=>{let b=0,x=t.length-1;for(;b<x;){let I=b+x+1>>1;t[I][0]<=l?b=I:x=I-1}let S=t[b];return S[0]<=l&&l<=S[1]},o=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&o.set(ve(nt(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let c=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),d=l=>(i.graphLookups+=1,c(l)),h=async(l,b)=>{if(r(l.node))return n.get(ve(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},w=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},u=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let N,y=0,E=l,R;for(;N===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){I.end="cycle";break}S.add(E);let H=this.paths[E];x.push({index:E,startBp:y}),I.fragments+=1;let v=y;for(let X=0;X<H.path.length;X++){let m=nt(H,X),k=n.get(ve(m)),A=this.record(m.node).sequenceLen;if(k){N=w(k,v,A);break}v+=A}if(y+=H.len,N){I.end="in-fragment sample";break}let G=nt(H,H.path.length-1);R=this.record(G.node).gbwt().lf(G.offset),E=void 0}if(R===void 0||R.node===0){I.end="endmarker";break}let F=ve(R),T=o.get(F);if(T!==void 0){let H=this.paths[T].identity;if(H){N=u(H,y),I.end="identified sibling";break}E=T;continue}this.records.has(R.node)&&(I.reentries+=1),this.twinStarts.has(F)&&(I.twinLandings+=1);let D=await h(R,I),O=await d(R.node);if(D){N=w(D,y,O.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,y-x[x.length-1].startBp>4*e+4*O.sequenceLen){I.end="bound";break}y+=O.sequenceLen,R=O.gbwt().lf(R.offset)}if(N){I.pathHandle=N.pathHandle;let F=await p(N.pathHandle);for(let{index:T,startBp:D}of x){let O=this.paths[T];O.identity=N.orientation==="forward"?{pathHandle:N.pathHandle,name:F,orientation:"forward",hapStart:N.base+D,hapEnd:N.base+D+O.len}:{pathHandle:N.pathHandle,name:F,orientation:"reverse",hapStart:N.base-D-O.len,hapEnd:N.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let r=t.get(n);r?r.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),r=new Int32Array(e.length),o=0,i=-1;for(let c=0;c<e.length;c++){let d=n.get(e[c]);if(d){let h=Rs(d,i);if(h===void 0)return;s[o]=c,r[o]=h,o+=1,i=h}}return{pathAt:s,refAt:r,count:o}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[s]).sequence,d=this.record(t[r]).sequence;for(;o<c.length&&i<d.length;){if(c[o]!==d[i])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[e.length-s-1]).sequence,d=this.record(t[t.length-r-1]).sequence;for(;o<c.length&&i<d.length;){if(c[c.length-o-1]!==d[d.length-i-1])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),r=this.pathLen(t),o=this.prefixMatches(e,t),i=this.suffixMatches(e,t);o+i>s&&(i=s-o),o+i>r&&(i=r-o),Z(n,"M",o),Xn(n,s-o-i,r-o-i),Z(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let r of e)n.has(r)&&(s+=this.record(r).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??As(yn(e,t,f=>this.record(f).sequenceLen)[0]),r=[],o=this.refPrefix(t),i=(f,p,w,u)=>{f===p?Z(r,"D",o[u]-o[w]):w===u?Z(r,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(w,u),r)},c=0,d=0,h=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],w=s.refAt[f];(d!==p||h!==w)&&i(d,p,h,w);let u=this.record(e[p]).sequenceLen;Z(r,"M",u),c+=u,d=p+1,h=w+1}return i(d,e.length,h,t.length),{edits:r,matched:c,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Te(n)&&(t.identity===void 0||!Te(De(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let r=De(t.path),o=this.sharedWeight(t.path,n);if(this.sharedWeight(r,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(o===0)s={...this.editsAgainst(r,n),flipped:!0};else{let c=this.editsAgainst(t.path,n),d=this.editsAgainst(r,n);s=d.matched>c.matched?{...d,flipped:!0}:{...c,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(h,f,p,w)=>{let u=Bs(h),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,S=x?.orientation==="forward",[I,N]=S?[l,b]:[b,l];return{strand:f,refStart:e.start+u.leading,refEnd:e.start+n-u.trailing,edits:u.edits,weight:l.weight,path:p.flatMap(y=>this.paths[y].path),start:nt(l,0),pieces:p,soloAligned:w,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+I.identity.hapStart,hapEnd:x.name.fragment+N.identity.hapEnd,walkForward:S}}},r=h=>h.soloAligned.reduce((f,p)=>f+p,0),o=h=>h.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=h=>2*r(h)>=o(h),c=h=>{let f=h[0],p=h[h.length-1],w=f.identity.walkForward;if(h.some((v,G)=>v.strand!==f.strand||v.identity.walkForward!==w||G>0&&v.identity.hapStart<h[G-1].identity.hapEnd))return;let u=w?h:[...h].reverse(),l=u.flatMap(v=>v.pieces),b=u.flatMap(v=>v.soloAligned),x=f.strand==="+"!==w,S=l.map(v=>this.paths[v]),I=S.slice(1).map((v,G)=>{let X=S[G].identity;return w?v.identity.hapStart-X.hapEnd:X.hapStart-v.identity.hapEnd}),N=x?[...S].reverse():S,y=x?[...I].reverse():I,E=N.flatMap(v=>x?De(v.path):v.path),{edits:R}=this.editsAgainst(E,t),F=Kn(R,N.map(v=>v.len)),T=new Map((x?[...l].reverse():l).map((v,G)=>[v,F[G]])),D=v=>2*v.pieces.reduce((G,X)=>G+T.get(X),0)>=r(v);if(!D(f)||!D(p))return;let O=[],H=0;return N.slice(0,-1).forEach((v,G)=>{H+=v.len,O.push([H,y[G]])}),s(Fs(R,O),f.strand,l,b)},d=[];return this.paths.forEach((h,f)=>{if(f===this.refId)return;let{edits:p,flipped:w}=this.alignment(f),u=h.identity,l=u?u.orientation==="forward"!==w:!w;d.push(s(p,l?"+":"-",[f],Kn(p,[h.len])))}),Ms(d,i,c).map(h=>{let{edits:f,identity:p,pieces:w,soloAligned:u,...l}=h,b={...l,cigar:Ts(f)};return p?{...b,resolved:!0,name:p.name,label:pe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,r=this.paths.flatMap(h=>{let{identity:f}=h;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:rt(h,f)}]:[]}),o=h=>f=>f.sample===h.sample&&f.haplotype===h.haplotype,i=o(t),c=n?o(n):h=>!i(h),d=h=>this.record(fe(h,"forward")).sequence;return r.filter(h=>i(h.name)).flatMap(h=>r.filter(f=>c(f.name)).flatMap(f=>bn({...s,query:f.steps,target:h.steps,sequenceOf:d}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:h.name,targetStart:h.start+p.targetStart,targetEnd:h.start+p.targetEnd,cigar:xn(p.edits),matches:p.edits.reduce((w,[u,l])=>w+(u==="="?l:0),0),columns:p.edits.reduce((w,[,u])=>w+u,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=fe(e,n);for(let r of this.record(s).successors())this.hasHandle(r)&&Fe(s,r)&&t.push([n==="reverse"?1:0,$(r),V(r)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!V(n)){let s=$(n),r=`S ${s} ${this.record(n).sequence}
|
|
1
|
+
import{a as fe,b as $,c as ke,d as V,e as ee,f as pn,g as Xe,h as Ye,i as un,j as gn,k as Fe,l as Te,m as Ne,n as wn,o as mn,p as yn,q as bn,r as xn,s as Rn,t as $n,u as Hn,v as Cn}from"./chunk-EF34SRHG.js";import{a as Nn}from"./chunk-SHPBCGXL.js";import{a as vn}from"./chunk-V55TK2NP.js";import"./chunk-JM4W4PKP.js";import{a as bs,b as Ln,c as Mn,d as Ht}from"./chunk-P4IMSFPU.js";import{a as In,g as kn,h as Lt,i as Mt}from"./chunk-ODX7AL6K.js";import"./chunk-YBLNN5FU.js";import"./chunk-Y74MVEM7.js";import"./chunk-ALUAL23O.js";import{Y as En,c as Sn}from"./chunk-B2EPNVM7.js";import"./chunk-FQI75MV6.js";import{b as _e,d as An}from"./chunk-U4ZQHJHX.js";import{j as Pn}from"./chunk-QNGSRFA7.js";import"./chunk-TMM73K4C.js";import{a as $e}from"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as Ke,h as dn,i as fn,j as ln}from"./chunk-EGZZ3ADM.js";import{a as Rt,g as Ae,h as Re,i as $t}from"./chunk-52Z3M7SW.js";import{e as hn,q as At}from"./chunk-5L276I7O.js";var ze=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},On=255,xs=256,Je=class{source;sigma;threshold;constructor(e,t){this.source=new ze(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<On?Math.floor(xs/this.sigma):0}next(){if(this.sigma>=On){let s=this.source.int(),r=this.source.int();return s===void 0||r===void 0?void 0:{value:s,len:r+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let s=this.source.int();if(s===void 0)return;n+=s}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Bn(a){let e=new ze(a),t=e.int();if(t===void 0||t===0)return[];let n=[],s=0;for(let r=0;r<t;r++){let o=e.int(),i=e.int();if(o===void 0||i===void 0)throw new Error("GBWT edge list ends early");s+=o,n.push({node:s,offset:i})}return n}var et=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Je(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(s=>s.offset),n=0;for(let s of this.runs()){let r=this.edge(s.value),o=t[s.value];if(n+s.len>e)return r.node===0?void 0:{node:r.node,offset:o+(e-n)};t[s.value]=o+s.len,n+=s.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let s=t+n>>1,r=this.edges[s];if(r.node===e)return s;r.node<e?t=s+1:n=s}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let s=0;for(let r of this.runs())if(s+=r.len,r.value===t&&(n+=r.len,n>e.offset))return s-(n-e.offset)}predecessorAt(e){let t=this.edges.map(s=>({node:s.node===0?0:ee(s.node),count:0}));for(let s of this.runs()){let r=t[s.value];r&&(r.count+=s.len)}for(let s=1;s<t.length;s++){let r=t[s-1],o=t[s];$(r.node)===$(o.node)&&(t[s-1]=o,t[s]=r)}let n=0;for(let s of t)if(n+=s.count,n>e)return s.node===0?void 0:s.node}decompressArrays(){let e=this.edges.map(o=>o.offset),t=0;for(let o of this.runs())t+=o.len;let n=new Int32Array(t),s=new Int32Array(t),r=0;for(let o of this.runs()){let i=this.edge(o.value),c=e[o.value];for(let d=0;d<o.len;d++)n[r]=i.node,s[r]=c,c+=1,r+=1;e[o.value]=c}return{nodes:n,offsets:s}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let s=this.edge(n.value);for(let r=0;r<n.len;r++)t.push({node:s.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var Ss=Uint32Array.from([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]),we=(a,e)=>a>>>e|a<<32-e;function Fn(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let d=0;d<e;d++){for(let S=0;S<16;S++)o[S]=n.getUint32(d*64+S*4);for(let S=16;S<64;S++){let I=o[S-15],N=o[S-2],y=we(I,7)^we(I,18)^I>>>3,E=we(N,17)^we(N,19)^N>>>10;o[S]=o[S-16]+y+o[S-7]+E}let h=r[0],f=r[1],p=r[2],w=r[3],u=r[4],l=r[5],b=r[6],x=r[7];for(let S=0;S<64;S++){let I=we(u,6)^we(u,11)^we(u,25),N=u&l^~u&b,y=x+I+N+Ss[S]+o[S]|0,E=we(h,2)^we(h,13)^we(h,22),R=h&f^h&p^f&p;x=b,b=l,l=u,u=w+y|0,w=p,p=f,f=h,h=y+E+R|0}[h,f,p,w,u,l,b,x].forEach((S,I)=>{r[I]=r[I]+S})}let i=new Uint8Array(32),c=new DataView(i.buffer);for(let d=0;d<8;d++)c.setUint32(d*4,r[d]);return i}function Tn(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[r,o]=s;if(s.length!==2||!r||!o)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(r);i||(i=new Set,t.set(r,i)),i.add(o)}return t}function qn(a){return{name:a.get("pggname"),subgraph:Tn(a.get("subgraph"),"subgraph"),translation:Tn(a.get("translation"),"translation")}}function _n(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let r of n)s.add(r)}}function Dn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),_n(t.subgraph,e.subgraph),_n(t.translation,e.translation)),t}function zn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function Gn(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of zn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of zn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function jn(a){let e=a.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of a)t.set(o,n),n+=o.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Fn(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Is="_gbwt_ref";function pe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Es=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,ks=/^([^#]+?)(?:\[\d+-\d+\])?$/;function vs(a){let e=Es.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=ks.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Le(a){return typeof a=="string"?vs(a):a}function Me(a,e){return{sample:a.sample??Is,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var Ps=4096;function Ot(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ps?n[1]=t:e.push([t,t])}return e}var Ns=32768,Un={mostChosenPaths:32},Ct=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},oe=class extends Error{};function tt(a,e,t,n){return a==="forward"?e+t:e-n}function Wn(a,e,t,n){return a==="forward"?e-n:e+t}function Qn(a){return Ne(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function qe(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Vn(a){let{db:e,records:t,signal:n}=a,s=performance.now(),r=()=>{let m=performance.now(),k=m-s;return s=m,k},o={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(m,k)=>{let A=`${m}: ${k}`;o.walks[A]=(o.walks[A]??0)+1},c=await e.haplotypeSampleInterval()??4096,d=new Map,h=async m=>{let k=t.get(m)??d.get(m);if(k)return k;let A=await e.getRecord(m);if(o.graphFetches+=1,!A)throw new Error(`Node record ${m} is missing from the database`);return d.set(m,A),A},f=m=>t.get(m).sequenceLen,p=await e.pathsByHandle(),w=m=>{let k=p.get(m);return k!==void 0&&a.keep(k.name)},u=[],l=new Ct,b=new Map,x=new Set,S=new Set,I=async m=>{let k=(await h(m.node)).gbwt().lf(m.offset);return k===void 0||k.node===0?void 0:k},N=async(m,k)=>{let A=(await h(ee(m.node))).gbwt().predecessorAt(m.offset);if(A===void 0||k!==void 0&&!k.has(A))return;let L=(await h(A)).gbwt().offsetTo(m);if(L===void 0)throw new Error(`No offset in ${A} leads to ${m.node}:${m.offset}`);return{node:A,offset:L}},y=(m,k,A,L)=>{let B=A.map(U=>U.pos.node),j=A.map(U=>U.pos.offset),Y=0;for(let U of B)Y+=f(U);let C=k==="forward"?A[0].left:A[A.length-1].left,M=u.length;u.push({pathHandle:m,orientation:k,handles:B,offsets:j,len:Y,hapStart:C,hapEnd:C+Y,canonical:Ne(B[0],B[B.length-1]),source:L});for(let U of A)l.set(U.pos,M);let Q=b.get(m);return Q?Q.push(M):b.set(m,[M]),M},E=async(m,k,A,L)=>{let B=[],j=m;for(;;){n?.throwIfAborted();let C=await N(j.pos,t);if(!C)break;j={pos:C,left:Wn(A,j.left,f(j.pos.node),f(C.node))},B.push(j)}B.reverse();let Y=[m];for(j=m;;){n?.throwIfAborted();let C=await I(j.pos);if(!C||!t.has(C.node))break;j={pos:C,left:tt(A,j.left,f(j.pos.node),f(C.node))},Y.push(j)}return y(k,A,[...B,...Y],L)},R=async(m,k,A,L)=>u[l.get(m.pos)??await E(m,k,A,L)],F=m=>{let k=m.handles[m.handles.length-1];return{pos:{node:k,offset:m.offsets[m.offsets.length-1]},left:m.orientation==="forward"?m.hapEnd-f(k):m.hapStart}},T=m=>{let k=m.handles[0];return{pos:{node:k,offset:m.offsets[0]},left:m.orientation==="forward"?m.hapStart:m.hapEnd-f(k)}},D=await E({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),O=u[D],H=()=>{if(o.fallback!==void 0)return{reference:O,pieces:[],stats:o};let m=new Map;u.forEach((A,L)=>{L!==D&&m.set(qe(A),[...m.get(qe(A))??[],A])});let k=[];for(let A of m.values()){let L=new Set;for(let B of A)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),k.push(B),o.sources[B.source]+=1)}return o.sources.reference=1,o.pieces=k.length+1,{reference:O,pieces:k,stats:o}},v=async(m,k)=>{let A=k?x:S,L=k?S:x,B=m;for(;;){if(A.has(B))return;A.add(B);let j=u[B],Y=k?F(j):T(j),C=0,M;for(;M===void 0;){n?.throwIfAborted();let Q=k?await I(Y.pos):await N(Y.pos);if(!Q){M="endmarker";break}let U=(await h(Y.pos.node)).sequenceLen,ge=(await h(Q.node)).sequenceLen,se=k?tt(j.orientation,Y.left,U,ge):Wn(j.orientation,Y.left,U,ge);if(t.has(Q.node)){let J=l.get(Q);J===void 0?(B=await E({pos:Q,left:se},j.pathHandle,j.orientation,"chain"),L.add(B),M="landed"):(L.add(J),M="merge")}else C>Ns?M="bound":(C+=ge,Y={pos:Q,left:se})}if(i("chain",M),M!=="landed")return}},G=async m=>{if(a.context>m.context)throw new oe(`the context of ${a.context} bp exceeds the ${m.context} bp the haplotype index's stray rows cover`);let k=o.spacing;if(k===void 0)throw new oe("the haplotype index has no anchors");let{bin:A,bound:L}=m,{fills:B,inserted:j}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new oe("the haplotype index's stray rows cover contained snarls only");for(let g of B){if(g.inserted>0&&g.low===g.high)throw new oe(`the haplotype index's stray rows leave out the snarl bounded by node ${g.low} at both ends`);if(g.inserted>0&&(m.snarlNodes===void 0||g.nodes>m.snarlNodes))throw new oe(m.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${g.nodes} nodes exceeds the ${m.snarlNodes} the haplotype index's stray rows cover`)}let Y=Math.floor(a.window.start/A),C=Math.floor((a.window.end-1)/A),M=Y*A,Q=(C+1)*A,U=new Map,ge=async(g,P)=>{let q=await e.haplotypeAnchorsBetween(a.referenceHandle,g*k,P*k);for(let _ of q)U.set(_.anchorOffset/k,_)},se=Math.max(0,Math.floor((M-L)/k)-1),J=Math.ceil((Q+L)/k)+1,[{listed:Ve,strays:ie}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,Y,C),ge(se,J)]);for(let g of t.keys()){let P=$(g);if(!V(g)&&!Ve(P)&&!j.has(P))throw new oe(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}o.scans=Ot([...t.keys()].sort((g,P)=>g-P));let he=Promise.all(o.scans.map(([g,P])=>e.haplotypeSamplesInRange(g,P)));for(he.catch(()=>{});se>0&&(U.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=M-L;)se-=1,await ge(se,se);for(;U.has(J)&&U.get(J).pathOffset<=Q+L;)J+=1,await ge(J,J);let ue=[...U.keys()].sort((g,P)=>g-P),be=U.get(ue[0]??-1);if(!be)throw new oe("the haplotype index has no anchors on this path");let de=g=>U.get(g).pathOffset,Ce=new Map;for(let g of ue){let P=$(U.get(g).node);Ce.set(P,[...Ce.get(P)??[],g])}let vt=[...Ce.keys()],Xt=vt.map(g=>U.get(Ce.get(g)[0]).visits);if(!Xt[vt.indexOf($(be.node))].some(g=>g.pathHandle===a.referenceHandle&&g.orientation==="forward"&&g.pathOffset===be.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${be.pathOffset} (node ${$(be.node)}); it does not match this graph`);let Yt=ue.filter(g=>de(g)<=a.window.start),gs=ue.filter(g=>de(g)>=a.window.end);o.anchors=[de(Yt[Yt.length-1]??ue[0]),de(gs[0]??ue[ue.length-1])],o.anchorsRead=ue.length;let Pt=new Map,Jt=new Set;if(vt.forEach((g,P)=>{let q=Ce.get(g),_=q.length===1?q[0]:void 0;for(let z of Xt[P])Jt.add(z.pathHandle),z.orientation==="forward"&&w(z.pathHandle)&&Pt.set(z.pathHandle,[...Pt.get(z.pathHandle)??[],{k:_,row:z}])}),o.chosenPaths=[...Jt].filter(w).length,o.chosenPaths>Un.mostChosenPaths)throw new oe(`${o.chosenPaths} chosen paths pass the anchors, more than ${Un.mostChosenPaths}`);let Ze=[],Ee=Number.POSITIVE_INFINITY,xe=0;for(let[g,P]of Pt){P.sort((q,_)=>q.row.pathOffset-_.row.pathOffset);for(let q=0;q+1<P.length;q++){let _=P[q],z=P[q+1];if(_.k===void 0||z.k===void 0||Math.abs(_.k-z.k)!==1)continue;let[K,te]=de(_.k)<=de(z.k)?[_,z]:[z,_],ne=de(K.k),re=de(te.k);ne<Q&&re>=M?(Ze.push({pathHandle:g,from:_.row,to:z.row}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,re+L)):ne>=Q&&ne-Q<=L?(Ze.push({pathHandle:g,from:K.row,to:void 0}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,ne+L)):re<M&&M-re<=L&&(Ze.push({pathHandle:g,from:te.row,to:void 0}),Ee=Math.min(Ee,re-L),xe=Math.max(xe,re+L))}}let ws=new Set(B.map(g=>`${g.low}:${g.high}`)),ms=ie.filter(g=>w(g.pathHandle)&&(g.snarl===void 0||ws.has(`${g.snarl[0]}:${g.snarl[1]}`))).sort((g,P)=>g.pathHandle-P.pathHandle||g.pathStart-P.pathStart);o.strays={bins:C-Y+1,rows:ie.length,walked:0,outsideBp:0},xe>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ee),xe+1),o.ms.scan=r();let en=8*k+2*(a.window.end-a.window.start),tn=o.strays,Oe=0,nn=g=>{if(tn.outsideBp+=g,Oe+=g,Oe>en)throw new oe(`a walk of a chosen path near the window went past its cap of ${en} bp`)},Nt=new Map,sn=(g,P,q)=>(Nt.get(g)??[]).some(([_,z])=>_<=P&&q<z),rn=(g,P,q)=>{Nt.set(g,[...Nt.get(g)??[],[P,q]])},on=async(g,P,q,_,z)=>{let K=P,te=q,ne=te;for(;K&&te<=_;){n?.throwIfAborted();let re;if(t.has(K.node)){let Be=await R({pos:K,left:te},g,"forward",z),cn=F(Be);K=cn.pos,te=cn.left,re=f(K.node),ne=Math.max(ne,Be.hapEnd)}else re=(await h(K.node)).sequenceLen,nn(re),ne=Math.max(ne,te+re);K=await I(K),te+=re}return ne},ys=async(g,P,q,_)=>{let z={pos:P,left:q},K=q;for(;z.left>_;){n?.throwIfAborted();let te=await N(z.pos);if(!te)break;let ne=(await h(te.node)).sequenceLen,re=z.left-ne;if(t.has(te.node)){let Be=await R({pos:te,left:re},g,"forward","section");z=T(Be),K=Math.min(K,Be.hapStart)}else nn(ne),z={pos:te,left:re},K=Math.min(K,re)}return K};for(let{pathHandle:g,from:P,to:q}of Ze){let _=P.pathOffset,z=(q??P).pathOffset+L;if(sn(g,_-L,z))continue;let K={node:P.node,offset:P.offset};Oe=0;let te=await on(g,K,_,z,"section");Oe=0;let ne=await ys(g,K,_,_-L);rn(g,Math.min(ne,_-L),Math.max(te,z+1)),i(q?"section":"visit",q?"past the far anchor":"bound")}for(let g of ms){if(sn(g.pathHandle,g.pathStart,g.pathEnd))continue;Oe=0;let P=await on(g.pathHandle,{node:g.node,offset:g.offset},g.pathStart,g.pathEnd,"stray");rn(g.pathHandle,g.pathStart,Math.max(P,g.pathEnd+1)),tn.walked+=1}o.ms.walks=r();let an=[];for(let g of await he)for(let P of g)if(o.scanRows+=1,t.has(P.node)&&w(P.pathHandle)){if(!(b.get(P.pathHandle)??[]).some(q=>{let _=u[q];return _.hapStart<=P.pathOffset&&P.pathOffset<_.hapEnd}))throw new oe(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&an.push(P)}for(let g of an)await R({pos:{node:g.node,offset:g.offset},left:g.pathOffset},g.pathHandle,"reverse","twin");o.ms.check=r()},X=async()=>{let m=new Map,k=C=>{let M=qe(C),Q=m.get(M);Q?Q.add(C.orientation):m.set(M,new Set([C.orientation]))},A=0,L=()=>{for(;A<u.length;A++)k(u[A])};L();let B=C=>(m.get(qe(C))?.size??0)>1,j=2*c,Y=(C,M)=>M===D?w(a.referenceHandle)&&Qn(C):!C.canonical||Qn(C);for(let C=0;C<u.length;C++){let M=u[C];if(B(M)||!Y(M,C))continue;o.twins.tried+=1;let Q=M.orientation==="forward"?"reverse":"forward",U=F(M),ge=0,se;for(;!se&&ge<=j;){n?.throwIfAborted();let ie=await I(U.pos);if(!ie)break;let he=(await h(ie.node)).sequenceLen,ue=tt(M.orientation,U.left,(await h(U.pos.node)).sequenceLen,he),be=ee(ie.node);se=(await e.haplotypeSamplesInRange(be,be)).find(de=>de.pathHandle===M.pathHandle&&de.orientation===Q&&de.pathOffset===ue),ge+=he,U={pos:ie,left:ue}}let J=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},Ve=0;for(;J&&!B(M)&&Ve<=j+M.len;){if(n?.throwIfAborted(),t.has(J.pos.node)){let ie=await R(J,M.pathHandle,Q,"twin"),he=u.indexOf(ie);await v(he,!0),await v(he,!1),L(),J=F(ie)}if(!B(M)){let ie=(await h(J.pos.node)).sequenceLen;Ve+=ie;let he=await I(J.pos);J=he?{pos:he,left:tt(Q,J.left,ie,(await h(he.node)).sequenceLen)}:void 0}}if(L(),!B(M))throw new oe(`piece ${qe(M)} was found in one orientation where extractPaths keeps the other`);o.twins.found+=1}o.ms.twins=r()};try{let m=await e.haplotypeStrayOptions();if(m===void 0)throw new oe("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await G(m),await X()}catch(m){if(!(m instanceof oe))throw m;o.fallback=m.message}return H()}function Zn(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var ae=class extends Error{name="SubgraphLimitError";limit;windowBp;walkedBp;constructor(e,t){super(t===void 0?`Subgraph size limit of ${e} nodes exceeded`:`Subgraph size limit of ${e} nodes exceeded ${t.walkedBp} bp into a ${t.windowBp} bp window`),this.limit=e,this.windowBp=t?.windowBp,this.walkedBp=t?.walkedBp}};function Bt(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var Ge=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let r=s.length-1;for(;r>0;){let o=r-1>>1;if(Bt(s[r],s[o]))[s[r],s[o]]=[s[o],s[r]],r=o;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let r=2*s+1,o=r+1,i=s;if(r<e.length&&Bt(e[r],e[i])&&(i=r),o<e.length&&Bt(e[o],e[i])&&(i=o),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function As(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],r)=>{e[r]=n,t[r]=s}),{pathAt:e,refAt:t,count:a.length}}function Rs(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ve(a){return`${a.node}:${a.offset}`}function De(a){return a.map(e=>ee(e)).reverse()}function $s(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Ls(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],r=n.edits.map(([d,h])=>[d,h]);Xn(r,t.insertion,t.deletion);for(let[d,h]of s.edits)Z(r,d,h);let o=a.identity.walkForward,[i,c]=o?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:r,weight:void 0,path:[...i.path,...c.path],start:i.start,pieces:[...i.pieces,...c.pieces],soloAligned:[...i.soloAligned,...c.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:o}}}function Ms(a,e,t){if(a.some(o=>o.weight!==void 0))return a;let n=new Map;a.forEach((o,i)=>{if(o.identity){let c=n.get(o.identity.pathHandle);c?c.push(i):n.set(o.identity.pathHandle,[i])}});let s=new Map,r=new Set;for(let o of n.values()){o.sort((h,f)=>a[h].identity.hapStart-a[f].identity.hapStart);let i=o[0],c=a[i],d=[];for(let h of o.slice(1)){let f=a[h],p=d.length===0?$s(c,f):void 0;if(p){c=Ls(c,f,p),r.add(h);continue}if(!e(f)){d.push(h);continue}let w=e(c)?t([c,...d.map(u=>a[u]),f]):void 0;if(w){c=w;for(let u of[...d,h])r.add(u)}else s.set(i,c),i=h,c=f;d=[]}s.set(i,c)}return a.flatMap((o,i)=>r.has(i)?[]:[s.get(i)??o])}function nt(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Hs=32768;function Cs(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Hs?s[1]=n:t.push([n,n])}return t}var je=class a{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new a(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(fe(e,"forward"))}hasHandle(e){return this.records.has(e)}record(e){let t=this.records.get(e);if(!t)throw new Error(`Subgraph has no record for handle ${e}`);return t}sortedHandles(){return[...this.records.keys()].sort((e,t)=>e-t)}async addNode(e){if(this.signal?.throwIfAborted(),this.limit!==void 0&&this.nodeCount>=this.limit)throw new ae(this.limit);let t=await this.db.getRecord(fe(e,"forward")),n=await this.db.getRecord(fe(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${pe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let r=n,o=s;for(;;){await this.ensureNode($(o.node));let i=this.record(o.node);if(r+i.sequenceLen>t)return{position:{seqOffset:t,handle:o.node,nodeOffset:t-r,gbwtOffset:o.offset},name:e.name,handle:e.handle};r+=i.sequenceLen;let c=i.gbwt().lf(o.offset);if(!c)throw new Error(`The fragment of ${pe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);o=c}}async aroundPosition(e,t,n){let s=$(e);await this.ensureNode(s);let r=this.record(e),o=ke(e),i=new Ge;return i.push(t,s,Xe(o)),i.push(r.sequenceLen-t-1,s,Ye(o)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,r]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&r){let o=s.pos.node,i=r.pos.node;if(!await this.db.prefetchRecords([[Math.min(o,i),Math.max(o,i)+1]])){let d=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Cs(d.map(h=>h.pos.node)).map(([h,f])=>[h,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof ae&&s.windowBp===void 0?new ae(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},r=e.nodeOffset,o=t,i=new Ge;for(;;){let c=$(s.node),d=ke(s.node);this.walkedBp=t-o,await this.ensureNode(c);let h=this.record(s.node);if(r>=h.sequenceLen)throw new Error(`Offset ${r} in node ${c} of length ${h.sequenceLen}`);i.push(r,c,Xe(d));let f=h.sequenceLen-r;if(o<=f){i.push(o===f?0:f-o-1,c,Ye(d));break}i.push(0,c,Ye(d));let p=h.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,r=0,o-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new Ge;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let o of this.records.keys())s.add($(o));let r=0;for(;e.size>0;){let[o,i,c]=e.pop(),d=`${i}:${c}`;if(n.has(d))continue;n.add(d),s.delete(i),this.hasNode(i)||(await this.addNode(i),r+=1);let h=pn(c);if(!n.has(`${i}:${h}`)){let w=this.record(fe(i,un(c))),u=o+w.sequenceLen-1;u<=t&&e.push(u,i,h)}let f=this.record(fe(i,gn(c))),p=o+1;if(p<=t)for(let w of f.successors()){let u=$(w),l=Xe(ke(w));n.has(`${u}:${l}`)||e.push(p,u,l)}}for(let o of s)this.records.delete(fe(o,"forward")),this.records.delete(fe(o,"reverse"));return{inserted:r,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([$(e),$(t)]),r=[];for(;n.length>0;){let o=n.pop(),i=$(o);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let c of this.record(o).successors()){let d=$(c);s.has(d)||(n.push(c,ee(c)),s.add(d))}}return{inserted:r,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:r,nodes:o}=await this.fillBetween(n,s),i=$(n),c=$(s);this.snarlFills.push({low:Math.min(i,c),high:Math.max(i,c),nodes:o,inserted:r.length});for(let d of r)this.snarlNodes.add(d);t+=r.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let r=this.record(s),o=r.next;o!==void 0&&(n=!0,this.hasHandle(o)?Fe(s,o)&&t.push([s,o]):e==="overlapping"&&this.isSnarlEntryInSubgraph(r)&&t.push([s,o]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let r=t.get(n);if(!r){if(r=await this.db.getRecord(n),e?.(),!r)throw new Error(`Node record ${n} is missing from the database`);t.set(n,r)}return r}}async findCoveringSnarl(){let e=this.recordReader(),t=async c=>{let d=c.successors(),h=d[0];return h===void 0?!1:d.length>1||(await e(ee(h))).successors().length>1},n=async c=>{let d=await e(ee(c));return d.next!==void 0?await t(d)?{kind:"snarl-exit",snarl:[ee(c),d.next]}:{kind:"chain"}:(await e(c)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,r=this.sortedHandles().flatMap(c=>this.record(c).successors()),o,i=!1;for(;!i&&r.length>0;){let c=r.shift(),d=$(c);if(!this.hasHandle(c)&&!s.has(d)){s.add(d);let h=await n(c);if(h.kind==="snarl-exit")o=h.snarl,i=!0;else if(h.kind==="chain")i=!0;else for(let f of["forward","reverse"])r.push(...(await e(fe(d,f))).successors())}}return o}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),r=s.length,o=new Map;s.forEach((y,E)=>o.set(y,E));let i=new Int32Array(r+1),c=new Int32Array(r),d=[];for(let y=0;y<r;y++){let E=this.record(s[y]),R=E.gbwt().decompressArrays();c[y]=E.sequenceLen,d.push(R),i[y+1]=i[y]+R.nodes.length}let h=i[r],f=new Int32Array(h),p=new Int32Array(h),w=new Uint8Array(h);for(let y=0;y<r;y++){let E=d[y];f.set(E.nodes,i[y]),p.set(E.offsets,i[y])}d.length=0;for(let y=0;y<h;y++){let E=o.get(f[y]);E===void 0?f[y]=-1:(f[y]=E,w[i[E]+p[y]]=1)}let u=n===void 0?void 0:o.get(n.handle),l=n?.gbwtOffset,b,x=(y,E,R)=>{let F=[],T=0,D=0,O=-1,H=y,v=E;for(;;){H===u&&v===l&&(O=T),R&&(R.push(s[H]),F.push(v)),T+=1,D+=c[H];let G=i[H]+v,X=f[G];if(X<0)break;v=p[G],H=X}return{offsets:F,len:D,refAt:O,last:H}},S=(y,E,R,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:y,offsets:E,len:R,weight:void 0,identity:void 0})},I=new Int32Array(r);for(let y=0;y<r;y++){let E=s[y];if(!V(E)){let R=i[y],F=i[y+1]-R;for(let T=0;T<F;T++)if(w[R+T]===0){let D=[],{offsets:O,len:H,refAt:v,last:G}=x(y,T,D),X=s[G];if(v>=0||Ne(E,X)){if(S(D,O,H,v),!V(X)){let m=o.get(ee(X));I[m]=I[m]+1}}else this.twinStarts.add(ve({node:E,offset:T}))}}}for(let y=0;y<r;y++){let E=s[y];if(V(E)){let R=i[y],F=i[y+1]-R,T=0;for(let O=0;O<F;O++)w[R+O]===0&&(T+=1);let D=(u===void 0||b!==void 0)&&T===I[y];for(let O=0;O<F;O++)if(w[R+O]===0){let H=D?void 0:x(y,O,void 0);if(H&&(H.refAt>=0||Ne(E,s[H.last]))){let v=[],{offsets:G,len:X,refAt:m}=x(y,O,v);S(v,G,X,m)}else this.twinStarts.add(ve({node:E,offset:O}))}}}let N=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),N&&(this.refId=this.paths.indexOf(N)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let F of y.path.slice(0,b))E+=this.record(F).sequenceLen;let R=n.seqOffset-E;this.refInterval=[R,R+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:R,hapEnd:R+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Te(n)?De(n):void 0,r=d=>s!==void 0&&Ft(d,s)===0||Te(De(d)),o=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((d,h)=>Ft(d.path,h.path)||d.len-h.len||(d===t?-1:h===t?1:0));let i=[],c;for(let d of this.paths){let h=i[i.length-1],f=o&&d!==t&&r(d.path);this.twinDeferred||=f,h&&Ft(h.path,d.path)===0&&!f?h.weight=(h.weight??1)+(d.weight??1):(d===t&&(c=i.length),i.push({...d,weight:d.weight??1}))}this.paths=i,this.refId=c}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=o=>`${o.pathHandle}:${o.hapStart}-${o.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let o of this.paths)o!==e&&o.identity?.orientation==="forward"&&s.add(n(o.identity));let r=this.paths.filter(o=>o===e||o.identity?.orientation!=="reverse"||!s.has(n(o.identity)));r.length<this.paths.length&&(this.paths=r,this.refId=e===void 0?void 0:r.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(o=>o.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((o,i)=>i!==this.refId&&o.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((o,i)=>i===this.refId||o.identity!==void 0&&e(o.identity.name)),r=new Set;for(let o of s)for(let i of o.path)r.add($(i));for(let o of[...this.records.keys()])r.has($(o))||this.records.delete(o);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let r=e.position.seqOffset,o=await Vn({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:r-e.position.nodeOffset,window:{start:r,end:r+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(h,f,p)=>this.prefetchReferenceRange(h,f,p)});if(this.stats.keep=o.stats,o.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),c=h=>({path:h.handles,offsets:h.offsets,len:h.len,weight:void 0,identity:{pathHandle:h.pathHandle,name:h===o.reference?e.name:i.get(h.pathHandle).name,orientation:h.orientation,hapStart:h.hapStart,hapEnd:h.hapEnd}}),d=[o.reference,...o.pieces].sort(Zn);return this.paths=d.map(c),this.refId=d.indexOf(o.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[o.reference.hapStart,o.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Ot(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ve(l),l);let r=l=>{let b=0,x=t.length-1;for(;b<x;){let I=b+x+1>>1;t[I][0]<=l?b=I:x=I-1}let S=t[b];return S[0]<=l&&l<=S[1]},o=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&o.set(ve(nt(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let c=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),d=l=>(i.graphLookups+=1,c(l)),h=async(l,b)=>{if(r(l.node))return n.get(ve(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},w=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},u=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let N,y=0,E=l,R;for(;N===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){I.end="cycle";break}S.add(E);let H=this.paths[E];x.push({index:E,startBp:y}),I.fragments+=1;let v=y;for(let X=0;X<H.path.length;X++){let m=nt(H,X),k=n.get(ve(m)),A=this.record(m.node).sequenceLen;if(k){N=w(k,v,A);break}v+=A}if(y+=H.len,N){I.end="in-fragment sample";break}let G=nt(H,H.path.length-1);R=this.record(G.node).gbwt().lf(G.offset),E=void 0}if(R===void 0||R.node===0){I.end="endmarker";break}let F=ve(R),T=o.get(F);if(T!==void 0){let H=this.paths[T].identity;if(H){N=u(H,y),I.end="identified sibling";break}E=T;continue}this.records.has(R.node)&&(I.reentries+=1),this.twinStarts.has(F)&&(I.twinLandings+=1);let D=await h(R,I),O=await d(R.node);if(D){N=w(D,y,O.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,y-x[x.length-1].startBp>4*e+4*O.sequenceLen){I.end="bound";break}y+=O.sequenceLen,R=O.gbwt().lf(R.offset)}if(N){I.pathHandle=N.pathHandle;let F=await p(N.pathHandle);for(let{index:T,startBp:D}of x){let O=this.paths[T];O.identity=N.orientation==="forward"?{pathHandle:N.pathHandle,name:F,orientation:"forward",hapStart:N.base+D,hapEnd:N.base+D+O.len}:{pathHandle:N.pathHandle,name:F,orientation:"reverse",hapStart:N.base-D-O.len,hapEnd:N.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let r=t.get(n);r?r.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),r=new Int32Array(e.length),o=0,i=-1;for(let c=0;c<e.length;c++){let d=n.get(e[c]);if(d){let h=Rs(d,i);if(h===void 0)return;s[o]=c,r[o]=h,o+=1,i=h}}return{pathAt:s,refAt:r,count:o}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[s]).sequence,d=this.record(t[r]).sequence;for(;o<c.length&&i<d.length;){if(c[o]!==d[i])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[e.length-s-1]).sequence,d=this.record(t[t.length-r-1]).sequence;for(;o<c.length&&i<d.length;){if(c[c.length-o-1]!==d[d.length-i-1])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),r=this.pathLen(t),o=this.prefixMatches(e,t),i=this.suffixMatches(e,t);o+i>s&&(i=s-o),o+i>r&&(i=r-o),Z(n,"M",o),Xn(n,s-o-i,r-o-i),Z(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let r of e)n.has(r)&&(s+=this.record(r).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??As(yn(e,t,f=>this.record(f).sequenceLen)[0]),r=[],o=this.refPrefix(t),i=(f,p,w,u)=>{f===p?Z(r,"D",o[u]-o[w]):w===u?Z(r,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(w,u),r)},c=0,d=0,h=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],w=s.refAt[f];(d!==p||h!==w)&&i(d,p,h,w);let u=this.record(e[p]).sequenceLen;Z(r,"M",u),c+=u,d=p+1,h=w+1}return i(d,e.length,h,t.length),{edits:r,matched:c,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Te(n)&&(t.identity===void 0||!Te(De(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let r=De(t.path),o=this.sharedWeight(t.path,n);if(this.sharedWeight(r,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(o===0)s={...this.editsAgainst(r,n),flipped:!0};else{let c=this.editsAgainst(t.path,n),d=this.editsAgainst(r,n);s=d.matched>c.matched?{...d,flipped:!0}:{...c,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(h,f,p,w)=>{let u=Bs(h),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,S=x?.orientation==="forward",[I,N]=S?[l,b]:[b,l];return{strand:f,refStart:e.start+u.leading,refEnd:e.start+n-u.trailing,edits:u.edits,weight:l.weight,path:p.flatMap(y=>this.paths[y].path),start:nt(l,0),pieces:p,soloAligned:w,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+I.identity.hapStart,hapEnd:x.name.fragment+N.identity.hapEnd,walkForward:S}}},r=h=>h.soloAligned.reduce((f,p)=>f+p,0),o=h=>h.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=h=>2*r(h)>=o(h),c=h=>{let f=h[0],p=h[h.length-1],w=f.identity.walkForward;if(h.some((v,G)=>v.strand!==f.strand||v.identity.walkForward!==w||G>0&&v.identity.hapStart<h[G-1].identity.hapEnd))return;let u=w?h:[...h].reverse(),l=u.flatMap(v=>v.pieces),b=u.flatMap(v=>v.soloAligned),x=f.strand==="+"!==w,S=l.map(v=>this.paths[v]),I=S.slice(1).map((v,G)=>{let X=S[G].identity;return w?v.identity.hapStart-X.hapEnd:X.hapStart-v.identity.hapEnd}),N=x?[...S].reverse():S,y=x?[...I].reverse():I,E=N.flatMap(v=>x?De(v.path):v.path),{edits:R}=this.editsAgainst(E,t),F=Kn(R,N.map(v=>v.len)),T=new Map((x?[...l].reverse():l).map((v,G)=>[v,F[G]])),D=v=>2*v.pieces.reduce((G,X)=>G+T.get(X),0)>=r(v);if(!D(f)||!D(p))return;let O=[],H=0;return N.slice(0,-1).forEach((v,G)=>{H+=v.len,O.push([H,y[G]])}),s(Fs(R,O),f.strand,l,b)},d=[];return this.paths.forEach((h,f)=>{if(f===this.refId)return;let{edits:p,flipped:w}=this.alignment(f),u=h.identity,l=u?u.orientation==="forward"!==w:!w;d.push(s(p,l?"+":"-",[f],Kn(p,[h.len])))}),Ms(d,i,c).map(h=>{let{edits:f,identity:p,pieces:w,soloAligned:u,...l}=h,b={...l,cigar:Ts(f)};return p?{...b,resolved:!0,name:p.name,label:pe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,r=this.paths.flatMap(h=>{let{identity:f}=h;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:rt(h,f)}]:[]}),o=h=>f=>f.sample===h.sample&&f.haplotype===h.haplotype,i=o(t),c=n?o(n):h=>!i(h),d=h=>this.record(fe(h,"forward")).sequence;return r.filter(h=>i(h.name)).flatMap(h=>r.filter(f=>c(f.name)).flatMap(f=>bn({...s,query:f.steps,target:h.steps,sequenceOf:d}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:h.name,targetStart:h.start+p.targetStart,targetEnd:h.start+p.targetEnd,cigar:xn(p.edits),matches:p.edits.reduce((w,[u,l])=>w+(u==="="?l:0),0),columns:p.edits.reduce((w,[,u])=>w+u,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=fe(e,n);for(let r of this.record(s).successors())this.hasHandle(r)&&Fe(s,r)&&t.push([n==="reverse"?1:0,$(r),V(r)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!V(n)){let s=$(n),r=`S ${s} ${this.record(n).sequence}
|
|
2
2
|
`;for(let[o,i,c]of this.canonicalEdges(s))r+=`L ${s} ${o?"-":"+"} ${i} ${c?"-":"+"}
|
|
3
3
|
`;t.push(e.encode(r))}return jn(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,n=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...Gn(Dn(await this.stableName(),await this.db.graphName()))],s=this.sortedHandles();for(let d of s)V(d)||n.push(`S ${$(d)} ${this.record(d).sequence}`);let r=d=>V(d)?"-":"+";for(let d of s)for(let h of this.record(d).successors())this.hasHandle(h)&&Fe(d,h)&&n.push(`L ${$(d)} ${r(d)} ${$(h)} ${r(h)} 0M`);let o=(d,h,f,p,w)=>{let u=rt(d,h).map(x=>`${V(x)?"<":">"}${$(x)}`).join(""),l=d.weight===void 0?"":` WT:i:${d.weight}`,b=w===void 0?"":` CG:Z:${w}`;return`W ${f.sample} ${f.haplotype} ${f.contig} ${f.fragment} ${p} ${u}${l}${b}`},i=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.push(o(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let c=1;return this.paths.forEach((d,h)=>{if(h!==this.refId){let f=e.names!=="anonymous"?d.identity:void 0,p=t?this.alignToRef(h):void 0;n.push(f?o(d,f,{...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd,p):o(d,void 0,{sample:"unknown",contig:i,haplotype:c,fragment:0},d.len,p)),c+=1}}),`${n.join(`
|
|
4
4
|
`)}
|
|
@@ -6,4 +6,4 @@ import{a as fe,b as $,c as ke,d as V,e as ee,f as pn,g as Xe,h as Ye,i as un,j a
|
|
|
6
6
|
`).filter(f=>f!=="")),n=Ys(t.flat()),s=0,r=t.map(h=>{let f=wt(h,"W").map(Ks),p=s;for(let w of f.filter(u=>u.fields[1]===Zs)){let u=+w.fields[2]+p;w.fields[2]=String(u),w.name=w.fields.slice(1,4).join(" "),s=Math.max(s,u)}return f}),i=[...Sn([...r.flatMap(h=>h.slice(0,1)),...r.flatMap(h=>h.slice(1))],h=>h.name).values()].flatMap(h=>er(h,n,e)),c=new Set(t.flatMap(h=>wt(h,"L")));for(let h of i)for(let f of h.seams.map(tr))!c.has(f.forward)&&!c.has(f.reverse)&&c.add(f.forward);return`${[...new Set([...wt(t[0],"H"),...t.flatMap(h=>wt(h,"S")),...c,...i.map(h=>h.fields.join(" "))])].join(`
|
|
7
7
|
`)}
|
|
8
8
|
`}var jt=class extends Error{constructor(a,e){super(e.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${a}" maps to none; set referenceSample`:`the anchor "${a}" is none of the graph's reference samples (${e.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`),this.name="NoReferenceSampleError"}},mt=class extends Error{constructor(a,e,t){super(`this ${e.toLocaleString()} bp window reads more than nodeLimit (${a.toLocaleString()}) graph nodes; zoom in to about ${t.toLocaleString()} bp or raise nodeLimit`),this.fitsBp=t,this.name="NodeLimitError",this.regionTooLarge=!0}};function ce(a){return`${a.sample}#${a.haplotype}`}function yt(a,e){let t=ce(a);return e===void 0||e.some(n=>Ae(t,n))}async function bt(a){return(await a.tag("gbwt_reference_samples")??"").split(/\s+/).filter(e=>e!=="")}function Ut(a,e){let t=a.toLowerCase(),n=In(a)?.toLowerCase();return e.find(s=>s===a)??e.find(s=>s.toLowerCase()===t)??e.find(s=>s.toLowerCase()===n)}function Wt({configured:a,anchorPrefix:e,referenceSamples:t}){if(a!=="")return a;let n=Ut(Rt(e),t)??(t.length===1?t[0]:void 0);if(n===void 0)throw new jt(e,t);return n}async function xt(a,e,t){let n=(await a.paths()).find(s=>s.isIndexed&&s.name.sample===e&&s.name.contig===t);return n?{sample:n.name.sample,contig:t,haplotype:n.name.haplotype}:void 0}function St(a,e,t){if(a instanceof Error&&(a.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(a.message))){let s="walkedBp"in a?a.walkedBp:void 0,r=typeof s=="number"&&s>0?Math.floor(s*.8):Math.floor(t/2);return new mt(e,t,Math.max(r,1))}else return}async function nr(a,e,t,n,s){return a.getSubgraphs({...s,path:e,start:t,end:n,haplotypes:"all"}).catch(r=>{throw St(r,s.limit,n-t)??r})}async function sr(a,e){let t=await a.paths();return cs(await Promise.all(e.map(n=>n.toGFA())),(n,s,r,o)=>t.some(({name:i})=>i.sample===n&&i.haplotype===s&&i.contig===r&&i.fragment===o))}async function Qt(a,e,t,n,s){if(!e)return"";let r=await nr(a,e,t,n,s);if(r.length===1)return hs(r[0].toCompactSubgraph());let o=await sr(a,r),i=o===""?void 0:kn(o);return i?{...i,revisited:Number.NaN}:o}function rr(a,e){let t=1/0,n=-1/0;for(let i of a)t=Math.min(t,i),n=Math.max(n,i);let s=n-t+1,r=a.length>0&&s<=16*a.length?new Int32Array(s).fill(-1):void 0,o=new Map;return a.forEach((i,c)=>{r?r[i-t]=c:o.set(i,c)}),i=>{let c=$(i),d=r!==void 0&&c>=t&&c<=n,h=d?r[c-t]:o.get(c)??-1;return h>=0?h:(d?r[c-t]=e.length:o.set(c,e.length),e.push(String(c)),e.length-1)}}var or=/^(.*)\[(\d+)-(\d+)\]$/;function hs(a){let e=Array.from(a.nodeIds,String),t=rr(a.nodeIds,e),n=a.nodeIds.length,s=a.edges.length/2,r=new Int32Array(s),o=new Int32Array(s),i=new Uint8Array(s);for(let l=0;l<s;l++){let b=a.edges[2*l],x=a.edges[2*l+1];r[l]=t(b),o[l]=t(x),i[l]=(V(b)?1:0)|(V(x)?2:0)}let c=a.paths.filter(l=>l.steps.length>0),d=new Int32Array(c.length+1);c.forEach((l,b)=>{d[b+1]=d[b]+l.steps.length});let h=new Int32Array(d[c.length]),f=new Uint8Array(h.length),p=new Float64Array(c.length),w=new Float64Array(c.length),u=c.map((l,b)=>{let x=or.exec(l.name);p[b]=x?+x[2]:0,w[b]=x?+x[3]:-1;let S=d[b];for(let I of l.steps)h[S]=t(I),f[S++]=V(I)?1:0;return x?x[1]:l.name});return{nodes:{names:e,lengths:Int32Array.from(a.nodeSequences,l=>l.length),refs:new Int32Array(n).fill(-1),starts:new Float64Array(n),ranks:new Int32Array(n),refNames:[]},links:{from:r,to:o,strands:i},walks:{names:u,starts:p,ends:w,offsets:d,steps:h,reversed:f},departures:En(),revisited:Number.NaN}}function It(a){let e=/\.gbz\.db$/i;return e.test(a)?a.replace(e,".haplotype-index.db"):void 0}function cr(a){return fn(a)&&It(dn(a))?ln(a,e=>It(e)):void 0}function hr(a){return a instanceof Error&&(/\bHTTP 40[34]\b/.test(a.message)||a.code==="ENOENT")}async function ds(a,e){let t=cr(a);if(!t)return{};try{return await $e(t,e).stat(),{location:t}}catch(n){return hr(n)?{}:{unreadable:String(n)}}}var dr=5e3,fr=50*2**20,Vt=class extends Error{constructor(t){super(`this GAF is ${(t/2**20).toFixed(0)} MB without an index; bgzip it and index it with tabix -p gaf`);this.name="UnindexedGafTooLargeError"}};function lr(a,e){if(a.length<=e)return a;let t=a.length/e;return Array.from({length:e},(n,s)=>a[Math.floor(s*t)])}var fs=(a,e)=>a.path.some(t=>e.has(t.name)),Et=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=_e({setup:async({signal:e})=>{let{size:t}=await this.file.stat();if(t>fr)throw new Vt(t);let n=await this.file.readFile({signal:e}),s=new TextDecoder().decode(n[0]===31&&n[1]===139?await Pn(n):n);return Mt(s)}})}async readIndexed(e,t,n){let s=1/0,r=-1/0;for(let i of t){let c=Number(i);Number.isInteger(c)&&(s=Math.min(s,c),r=Math.max(r,c))}let o=[];return s<=r&&await e.getLines("{node}",s,r+1,{signal:n,lineCallback:i=>{let c=Lt(i);c&&fs(c,t)&&o.push(c)}}),o}async readsOver(e,{signal:t}={}){let n=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(s=>fs(s,e));return{records:lr(n,dr),total:n.length}}};var kt=class extends Error{constructor(t){super(t===void 0?"no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation":`the haplotype index beside the graph database could not be checked (${t}), so the walks cannot be named; if it is there, reload to try again, or set haplotypeIndexLocation`);this.name="NoHaplotypeIndexError"}},Zt=class extends Error{constructor(t,n){super(`the graph is cut on its reference, ${n}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${n} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function pr(a,e){return`${ce(a)}#${a.contig}@${e.start.node}.${e.start.offset}`}function ur({alignment:a,assemblyName:e,refName:t,lane:n}){let{refStart:s,refEnd:r,strand:o,cigar:i}=a;if(!(r<=s)){let{name:c,hapStart:d,hapEnd:h}=a,f=pr(c,a),p={uniqueId:f,assemblyName:e,refName:t,start:s,end:r,type:"match",strand:o==="-"?-1:1,CIGAR:i,syntenyId:f,mate:{refName:c.contig,start:d,end:h,assemblyName:n}};return new Rn(p)}}function gr({pair:a,lane:e,mateLane:t}){return Cn({target:{name:`${ce(a.target)}#${a.target.contig}`,assemblyName:e,refName:a.target.contig,start:a.targetStart,end:a.targetEnd},query:{name:`${ce(a.query)}#${a.query.contig}`,assemblyName:t,refName:a.query.contig,start:a.queryStart,end:a.queryEnd},strand:a.strand,cigar:a.cigar,matches:a.matches,columns:a.columns})}var wr=12e4;function mr(a,e){let t=new Map;for(let s of a)for(let{name:r,start:o,end:i}of s.walkSpans()){let c=ce(r);if(e.has(c)){let d=`${c}#${r.contig}`,h=t.get(d);h?h.push([o,i]):t.set(d,[[o,i]])}}let n=0;for(let s of t.values()){s.sort((r,o)=>r[0]-o[0]);for(let r=1;r<s.length;r++){let o=s[r][0]-s[r-1][1];o>0&&o<=wr&&(n=Math.max(n,o))}}return n}function us(a,e){return a instanceof mt&&(a.message=`Zoom in to about ${hn(a.fitsBp)} to see ${e}`),a}var ls=(a,e,t)=>Hn(us(St(a,e,t)??a,"lanes"),t),ps=a=>({...a,start:Math.floor(a.start),end:Math.ceil(a.end)}),Kt=class extends $n{constructor(){super(...arguments);this.graph=_e({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),n=this.getConf("haplotypeIndexLocation"),s=Ke(n)?{location:n}:await ds(t,this.pluginManager),r=s.location,o=await Qe.open({source:$e(t,this.pluginManager),haplotypeIndex:r?$e(r,this.pluginManager):void 0}),i=this.getConf("assemblyNames")[0];if(i===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let c=await bt(o),d=Wt({configured:this.getConf("referenceSample"),anchorPrefix:Re(this,i),referenceSamples:c});return{db:o,anchor:i,referenceSample:d,referenceSamples:c,unreadableIndex:s.unreadable}}});this.gaf=_e({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),n=this.getConf(["readsIndex","location"]);return Ke(t)?new Et($e(t,this.pluginManager),Ke(n)?An(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,n){let{db:s,referenceSample:r}=await this.graph(n);return xt(s,r,t)}async getHaplotypes(t={}){let{db:n,referenceSamples:s}=await this.graph(t),r=new Map;for(let o of await n.paths()){let i=ce(o.name),c=r.get(i);c?c.contigs.includes(o.name.contig)||c.contigs.push(o.name.contig):r.set(i,{prefix:i,sample:o.name.sample,haplotype:o.name.haplotype,contigs:[o.name.contig],isReference:s.includes(o.name.sample)})}return[...r.values()]}async getHeader(t={}){let{anchor:n,referenceSample:s}=await this.graph(t),r=$t(this),o=[];for(let i of await this.getHaplotypes(t))i.sample!==s&&o.push({name:Ht(r,i.prefix),label:i.prefix,group:i.sample});return{hasCoarseTier:!1,anchorAssemblyName:n,lanes:o}}async getRefNames(t={}){let{db:n,anchor:s,referenceSample:r}=await this.graph(t),{assemblyName:o}=t,i=o===s?void 0:Re(this,o),c=(await n.paths()).filter(d=>o===s?d.isIndexed&&d.name.sample===r:Ae(ce(d.name),i)).map(d=>d.name.contig);return[...new Set(c)]}keepPredicate(t,n){let s=t===void 0||t.length===0?void 0:t.map(r=>Re(this,r));return s===void 0&&n===void 0?void 0:r=>yt(r,s)&&(n===void 0||Ae(ce(r),n))}async getSubgraph(t,n={}){let{signal:s}=n,{db:r,anchor:o,referenceSample:i,unreadableIndex:c}=await this.graph({signal:s}),{assemblyName:d,refName:h,start:f,end:p}=ps(t);if(d!==o)throw new Zt(d,o);let w=await this.referenceQuery(h,{signal:s});if(!w)throw new Error(`${i} has no indexed path ${h} in this graph`);let u=this.keepPredicate(n.haplotypes);if(u!==void 0&&!r.hasHaplotypeIndex)throw new kt(c);let l=await Qt(r,w,f,p,{context:this.getConf("context"),snarls:n.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:n.signal,keep:u}).catch(b=>{throw us(b,"the graph")});return typeof l=="string"?l:Nn(l,{start:f,end:p},n.walkRows)}async getReads(t,n={}){let s=await this.gaf(n);return s?s.readsOver(new Set(t),n):{records:[],total:0}}async laneHaplotypes(t,n){let s=Re(this,t);return(await this.getHaplotypes(n)).filter(r=>Ae(r.prefix,s))}async anchorFeatures(t,n){let{db:s}=await this.graph(n),{assemblyName:r,refName:o,start:i,end:c}=t,d=Re(this,n.targetAssemblyName),h=$t(this),f=this.keepPredicate(n.haplotypes,d),p=await this.referenceQuery(o,n),w=this.getConf("nodeLimit");return(p?await At(`Reading graph ${o}:${i.toLocaleString()}-${c.toLocaleString()}`,n.statusCallback,()=>s.getAlignments({path:p,start:i,end:c,context:this.getConf("context"),haplotypes:"all",limit:w,signal:n.signal,keep:f}).catch(l=>{throw ls(l,w,c-i)})):[]).flatMap(l=>{let b=l.resolved?ur({alignment:l,assemblyName:r,refName:o,lane:Ht(h,ce(l.name))}):void 0;return b===void 0?[]:[b]})}async pairFeatures(t,n,s){let{db:r}=await this.graph(s),{refName:o,start:i,end:c}=t,h=(await Promise.all(n.map(async S=>({pair:S,featureSide:await this.laneHaplotypes(S.queryAssemblyName,s),mateSide:await this.laneHaplotypes(S.targetAssemblyName,s)})))).filter(({featureSide:S,mateSide:I})=>S.length>0&&I.length>0),f=new Set(h.flatMap(({featureSide:S,mateSide:I})=>[...S,...I].map(ce))),p=await this.referenceQuery(o,s),w=this.getConf("nodeLimit"),u=this.getConf("context"),l=(S,I)=>r.getSubgraphs({path:S,start:i,end:c,context:I,snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:w,signal:s.signal,keep:N=>f.has(ce(N))}),b=async S=>{let I=await l(S,u).catch(E=>{throw ls(E,w,c-i)}),N=mr(I,f),y=Math.ceil(N/2)+2e3;return N>0&&y>u?l(S,y).catch(E=>{if(E instanceof ae)return I;throw E}):I};return(p&&h.length>0?await At(Mn(n),s.statusCallback,()=>b(p)):[]).flatMap(S=>h.flatMap(({pair:I,featureSide:N,mateSide:y})=>N.flatMap(E=>y.flatMap(R=>S.pairAlignments({target:E,query:R,bases:!1}).map(F=>gr({pair:F,lane:I.queryAssemblyName,mateLane:I.targetAssemblyName}))))))}getFeatures(t,n={}){let s=ps(t);return vn(async r=>{let{db:o,anchor:i,unreadableIndex:c}=await this.graph(n);if(!o.hasHaplotypeIndex)throw new kt(c);if(s.assemblyName===i){let d=Ln(n),h=d.length>0?await this.pairFeatures(s,d,n):await this.anchorFeatures(s,n);for(let f of h)r.next(f)}r.complete()},n.signal)}};export{kt as NoHaplotypeIndexError,bs as PairTargetError,Kt as default,mr as widestWalkGap};
|
|
9
|
-
//# sourceMappingURL=GbzBaseSyntenyAdapter-
|
|
9
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-5CIIRXKR.js.map
|