jbrowse-plugin-graphgenomeviewer 6.9.1 → 6.9.2
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/dist/chunks/RgfaTabixAdapter-KOIMYOR3.js +4 -0
- package/dist/chunks/RgfaTabixAdapter-KOIMYOR3.js.map +7 -0
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +1 -1
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +2 -2
- package/package.json +1 -1
- package/src/RgfaTabixAdapter/RgfaTabixAdapter.test.ts +12 -0
- package/src/RgfaTabixAdapter/RgfaTabixAdapter.ts +52 -21
- package/src/RgfaTabixAdapter/configSchema.ts +12 -9
- package/src/RgfaTabixAdapter/test_data/walks_maxnode.links.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/walks_maxnode.links.bed.gz.tbi +0 -0
- package/src/RgfaTabixAdapter/test_data/walks_maxnode.nodes.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/walks_maxnode.nodes.bed.gz.tbi +0 -0
- package/src/RgfaTabixAdapter/test_data/walks_maxnode.walks.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/walks_maxnode.walks.bed.gz.tbi +0 -0
- package/src/RgfaTabixAdapter/walkFiles.test.ts +74 -0
- package/src/RgfaTabixAdapter/walkRows.test.ts +30 -0
- package/src/RgfaTabixAdapter/walkRows.ts +31 -15
- package/src/version.ts +1 -1
- package/dist/chunks/RgfaTabixAdapter-2CIFHOB3.js +0 -4
- package/dist/chunks/RgfaTabixAdapter-2CIFHOB3.js.map +0 -7
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as ge,b as he,d as $,e as z}from"./chunk-BFBKRNH4.js";import{g as B}from"./chunk-OEU2V7TV.js";import"./chunk-6AWRYNB2.js";import"./chunk-KWAXLUPQ.js";import"./chunk-YBLNN5FU.js";import{c as Z,e as A,f as G}from"./chunk-7QEJLDYY.js";import{a as j}from"./chunk-J4OLMLS5.js";import{b as R}from"./chunk-FY3BTKY4.js";var M=R(ge(),1),F=R(j(),1),le=R(he(),1);function I(s){let t=s.split(" "),e=t.length>=8,n=e?5:0;return{anchored:e,segment:{refName:t[n],start:+t[n+1],end:+t[n+2],id:t[3],rank:+t[4],tags:t[e?8:5]??""}}}function U(s){let t=s.tags.split(" ").find(n=>n.startsWith("SM:Z:"));if(t===void 0)return;let e=t.slice(5).split(",").map(n=>n.trim()).filter(Boolean);return e.length>0?e:void 0}function D(s){return{id:s.slice(0,-1),strand:s.slice(-1)}}function W(s){let t=s.split(" "),e=D(t[3]),n=D(t[4]);return{source:e.id,sourceStrand:e.strand,target:n.id,targetStrand:n.strand,sourceSegment:{id:e.id,refName:t[5],start:+t[6],end:+t[7],rank:+t[8],tags:t[13]??""},targetSegment:{id:n.id,refName:t[9],start:+t[10],end:+t[11],rank:+t[12],tags:t[14]??""}}}function y(s){return`${s.source}${s.sourceStrand}${s.target}${s.targetStrand}`}function _(s,t,e){let n=i=>i.rank!==0||i.refName!==e.refName?0:i.end<=e.start?-1:i.start>=e.end?1:0,r=new Map(s),a=new Map;for(let i of t)if(s.has(i.source)||s.has(i.target)||n(i.sourceSegment)*n(i.targetSegment)===-1){a.set(y(i),i);for(let o of[i.sourceSegment,i.targetSegment])r.has(o.id)||r.set(o.id,o)}for(let i of t)r.has(i.source)&&r.has(i.target)&&a.set(y(i),i);return{segments:r,links:a}}function K(s,t,e){let n=r=>r.refName!==e.refName||r.end<=e.start||r.start>=e.end;return[...Q(s.filter(r=>r.rank>0),t,e.end-e.start),...Q(s.filter(r=>r.rank===0&&n(r)),new Set(s.map(r=>r.id)),0)]}function Q(s,t,e){let n=[...s].sort((a,i)=>L(a.refName,i.refName)||a.start-i.start),r=[];for(let a of n){let i=r.at(-1);i?.refName===a.refName&&a.start-i.end<=e?(i.needed||=a.start>i.end||t.has(a.id),i.end=Math.max(i.end,a.end)):r.push({refName:a.refName,start:a.start,end:a.end,needed:t.has(a.id)})}return r.filter(a=>a.needed).map(({refName:a,start:i,end:o})=>({refName:a,start:i,end:o}))}function V(s,t,e){let n=r=>t.has(r.id)||e.some(a=>a.refName===r.refName&&r.start>=a.start&&r.end<=a.end);return s.filter(r=>n(r.sourceSegment)&&n(r.targetSegment))}var ke=/^[A-Za-z][A-Za-z0-9]:[AifZJHB]:/;function be(s){let{id:t,refName:e,start:n,end:r,rank:a,tags:i}=s,o=i.split(" ").filter(l=>ke.test(l)),f=o.length===0?"":` ${o.join(" ")}`;return`S ${t} * LN:i:${r-n} SN:Z:${e} SO:i:${n} SR:i:${a}${f}`}function Se(s){let{source:t,sourceStrand:e,target:n,targetStrand:r}=s;return`L ${t} ${e} ${n} ${r} 0M`}function L(s,t){return s<t?-1:s>t?1:0}function O(s,t){let e=[...s.values()].sort((r,a)=>L(r.refName,a.refName)||r.start-a.start||L(r.id,a.id)),n=[...t.keys()].sort((r,a)=>L(r,a));return["H VN:Z:1.0",...e.map(r=>be(r)),...n.map(r=>Se(t.get(r)))].join(`
|
|
2
|
+
`)}var T=R(j(),1);function ee(s){let t=-1;for(let e=0;e<3;e++)t=s.indexOf(" ",t+1);return s.slice(t+1,s.indexOf(" ",t+1))}function te(s){let t=s.split(" ",9);return{chunkStart:+t[1],name:t[3],fragStart:+t[4],hapOffset:+t[5],piece:+t[6],n:+t[7],enc:t[8]}}function J(s,t){let e=new RegExp(`(?:^|\\t)${t}:i:(\\d+)`).exec(s);return e?+e[1]:void 0}function ne(s){let t={references:[],haplotypes:[]};for(let e of s){let[n,r=""]=e.split(" ");n==="#reference"?t.references.push(r):n==="#haplotype"?t.haplotypes.push(r):(t.chunk??=J(e,"chunk"),t.maxNode??=J(e,"maxnode"))}return t}function re(s,t){return s===void 0?1:Math.max(1,Math.ceil(s/t))}function P(s,t,e=1){return Math.max(0,(Math.floor(s/t)-e)*t)}function ae(s,t){return s===void 0||s.length===0?void 0:e=>A(e,t)||s.some(n=>A(e,n))}function we(s,t,e=new Int32Array(t),n=new Uint8Array(t),r=0){let a=0,i=r,o=0,f=!1;for(let l=0;l<=s.length;l++){let c=l<s.length?s.charCodeAt(l):44;if(c===44){let u=f?-o:o,d=u&1;n[i]=d,a+=(u-d)/2,e[i++]=a,o=0,f=!1}else c===45?f=!0:o=o*10+(c-48)}return{ids:e,rev:n}}function se(s){let t=new Map;for(let n of s){let r=`${n.name} ${n.fragStart}`,a=t.get(r);a?a.push(n):t.set(r,[n])}let e=[];for(let n of t.values()){n.sort((a,i)=>a.piece-i.piece);let r=0;for(let a=1;a<=n.length;a++)(a===n.length||n[a].piece!==n[a-1].piece+1)&&(e.push(xe(n.slice(r,a))),r=a)}return e}function xe(s){let t=s.reduce((a,i)=>a+i.n,0),e=new Int32Array(t),n=new Uint8Array(t),r=0;for(let a of s)we(a.enc,a.n,e,n,r),r+=a.n;return{name:s[0].name,hapOffset:s[0].hapOffset,ids:e,rev:n}}function oe(s,t){let e=o=>o?.onWindow===!0,n=new Set;for(let[o,f]of t)f.onWindow&&n.add(o);let r=[];for(let o of s){let{ids:f}=o,l=-1,c=-1;for(let u=0;u<f.length;u++)e(t.get(f[u]))&&(l<0&&(l=u),c=u);if(l>=0){for(let u=l;u<=c;u++)n.add(f[u]);r.push({run:o,first:l,last:c})}}let a=o=>{let f=t.get(o);return f===void 0?0:f.end-f.start},i=[];for(let{run:o,first:f,last:l}of r){let{ids:c,rev:u}=o,d=f,p=l;for(;d>0&&n.has(c[d-1]);)d--;for(;p<c.length-1&&n.has(c[p+1]);)p++;let h=o.hapOffset;for(let m=0;m<d;m++)h+=a(c[m]);let g=h;for(let m=d;m<=p;m++)g+=a(c[m]);i.push({name:o.name,hapStart:h,hapEnd:g,ids:c.subarray(d,p+1),rev:u.subarray(d,p+1)})}return{kept:n,fragments:i}}function Ne({name:s,hapStart:t,hapEnd:e,ids:n,rev:r}){let[a,i,...o]=s.split("#"),f=new Array(n.length);for(let l=0;l<n.length;l++)f[l]=(r[l]?"<":">")+n[l];return`W ${a} ${i} ${o.join("#")} ${t} ${e} ${f.join("")}`}function X(s,t,e){let n=-1;for(let r=0;r<t;r++)n=n===-1&&r>0?-1:s.indexOf(" ",n+1),e[r]=n;return e}var v=class{constructor(t){this.window=t;this.nodes=new Map;this.links=[];this.t=[]}addNode(t){let e=X(t,8,this.t),n=+t.slice(e[2]+1,e[3]);if(!this.nodes.has(n)){let r=+t.slice(e[3]+1,e[4]),a=t.slice(e[4]+1,e[5]),i=+t.slice(e[5]+1,e[6]),o=+t.slice(e[6]+1,e[7]===-1?void 0:e[7]),{window:f}=this;this.nodes.set(n,{rank:r,refName:a,start:i,end:o,onWindow:r===0&&a===f.refName&&o>f.start-f.context&&i<f.end+f.context})}}addLink(t){let e=X(t,5,this.t);this.links.push(Y(t,e[2]+1,e[3]),Y(t,e[3]+1,e[4]===-1?t.length:e[4]))}format(t,e){let n=[];for(let o of t){let f=this.nodes.get(o);f&&n.push({...f,id:o})}n.sort((o,f)=>o.refName<f.refName?-1:o.refName>f.refName?1:o.start-f.start||o.id-f.id);let r=["H VN:Z:1.1"];for(let{id:o,refName:f,start:l,end:c,rank:u}of n)r.push(`S ${o} * LN:i:${c-l} SN:Z:${f} SO:i:${l} SR:i:${u}`);let a=new Set,i=[];for(let o=0;o<this.links.length;o+=2){let f=this.links[o],l=this.links[o+1],c=Math.floor(f/2),u=Math.floor(l/2);if(t.has(c)&&t.has(u)){let d=`L ${c} ${f%2?"-":"+"} ${u} ${l%2?"-":"+"} 0M`;a.has(d)||(a.add(d),i.push(d))}}return i.sort(),[...r,...i,...this.referenceFirst(e).map(Ne)].join(`
|
|
3
|
+
`)}referenceFirst(t){let{refName:e}=this.window;return[...t].sort((n,r)=>+(r.name===e)-+(n.name===e)||(n.name<r.name?-1:n.name>r.name?1:n.hapStart-r.hapStart))}};function Y(s,t,e){return+s.slice(t,e-1)*2+(s.charCodeAt(e-1)===45?1:0)}function ie(s,t,e,n,r){let a=0,i=new Map,o=new Set;for(let p of s)a+=p.n,i.set(p.chunkStart,(i.get(p.chunkStart)??0)+p.n),o.add(p.name);if(a<=t)return;let f=e.end-e.start,l=0,c=0;for(let p of[...i.keys()].sort((h,g)=>h-g)){if(l+=i.get(p),l>t)break;c=Math.max(c,p+n-e.start)}let u=!r&&o.size>2&&2*a/o.size<=t,d=new B(t,f,Math.max(c,1));return d.message=c>0?`Zoom in to about ${(0,T.getBpDisplayStr)(c)}${u?", or choose fewer haplotypes,":""} to see the graph`:`Too many haplotype steps here to draw ${r?"these haplotypes":"every haplotype"} (${l.toLocaleString()} against walkStepBudget ${t.toLocaleString()}); choose fewer haplotypes`,d}async function fe(s,t,e,n){let r=await s(e.end);if(r<=t)return;let a=0,i;for(let l=Math.floor(e.start/n)*n;l<e.end;l+=n){let c=await s(l+1);if(i??=c,c>t)break;a=l+n-e.start}let o=e.end-e.start,f=new B(t,o,Math.max(a,1));return f.message=a>0?`Zoom in to about ${(0,T.getBpDisplayStr)(a)} to see the graph`:`Too much graph here to fetch (${q(i??r)} against walkByteBudget ${q(t)})`,f}var q=s=>`${(s/1e6).toFixed(1)} MB`;function ce(s){return s.filter(t=>t.rank>0)}function me(s,t,e){if(!Number.isFinite(t)||!Number.isFinite(e))throw new Error(`${s}:${t}-${e} is not a finite range to query the graph's index for`)}async function x(s,t,e,n,r){return me(t,e,n),s.getLines(t,e,n,r)}var ye=1e3,H=class extends M.BaseFeatureDataAdapter{constructor(e,n,r){super(e,n,r);this.walkHeader=(0,M.cachedSetup)({setup:async e=>{let n=this.fine.walks,r=ne(n?await n.getHeaderLines(e):[]),a=this.getConf("walkChunk"),i=r.chunk??a;return{...r,chunk:i,lookback:re(r.maxNode,i)}}});this.fine=this.openIndex([])}static{this.capabilities=["getFeatures","getRefNames"]}openIndex(e){let n=$(this,[...e,"segmentsLocation"],[...e,"segmentsIndex"]),r=this.getConf("walksLocation"),a=e.length===0&&(!("uri"in r)||r.uri!=="");return{segments:n,links:$(this,[...e,"linksLocation"],[...e,"linksIndex"]),walks:a?$(this,["walksLocation"],["walksIndex"]):void 0,refNames:new z(n,this)}}async walkQueryStart(e,n){let{chunk:r,lookback:a}=await this.walkHeader(n);return P(e,r,a)}async getHaplotypeNames(e={}){if(!this.fine.walks)return;let{haplotypes:n}=await this.walkHeader(e);return n.length>0?n:void 0}index(e="fine"){return e==="fine"?this.fine:(this.coarse??=this.openIndex(["coarse"]),this.coarse)}async getRefNames(e={}){return this.fine.refNames.assemblyRefNames(e)}async hasDataForRefName(){return!0}getFeatures(e,n={}){let{signal:r,statusCallback:a}=n;return(0,le.ObservableCreate)(async i=>{let o=await this.fine.refNames.resolve(e,n);if(o!==void 0){let f=this.fine.walks?await this.walkQueryStart(e.start,n):e.start;await(0,F.updateStatus)("Downloading segments",a,()=>x(this.fine.segments,o,f,e.end,{signal:r,lineCallback:l=>{let{segment:c,anchored:u}=I(l);if(u&&c.refName!==o)return;let d=U(c);i.next(new F.SimpleFeature({uniqueId:c.id,refName:e.refName,start:c.start,end:c.end,name:c.id,type:"segment",rank:c.rank,stableName:c.refName,...d&&{samples:d,sampleCount:d.length}}))}}))}i.complete()},r)}async getSubgraph(e,n={}){let{hops:r=0,signal:a,tier:i}=n,o=this.index(i),f=new Map,l=new Map,c=await o.refNames.resolve(e,{signal:a}),u=async(h,g,m)=>{let b=[];return await x(o.links,h,g,m,{signal:a,lineCallback:N=>{let S=W(N);l.set(y(S),S);for(let w of[S.sourceSegment,S.targetSegment])f.has(w.id)||(f.set(w.id,w),b.push(w))}}),b};if(c===void 0)throw new Error(`${e.assemblyName} ${e.refName} is not in this graph's index; a graph with PanSN names (GRCh38#0#chr1) needs ${e.assemblyName} mapped to its prefix in assemblyNameToPanSN`);if(o.walks)return this.walkSubgraph(o,o.walks,c,e,n);let d={anchored:!1};if(await x(o.segments,c,e.start,e.end,{signal:a,lineCallback:h=>{let g=I(h);d.anchored||=g.anchored,f.set(g.segment.id,g.segment)}}),d.anchored){let h=[];await x(o.links,c,e.start,e.end,{signal:a,lineCallback:m=>{h.push(W(m))}});let g=_(f,h,{refName:c,start:e.start,end:e.end});return O(g.segments,g.links)}let p=ce(await u(c,e.start,e.end));for(let h=0;h<r;h++){let g=await Promise.all(p.map(m=>u(m.refName,m.start,m.end)));p=ce(g.flat())}if(r>0){let h=K([...f.values()],new Set(p.map(m=>m.id)),{refName:c,start:e.start,end:e.end}),g=[];await Promise.all(h.map(m=>x(o.links,m.refName,m.start,m.end,{signal:a,lineCallback:b=>{g.push(W(b))}})));for(let m of V(g,f,h)){l.set(y(m),m);for(let b of[m.sourceSegment,m.targetSegment])f.has(b.id)||f.set(b.id,b)}}return O(f,l)}async walkSubgraph(e,n,r,a,i){let{signal:o,haplotypes:f}=i,{chunk:l,lookback:c}=await this.walkHeader({signal:o}),u=this.getConf("walkStepBudget"),d=ae(f?.map(k=>G(this,k)),Z(r)),p=P(a.start,l,c),h=[n,e.segments,e.links],g=await fe(async k=>(me(r,p,k),(await Promise.all(h.map(C=>C.bytesForRegions([{refName:r,start:p,end:k}],{signal:o})))).reduce((C,pe)=>C+pe,0)),this.getConf("walkByteBudget"),a,l);if(g)throw g;let m=new AbortController,b=()=>{m.abort(o?.reason)};o?.addEventListener("abort",b,{once:!0});let N=[],S=new v({refName:r,start:a.start,end:a.end,context:ye}),w=(k,E)=>x(k,r,p,a.end,{signal:m.signal,lineCallback:E});try{await Promise.all([w(n,k=>{(d===void 0||d(ee(k)))&&N.push(te(k))}).then(()=>{let k=ie(N,u,a,l,d!==void 0);if(k)throw k}),w(e.segments,k=>{S.addNode(k)}),w(e.links,k=>{S.addLink(k)})])}catch(k){throw m.abort(),k}finally{o?.removeEventListener("abort",b)}let{kept:ue,fragments:de}=oe(se(N),S.nodes);return S.format(ue,de)}};export{H as default};
|
|
4
|
+
//# sourceMappingURL=RgfaTabixAdapter-KOIMYOR3.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/RgfaTabixAdapter/RgfaTabixAdapter.ts", "../../src/RgfaTabixAdapter/rgfaBed.ts", "../../src/RgfaTabixAdapter/walkRows.ts"],
|
|
4
|
+
"sourcesContent": ["import { panSNHaplotype, resolvePanSNPrefix } from '@jbrowse/bandage-core/pansn'\nimport {\n BaseFeatureDataAdapter,\n cachedSetup,\n} from '@jbrowse/core/data_adapters/BaseAdapter'\nimport { SimpleFeature, updateStatus } from '@jbrowse/core/util'\nimport { ObservableCreate } from '@jbrowse/core/util/rxjs'\n\nimport { PanSNRefNames, openTabixSlot } from '../panSNTabix.ts'\nimport {\n anchoredCut,\n closingLinks,\n closingSpans,\n formatSubgraph,\n linkKey,\n parseLinkLine,\n parseSegmentRow,\n segmentSamples,\n} from './rgfaBed.ts'\nimport {\n WalkGraph,\n byteBudgetError,\n chunkQueryStart,\n joinPieces,\n lookbackChunks,\n parseWalkRow,\n stepBudgetError,\n walkCut,\n walkHeader,\n walkNameFilter,\n walkRowName,\n} from './walkRows.ts'\n\nimport type { RgfaTabixAdapterConfig } from './configSchema.ts'\nimport type { WalkRow } from './walkRows.ts'\nimport type { SubgraphAdapterOptions, SubgraphTier } from '../GetSubgraph.ts'\nimport type { RgfaLink, RgfaSegment } from './rgfaBed.ts'\nimport type { TabixIndexedFile } from '@gmod/tabix'\nimport type PluginManager from '@jbrowse/core/PluginManager'\nimport type { BaseOptions } from '@jbrowse/core/data_adapters/BaseAdapter'\nimport type { getSubAdapterType } from '@jbrowse/core/data_adapters/dataAdapterCache'\nimport type { Feature } from '@jbrowse/core/util'\nimport type { FileLocation, Region } from '@jbrowse/core/util/types'\n\n// What a hop follows: alleles, never the backbone. A rank-0 segment reached\n// through a link is flanking backbone, usually outside the window, so querying\n// its links walks the reference away from the region, brings back more backbone,\n// and closes nothing. Every segment that closes a bubble is an allele interior,\n// and an allele interior is rank > 0 in both index formats (rGFA's SR tag, and\n// pggb's rank 0-or-1 against the anchor path). Reached backbone still becomes a\n// node and its edge still draws; it is only not walked through.\n//\n// This is gfabase's rule, arrived at from the other end. `gfabase sub` expands\n// from a seed either to the whole connected component (`--connected`, which its\n// own README calls overkill) or with `--cutpoints 1`, which takes the biconnected\n// component by *stopping at cutpoints*, the segments every end-to-end walk of\n// the chromosome must traverse. In a reference-anchored pangenome the cutpoints\n// are the backbone, and rank is what the index already states about it, so\n// `rank > 0` is that stopping rule without a connectivity index to build. The\n// third tool is the same shape again: `gfatools view -R` maps the region onto its\n// precomputed bubble decomposition and returns whole overlapping bubbles\n// (gfa_query_by_reg), which is complete for the same reason. Bandage's own\n// `--distance` is a node-step radius, but Bandage holds the entire graph in\n// memory, so its scope is a drawing filter rather than a fetch strategy.\n//\n// Measured with this rule: the E. coli paa window converges at one hop (17\n// segments at 1 and at 2), so the cut closes and stays closed. HPRC's amylase\n// window keeps growing (63 at 0, 78 at 1, 92 at 2) because its alleles have\n// alleles, and wall-clock is flat across all three, since a hop's queries go out\n// together and the remote index dominates.\n//\n// The exact version, when a graph ships a bubble index beside its segments:\n// gfatools' bubble rows carry the member segment ids of every bubble, so the\n// bubbles overlapping the region state which segments a complete cut must\n// contain. That turns the hop count into a termination condition rather than a\n// setting, and MinigraphBubbleAdapter already parses those rows.\nfunction offReference(segments: RgfaSegment[]) {\n return segments.filter(segment => segment.rank > 0)\n}\n\n// tabix-js loops forever on a NaN end and reads nothing for a NaN start\n// (GMOD/tabix-js#157), so every query the adapter makes refuses a range that\n// is not finite first\nfunction checkRange(refName: string, start: number, end: number) {\n if (!Number.isFinite(start) || !Number.isFinite(end)) {\n throw new Error(\n `${refName}:${start}-${end} is not a finite range to query the graph's index for`,\n )\n }\n}\n\nasync function getLines(\n file: TabixIndexedFile,\n refName: string,\n start: number,\n end: number,\n opts: { signal?: AbortSignal; lineCallback: (line: string) => void },\n) {\n checkRange(refName, start, end)\n return file.getLines(refName, start, end, opts)\n}\n\ninterface GraphIndex {\n segments: TabixIndexedFile\n links: TabixIndexedFile\n walks?: TabixIndexedFile\n refNames: PanSNRefNames\n}\n\n// How much graph a walk cut keeps around the window, on the reference\nconst WALK_CONTEXT = 1000\n\nexport default class RgfaTabixAdapter extends BaseFeatureDataAdapter<RgfaTabixAdapterConfig> {\n public static capabilities = ['getFeatures', 'getRefNames']\n\n private readonly fine\n private coarse: GraphIndex | undefined\n\n public constructor(\n config: RgfaTabixAdapterConfig,\n getSubAdapter?: getSubAdapterType,\n pluginManager?: PluginManager,\n ) {\n super(config, getSubAdapter, pluginManager)\n this.fine = this.openIndex([])\n }\n\n // refNames off the SEGMENT index: it is the one that names every stable\n // sequence the graph is anchored to, where the link index only names those a\n // link touches.\n private openIndex(under: string[]): GraphIndex {\n const segments = openTabixSlot(\n this,\n [...under, 'segmentsLocation'],\n [...under, 'segmentsIndex'],\n )\n const walksLocation: FileLocation = this.getConf('walksLocation')\n const hasWalks =\n under.length === 0 &&\n (!('uri' in walksLocation) || walksLocation.uri !== '')\n return {\n segments,\n links: openTabixSlot(\n this,\n [...under, 'linksLocation'],\n [...under, 'linksIndex'],\n ),\n walks: hasWalks\n ? openTabixSlot(this, ['walksLocation'], ['walksIndex'])\n : undefined,\n refNames: new PanSNRefNames(segments, this),\n }\n }\n\n // A walk-indexed graph's header: the chunk its rows are filed under, else\n // the walkChunk slot, how many chunks before a window a cut reads, and the\n // haplotypes it names\n private walkHeader = cachedSetup({\n setup: async opts => {\n const walks = this.fine.walks\n const header = walkHeader(walks ? await walks.getHeaderLines(opts) : [])\n const slot: number = this.getConf('walkChunk')\n const chunk = header.chunk ?? slot\n return {\n ...header,\n chunk,\n lookback: lookbackChunks(header.maxNode, chunk),\n }\n },\n })\n\n private async walkQueryStart(start: number, opts: BaseOptions) {\n const { chunk, lookback } = await this.walkHeader(opts)\n return chunkQueryStart(start, chunk, lookback)\n }\n\n /**\n * The haplotypes a walk-indexed graph's header names, `sample#haplotype`\n * in byte order, or undefined when it names none\n */\n async getHaplotypeNames(opts: BaseOptions = {}) {\n if (!this.fine.walks) {\n return undefined\n }\n const { haplotypes } = await this.walkHeader(opts)\n return haplotypes.length > 0 ? haplotypes : undefined\n }\n\n private index(tier: SubgraphTier = 'fine') {\n if (tier === 'fine') {\n return this.fine\n }\n this.coarse ??= this.openIndex(['coarse'])\n return this.coarse\n }\n\n async getRefNames(opts: BaseOptions = {}) {\n return this.fine.refNames.assemblyRefNames(opts)\n }\n\n public async hasDataForRefName() {\n return true\n }\n\n getFeatures(query: Region, opts: BaseOptions = {}) {\n const { signal, statusCallback } = opts\n return ObservableCreate<Feature>(async observer => {\n const tabixRefName = await this.fine.refNames.resolve(query, opts)\n if (tabixRefName !== undefined) {\n // a walk-indexed node row names only its chunk's first base, and a\n // node crossing in from a chunk before is filed there\n const start = this.fine.walks\n ? await this.walkQueryStart(query.start, opts)\n : query.start\n await updateStatus('Downloading segments', statusCallback, () =>\n getLines(this.fine.segments, tabixRefName, start, query.end, {\n signal,\n lineCallback: line => {\n const { segment, anchored } = parseSegmentRow(line)\n // An anchored index also returns the alleles under the region,\n // which lie on other stable sequences and have no place on this\n // one.\n if (anchored && segment.refName !== tabixRefName) {\n return\n }\n // `samples` lists the haplotypes whose paths visit the segment and\n // `sampleCount` counts them. A lane's color reads the count, and\n // a count in jexl would otherwise rely on `.length` resolving\n // through a member access on an array.\n const samples = segmentSamples(segment)\n observer.next(\n new SimpleFeature({\n uniqueId: segment.id,\n refName: query.refName,\n start: segment.start,\n end: segment.end,\n name: segment.id,\n type: 'segment',\n rank: segment.rank,\n stableName: segment.refName,\n ...(samples && { samples, sampleCount: samples.length }),\n }),\n )\n },\n }),\n )\n }\n observer.complete()\n }, signal)\n }\n\n // Extract the graph around a region as GFA text, for GraphGenomeView. The\n // region's own segments come from segs.bed.gz; links.bed.gz supplies the edges\n // incident to them *and* the coordinates of the segments on the other end,\n // which typically sit on a different stable sequence (a rank>0 bubble) and so\n // are not reachable by any coordinate query on this region.\n //\n // `hops` is extra rounds of link-following past the region's own segments\n // and their immediate neighbours, each costing one tabix query per\n // off-reference segment newly reached. After the last round, one more read\n // per stretch of stable sequence the cut holds closes it (closingSpans), so\n // an allele reached from both ends draws whole. The view asks for one hop; a\n // hopless cut stays as cheap as it was. `signal` goes to every one of those\n // queries, so a cut the view has replaced stops.\n // `tier: 'coarse'` reads the `coarse` pair instead, the same way.\n async getSubgraph(region: Region, opts: SubgraphAdapterOptions = {}) {\n const { hops = 0, signal, tier } = opts\n const index = this.index(tier)\n const segments = new Map<string, RgfaSegment>()\n const links = new Map<string, RgfaLink>()\n const tabixRefName = await index.refNames.resolve(region, { signal })\n\n const addLinksOver = async (\n refName: string,\n start: number,\n end: number,\n ) => {\n const reached: RgfaSegment[] = []\n await getLines(index.links, refName, start, end, {\n signal,\n lineCallback: line => {\n const link = parseLinkLine(line)\n links.set(linkKey(link), link)\n for (const segment of [link.sourceSegment, link.targetSegment]) {\n if (!segments.has(segment.id)) {\n segments.set(segment.id, segment)\n reached.push(segment)\n }\n }\n },\n })\n return reached\n }\n\n if (tabixRefName === undefined) {\n throw new Error(\n `${region.assemblyName} ${region.refName} is not in this graph's index; a graph with PanSN names (GRCh38#0#chr1) needs ${region.assemblyName} mapped to its prefix in assemblyNameToPanSN`,\n )\n }\n if (index.walks) {\n return this.walkSubgraph(index, index.walks, tabixRefName, region, opts)\n }\n const layout = { anchored: false }\n await getLines(index.segments, tabixRefName, region.start, region.end, {\n signal,\n lineCallback: line => {\n const row = parseSegmentRow(line)\n layout.anchored ||= row.anchored\n segments.set(row.segment.id, row.segment)\n },\n })\n // An anchored index files every allele and every link under the reference\n // interval its bubble hangs from, so one read of each file holds the whole\n // graph under the region and there is nothing to hop to or close.\n if (layout.anchored) {\n const found: RgfaLink[] = []\n await getLines(index.links, tabixRefName, region.start, region.end, {\n signal,\n lineCallback: line => {\n found.push(parseLinkLine(line))\n },\n })\n const cut = anchoredCut(segments, found, {\n refName: tabixRefName,\n start: region.start,\n end: region.end,\n })\n return formatSubgraph(cut.segments, cut.links)\n }\n let frontier = offReference(\n await addLinksOver(tabixRefName, region.start, region.end),\n )\n for (let hop = 0; hop < hops; hop++) {\n // One hop's queries are independent of each other, so they go out\n // together rather than one round-trip at a time. Their callbacks share\n // the segment and link maps, which is safe because only one of them runs\n // at a time, and the output is sorted at the end regardless of the order\n // they arrive in.\n const reached = await Promise.all(\n frontier.map(segment =>\n addLinksOver(segment.refName, segment.start, segment.end),\n ),\n )\n frontier = offReference(reached.flat())\n }\n if (hops > 0) {\n const spans = closingSpans(\n [...segments.values()],\n new Set(frontier.map(segment => segment.id)),\n { refName: tabixRefName, start: region.start, end: region.end },\n )\n const found: RgfaLink[] = []\n await Promise.all(\n spans.map(span =>\n getLines(index.links, span.refName, span.start, span.end, {\n signal,\n lineCallback: line => {\n found.push(parseLinkLine(line))\n },\n }),\n ),\n )\n for (const link of closingLinks(found, segments, spans)) {\n links.set(linkKey(link), link)\n for (const segment of [link.sourceSegment, link.targetSegment]) {\n if (!segments.has(segment.id)) {\n segments.set(segment.id, segment)\n }\n }\n }\n }\n\n return formatSubgraph(segments, links)\n }\n\n // A walk-indexed graph's cut: one read of each file over whole chunks, from\n // the lookback chunks before the window to its end. The indexes first\n // estimate the bytes those reads fetch, and a window past walkByteBudget\n // reads no row. Only the walks `haplotypes` asks for, and the reference's,\n // are decoded, and none is past walkStepBudget: the three reads go out\n // together and a walk read over budget stops the other two.\n private async walkSubgraph(\n index: GraphIndex,\n walks: TabixIndexedFile,\n refName: string,\n region: Region,\n opts: SubgraphAdapterOptions,\n ) {\n const { signal, haplotypes } = opts\n const { chunk, lookback } = await this.walkHeader({ signal })\n const budget: number = this.getConf('walkStepBudget')\n const keep = walkNameFilter(\n haplotypes?.map(lane => resolvePanSNPrefix(this, lane)),\n panSNHaplotype(refName),\n )\n const from = chunkQueryStart(region.start, chunk, lookback)\n const files = [walks, index.segments, index.links]\n const tooLarge = await byteBudgetError(\n async end => {\n checkRange(refName, from, end)\n const sizes = await Promise.all(\n files.map(file =>\n file.bytesForRegions([{ refName, start: from, end }], { signal }),\n ),\n )\n return sizes.reduce((sum, bytes) => sum + bytes, 0)\n },\n this.getConf('walkByteBudget'),\n region,\n chunk,\n )\n if (tooLarge) {\n throw tooLarge\n }\n const reads = new AbortController()\n const stop = () => {\n reads.abort(signal?.reason)\n }\n signal?.addEventListener('abort', stop, { once: true })\n const rows: WalkRow[] = []\n const graph = new WalkGraph({\n refName,\n start: region.start,\n end: region.end,\n context: WALK_CONTEXT,\n })\n const read = (\n file: TabixIndexedFile,\n lineCallback: (line: string) => void,\n ) =>\n getLines(file, refName, from, region.end, {\n signal: reads.signal,\n lineCallback,\n })\n try {\n await Promise.all([\n read(walks, line => {\n if (keep === undefined || keep(walkRowName(line))) {\n rows.push(parseWalkRow(line))\n }\n }).then(() => {\n const error = stepBudgetError(\n rows,\n budget,\n region,\n chunk,\n keep !== undefined,\n )\n if (error) {\n throw error\n }\n }),\n read(index.segments, line => {\n graph.addNode(line)\n }),\n read(index.links, line => {\n graph.addLink(line)\n }),\n ])\n } catch (error) {\n reads.abort()\n throw error\n } finally {\n signal?.removeEventListener('abort', stop)\n }\n const { kept, fragments } = walkCut(joinPieces(rows), graph.nodes)\n return graph.format(kept, fragments)\n }\n}\n", "// A segment as it appears in segs.bed.gz, and as it is repeated inside every\n// links.bed.gz row: `stableName start end segmentId rank [tags]`. The first\n// five are the SN/SO/SR tags rGFA already carries, projected to BED by\n// `gfatools gfa2bed -m`.\n//\n// `tags` is a space-separated list of GFA tags, written verbatim onto the\n// S-line formatSegment synthesizes, where the GFA parser reads them into\n// `GraphNode.tags` with no work here. It is the extension point for everything\n// the five columns cannot say: carriage on a path-derived graph (`SM:Z:`), the\n// collapse summary on a level-of-detail tier (`ct:Z:`, `cn:i:`, ...), a\n// precomputed layout position later. rGFA files have no sixth column at all,\n// so this is empty for them and nothing changes.\nexport interface RgfaSegment {\n refName: string\n start: number\n end: number\n id: string\n rank: number\n tags: string\n}\n\nexport interface RgfaLink {\n source: string\n sourceStrand: string\n target: string\n targetStrand: string\n sourceSegment: RgfaSegment\n targetSegment: RgfaSegment\n}\n\nexport function parseSegmentLine(line: string): RgfaSegment {\n return parseSegmentRow(line).segment\n}\n\n// gfa-to-tabix's anchored layout files a segment under the reference interval\n// its bubble hangs from and states the segment's own coordinate after the rank:\n// `anchorName anchorStart anchorEnd segmentId rank stableName start end [tags]`.\n// One query over a region then returns every segment of every bubble under it,\n// and `anchored` tells a cut it has nothing left to follow.\nexport function parseSegmentRow(line: string) {\n const cols = line.split('\\t')\n const anchored = cols.length >= 8\n const own = anchored ? 5 : 0\n return {\n anchored,\n segment: {\n refName: cols[own]!,\n start: +cols[own + 1]!,\n end: +cols[own + 2]!,\n id: cols[3]!,\n rank: +cols[4]!,\n tags: cols[anchored ? 8 : 5] ?? '',\n } satisfies RgfaSegment,\n }\n}\n\n// Carriage as an ordinary feature attribute, for the linear track rather than\n// the graph. The tag column reaches the graph view through the synthesized\n// S-line (formatSegment below, then gfaConverter reads SM into\n// `GraphNode.samples`), and that route ends at the graph: `getFeatures` builds\n// its own features and had no way to say who carries a segment, so a lane\n// colored by carriage was not expressible.\n//\n// `SM:Z:` is its own grammar check here. build_pggb_tabix.sh wrote a bare\n// comma-separated list in this column before the tag column existed, and those\n// files are still hosted; a bare list has no prefix to match, so it is dropped\n// rather than read as one sample named `K12,Sakai,CFT073`.\n//\n// Undefined rather than [] when the tag is absent, matching gfaConverter: an\n// rGFA has no sixth column at all, so a segment that says nothing about\n// carriage stays distinguishable from one carried by nobody.\nexport function segmentSamples(segment: RgfaSegment) {\n const tag = segment.tags.split(' ').find(t => t.startsWith('SM:Z:'))\n if (tag === undefined) {\n return undefined\n }\n const samples = tag\n .slice('SM:Z:'.length)\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n return samples.length > 0 ? samples : undefined\n}\n\n// `s322+` \u2014 the L-line's segment id with its orientation appended, mirroring\n// the GFA record it came from.\nfunction parseEndpoint(field: string) {\n return { id: field.slice(0, -1), strand: field.slice(-1) }\n}\n\nexport function parseLinkLine(line: string): RgfaLink {\n const cols = line.split('\\t')\n const source = parseEndpoint(cols[3]!)\n const target = parseEndpoint(cols[4]!)\n return {\n source: source.id,\n sourceStrand: source.strand,\n target: target.id,\n targetStrand: target.strand,\n sourceSegment: {\n id: source.id,\n refName: cols[5]!,\n start: +cols[6]!,\n end: +cols[7]!,\n rank: +cols[8]!,\n tags: cols[13] ?? '',\n },\n targetSegment: {\n id: target.id,\n refName: cols[9]!,\n start: +cols[10]!,\n end: +cols[11]!,\n rank: +cols[12]!,\n tags: cols[14] ?? '',\n },\n }\n}\n\nexport function linkKey(link: RgfaLink) {\n return `${link.source}${link.sourceStrand}${link.target}${link.targetStrand}`\n}\n\n// The cut an anchored index gives: `under` is what the segment file returned\n// for the window, every segment of every bubble under it, and `found` is what\n// the link file returned. gfa-to-tabix files a link widely enough that `found`\n// holds every link touching a segment in `under` and every link between the\n// segments those lead to, plus links of neither kind, which are dropped here.\n// A backbone link that jumps the whole window, as a deletion or inversion\n// spanning it does, touches nothing in `under` and is kept by its own rule.\nexport function anchoredCut(\n under: Map<string, RgfaSegment>,\n found: RgfaLink[],\n window: StableSpan,\n) {\n const side = (segment: RgfaSegment) =>\n segment.rank !== 0 || segment.refName !== window.refName\n ? 0\n : segment.end <= window.start\n ? -1\n : segment.start >= window.end\n ? 1\n : 0\n const segments = new Map(under)\n const links = new Map<string, RgfaLink>()\n for (const link of found) {\n if (\n under.has(link.source) ||\n under.has(link.target) ||\n side(link.sourceSegment) * side(link.targetSegment) === -1\n ) {\n links.set(linkKey(link), link)\n for (const segment of [link.sourceSegment, link.targetSegment]) {\n if (!segments.has(segment.id)) {\n segments.set(segment.id, segment)\n }\n }\n }\n }\n for (const link of found) {\n if (segments.has(link.source) && segments.has(link.target)) {\n links.set(linkKey(link), link)\n }\n }\n return { segments, links }\n}\n\n// Both endpoints of a link are written into every row, so the same link is\n// indexed under each endpoint's stable sequence and arrives twice for a region\n// covering both. Callers dedupe on linkKey.\n\nexport interface StableSpan {\n refName: string\n start: number\n end: number\n}\n\n// Where a cut reads links once more to close itself. A hop reads the links of\n// the segments the round before it reached, so a link between two segments of\n// the last round is never read and an allele reached from both ends draws as\n// two stubs. rGFA lays an allele out as one stretch of the stable sequence that\n// introduced it, so pieces of one sequence within the window's length of each\n// other merge into a span, and reading it brings the pieces between too.\n// Backbone reached past the window is unread for the same reason; its spans\n// join only abutting pieces, since the reference past the window is not the\n// cut's to fill. A span whose segments were all read and abut is skipped.\nexport function closingSpans(\n held: RgfaSegment[],\n unread: Set<string>,\n window: StableSpan,\n) {\n const outside = (segment: RgfaSegment) =>\n segment.refName !== window.refName ||\n segment.end <= window.start ||\n segment.start >= window.end\n return [\n ...mergedSpans(\n held.filter(segment => segment.rank > 0),\n unread,\n window.end - window.start,\n ),\n ...mergedSpans(\n held.filter(segment => segment.rank === 0 && outside(segment)),\n new Set(held.map(segment => segment.id)),\n 0,\n ),\n ]\n}\n\nfunction mergedSpans(\n segments: RgfaSegment[],\n unread: Set<string>,\n maxGap: number,\n) {\n const sorted = [...segments].sort(\n (a, b) => compare(a.refName, b.refName) || a.start - b.start,\n )\n const spans: (StableSpan & { needed: boolean })[] = []\n for (const segment of sorted) {\n const span = spans.at(-1)\n if (\n span?.refName === segment.refName &&\n segment.start - span.end <= maxGap\n ) {\n span.needed ||= segment.start > span.end || unread.has(segment.id)\n span.end = Math.max(span.end, segment.end)\n } else {\n spans.push({\n refName: segment.refName,\n start: segment.start,\n end: segment.end,\n needed: unread.has(segment.id),\n })\n }\n }\n return spans\n .filter(span => span.needed)\n .map(({ refName, start, end }): StableSpan => ({ refName, start, end }))\n}\n\n// The links a closing read keeps: each end is a segment the cut holds or one\n// lying inside a span. Following anything else is what another hop is for.\nexport function closingLinks(\n found: RgfaLink[],\n held: Map<string, RgfaSegment>,\n spans: StableSpan[],\n) {\n const inside = (segment: RgfaSegment) =>\n held.has(segment.id) ||\n spans.some(\n span =>\n span.refName === segment.refName &&\n segment.start >= span.start &&\n segment.end <= span.end,\n )\n return found.filter(\n link => inside(link.sourceSegment) && inside(link.targetSegment),\n )\n}\n\n// Segments carry no sequence here \u2014 the BED records only their span \u2014 so every\n// S-line is written with `*` and an LN tag, which is what the GFA spec asks for\n// and what packages/graph-core's parser reads back as the node length.\n// `NM:i:0`, `SM:Z:HG002.1,HG002.2` \u2014 the GFA tag grammar, checked rather than\n// trusted. Files built before the tag column existed put a bare comma-separated\n// sample list here, and passing that through would put a field that is not a\n// tag on an S-line, which is a malformed GFA rather than a missing annotation.\n// Dropping it degrades to the pre-tag behaviour instead.\nconst GFA_TAG = /^[A-Za-z][A-Za-z0-9]:[AifZJHB]:/\n\nfunction formatSegment(segment: RgfaSegment) {\n const { id, refName, start, end, rank, tags } = segment\n const valid = tags.split(' ').filter(t => GFA_TAG.test(t))\n const extra = valid.length === 0 ? '' : `\\t${valid.join('\\t')}`\n return `S\\t${id}\\t*\\tLN:i:${end - start}\\tSN:Z:${refName}\\tSO:i:${start}\\tSR:i:${rank}${extra}`\n}\n\nfunction formatLink(link: RgfaLink) {\n const { source, sourceStrand, target, targetStrand } = link\n return `L\\t${source}\\t${sourceStrand}\\t${target}\\t${targetStrand}\\t0M`\n}\n\n// Codepoint order, not localeCompare: the byte-identical-output guarantee below\n// has to hold across locales.\nfunction compare(a: string, b: string) {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n// Deterministic ordering: the same region always produces byte-identical GFA,\n// so a layout computed from it is reproducible.\nexport function formatSubgraph(\n segments: Map<string, RgfaSegment>,\n links: Map<string, RgfaLink>,\n) {\n const sortedSegments = [...segments.values()].sort(\n (a, b) =>\n compare(a.refName, b.refName) || a.start - b.start || compare(a.id, b.id),\n )\n const sortedLinks = [...links.keys()].sort((a, b) => compare(a, b))\n return [\n 'H\\tVN:Z:1.0',\n ...sortedSegments.map(s => formatSegment(s)),\n ...sortedLinks.map(k => formatLink(links.get(k)!)),\n ].join('\\n')\n}\n", "import { NodeLimitError } from '@jbrowse/bandage-core/gbzWindow'\nimport { panSNMatchesPrefix } from '@jbrowse/bandage-core/pansn'\nimport { getBpDisplayStr } from '@jbrowse/core/util'\n\n// A walk-indexed graph is three tabix files filed under fixed chunks of each\n// reference: walk rows, node rows and link rows. A row's first three columns\n// name its chunk, either as the whole chunk or as its first base.\n//\n// walks: anchor cs ce sample#hap#contig fragStart hapOffset piece nsteps steps\n// nodes: anchor cs ce id rank stableName start end [tags]\n// links: anchor cs ce src+ tgt- [both endpoints' coordinates]\n//\n// Steps are node-id deltas with the orientation in the low bit,\n// comma-separated, the first of each row absolute. A haplotype path's piece in\n// one chunk is cut into rows of at most a fixed number of steps, and each row\n// takes the next piece index, so consecutive indices of one path join.\nexport interface WalkRow {\n name: string\n fragStart: number\n hapOffset: number\n piece: number\n n: number\n enc: string\n chunkStart: number\n}\n\nexport interface WalkNode {\n refName: string\n start: number\n end: number\n rank: number\n // on the reference inside the window plus the cut's context\n onWindow: boolean\n}\n\nexport interface WalkWindow {\n refName: string\n start: number\n end: number\n context: number\n}\n\n// The name column, read without splitting the steps, so a row the cut does\n// not want costs a few indexOf calls\nexport function walkRowName(line: string) {\n let at = -1\n for (let k = 0; k < 3; k++) {\n at = line.indexOf('\\t', at + 1)\n }\n return line.slice(at + 1, line.indexOf('\\t', at + 1))\n}\n\nexport function parseWalkRow(line: string): WalkRow {\n const c = line.split('\\t', 9)\n return {\n chunkStart: +c[1]!,\n name: c[3]!,\n fragStart: +c[4]!,\n hapOffset: +c[5]!,\n piece: +c[6]!,\n n: +c[7]!,\n enc: c[8]!,\n }\n}\n\nexport interface WalkHeader {\n chunk?: number\n maxNode?: number\n references: string[]\n haplotypes: string[]\n}\n\nfunction integerTag(line: string, tag: string) {\n const match = new RegExp(`(?:^|\\\\t)${tag}:i:(\\\\d+)`).exec(line)\n return match ? +match[1]! : undefined\n}\n\n/**\n * What a walk file's header states: its chunk size in a\n * `#walks\\tchunk:i:65536` line, from gfa-to-tabix 0.4.0 a\n * `#reference\\tGRCh38` line per reference sample and a\n * `#haplotype\\tHG002#1` line per other haplotype with rows, and from 0.5.0\n * the longest node in bp as `maxnode:i:1024` beside the chunk size\n */\nexport function walkHeader(lines: string[]): WalkHeader {\n const header: WalkHeader = { references: [], haplotypes: [] }\n for (const line of lines) {\n const [key, value = ''] = line.split('\\t')\n if (key === '#reference') {\n header.references.push(value)\n } else if (key === '#haplotype') {\n header.haplotypes.push(value)\n } else {\n header.chunk ??= integerTag(line, 'chunk')\n header.maxNode ??= integerTag(line, 'maxnode')\n }\n }\n return header\n}\n\n/**\n * How many chunks before the window's own a cut reads. A node is filed under\n * the chunk holding its start, so a node `maxNode` bp long reaching into the\n * window starts at most ceil(maxNode / chunk) chunks back. At least one, since\n * the chunk before carries the detour a haplotype takes into the window's\n * first reference node; one when the header gives no `maxnode:i:`, which holds\n * for vg's graphs, chopped to nodes of at most 1,024 bp.\n */\nexport function lookbackChunks(maxNode: number | undefined, chunk: number) {\n return maxNode === undefined ? 1 : Math.max(1, Math.ceil(maxNode / chunk))\n}\n\n// The first base a cut queries: the start of the chunk `lookback` chunks\n// before the one holding the window's start\nexport function chunkQueryStart(start: number, chunk: number, lookback = 1) {\n return Math.max(0, (Math.floor(start / chunk) - lookback) * chunk)\n}\n\n// Which walks a cut decodes: the reference's, and those `wanted` names by\n// PanSN prefix at sample or haplotype depth; undefined decodes every one\nexport function walkNameFilter(\n wanted: string[] | undefined,\n referenceHaplotype: string | undefined,\n) {\n return wanted === undefined || wanted.length === 0\n ? undefined\n : (name: string) =>\n panSNMatchesPrefix(name, referenceHaplotype) ||\n wanted.some(prefix => panSNMatchesPrefix(name, prefix))\n}\n\nexport function decodeSteps(\n enc: string,\n n: number,\n ids = new Int32Array(n),\n rev = new Uint8Array(n),\n at = 0,\n) {\n let prev = 0\n let i = at\n let v = 0\n let neg = false\n for (let p = 0; p <= enc.length; p++) {\n const ch = p < enc.length ? enc.charCodeAt(p) : 44\n if (ch === 44) {\n const d = neg ? -v : v\n const r = d & 1\n rev[i] = r\n prev += (d - r) / 2\n ids[i++] = prev\n v = 0\n neg = false\n } else if (ch === 45) {\n neg = true\n } else {\n v = v * 10 + (ch - 48)\n }\n }\n return { ids, rev }\n}\n\n// One stretch of a haplotype path: rows of consecutive piece index, decoded\nexport interface WalkRun {\n name: string\n hapOffset: number\n ids: Int32Array\n rev: Uint8Array\n}\n\nexport function joinPieces(rows: WalkRow[]) {\n const byPath = new Map<string, WalkRow[]>()\n for (const row of rows) {\n const key = `${row.name}\\t${row.fragStart}`\n const list = byPath.get(key)\n if (list) {\n list.push(row)\n } else {\n byPath.set(key, [row])\n }\n }\n const runs: WalkRun[] = []\n for (const pieces of byPath.values()) {\n pieces.sort((a, b) => a.piece - b.piece)\n let from = 0\n for (let i = 1; i <= pieces.length; i++) {\n if (\n i === pieces.length ||\n pieces[i]!.piece !== pieces[i - 1]!.piece + 1\n ) {\n runs.push(decodeRun(pieces.slice(from, i)))\n from = i\n }\n }\n }\n return runs\n}\n\nfunction decodeRun(pieces: WalkRow[]): WalkRun {\n const n = pieces.reduce((sum, p) => sum + p.n, 0)\n const ids = new Int32Array(n)\n const rev = new Uint8Array(n)\n let at = 0\n for (const p of pieces) {\n decodeSteps(p.enc, p.n, ids, rev, at)\n at += p.n\n }\n return { name: pieces[0]!.name, hapOffset: pieces[0]!.hapOffset, ids, rev }\n}\n\nexport interface WalkFragment {\n name: string\n hapStart: number\n hapEnd: number\n ids: Int32Array\n rev: Uint8Array\n}\n\n/**\n * The cut a window draws from its walks: the reference inside the window plus\n * its context, and each run from its first to its last step on that stretch,\n * run on outward while the next step's node is already in the cut. Without\n * the run-on a haplotype whose alternate allele straddles the edge stopped\n * short of a node other walks had brought into the cut, and that node drew\n * without it. The run-on adds no node, so one pass is enough.\n */\nexport function walkCut(runs: WalkRun[], nodes: Map<number, WalkNode>) {\n const onWindow = (node: WalkNode | undefined) => node?.onWindow === true\n const kept = new Set<number>()\n for (const [id, node] of nodes) {\n if (node.onWindow) {\n kept.add(id)\n }\n }\n const spans: { run: WalkRun; first: number; last: number }[] = []\n for (const run of runs) {\n const { ids } = run\n let first = -1\n let last = -1\n for (let i = 0; i < ids.length; i++) {\n if (onWindow(nodes.get(ids[i]!))) {\n if (first < 0) {\n first = i\n }\n last = i\n }\n }\n if (first >= 0) {\n for (let i = first; i <= last; i++) {\n kept.add(ids[i]!)\n }\n spans.push({ run, first, last })\n }\n }\n const length = (id: number) => {\n const node = nodes.get(id)\n return node === undefined ? 0 : node.end - node.start\n }\n const fragments: WalkFragment[] = []\n for (const { run, first: f, last: l } of spans) {\n const { ids, rev } = run\n let first = f\n let last = l\n while (first > 0 && kept.has(ids[first - 1]!)) {\n first--\n }\n while (last < ids.length - 1 && kept.has(ids[last + 1]!)) {\n last++\n }\n let hapStart = run.hapOffset\n for (let i = 0; i < first; i++) {\n hapStart += length(ids[i]!)\n }\n let hapEnd = hapStart\n for (let i = first; i <= last; i++) {\n hapEnd += length(ids[i]!)\n }\n fragments.push({\n name: run.name,\n hapStart,\n hapEnd,\n ids: ids.subarray(first, last + 1),\n rev: rev.subarray(first, last + 1),\n })\n }\n return { kept, fragments }\n}\n\nexport function formatWalk({ name, hapStart, hapEnd, ids, rev }: WalkFragment) {\n const [sample, haplotype, ...contig] = name.split('#')\n const steps = new Array<string>(ids.length)\n for (let i = 0; i < ids.length; i++) {\n steps[i] = (rev[i] ? '<' : '>') + ids[i]\n }\n return `W\\t${sample}\\t${haplotype}\\t${contig.join('#')}\\t${hapStart}\\t${hapEnd}\\t${steps.join('')}`\n}\n\n// The positions of a line's first `n` tabs, -1 past the last\nfunction tabs(line: string, n: number, out: number[]) {\n let at = -1\n for (let k = 0; k < n; k++) {\n at = at === -1 && k > 0 ? -1 : line.indexOf('\\t', at + 1)\n out[k] = at\n }\n return out\n}\n\n/**\n * The node and link rows a walk cut reads, parsed as they arrive, and the GFA\n * text of the cut they make with its walks. A node filed under two chunks\n * arrives twice and is read once; columns past a node row's eighth (LN:i:,\n * SQ:Z: and whatever follows) are not read at all.\n */\nexport class WalkGraph {\n readonly nodes = new Map<number, WalkNode>()\n private links: number[] = []\n private readonly t: number[] = []\n\n constructor(private window: WalkWindow) {}\n\n addNode(line: string) {\n const t = tabs(line, 8, this.t)\n const id = +line.slice(t[2]! + 1, t[3])\n if (!this.nodes.has(id)) {\n const rank = +line.slice(t[3]! + 1, t[4])\n const refName = line.slice(t[4]! + 1, t[5])\n const start = +line.slice(t[5]! + 1, t[6])\n const end = +line.slice(t[6]! + 1, t[7] === -1 ? undefined : t[7])\n const { window } = this\n this.nodes.set(id, {\n rank,\n refName,\n start,\n end,\n onWindow:\n rank === 0 &&\n refName === window.refName &&\n end > window.start - window.context &&\n start < window.end + window.context,\n })\n }\n }\n\n // An endpoint is held as id * 2 + 1 when reversed\n addLink(line: string) {\n const t = tabs(line, 5, this.t)\n this.links.push(\n endpoint(line, t[2]! + 1, t[3]!),\n endpoint(line, t[3]! + 1, t[4] === -1 ? line.length : t[4]!),\n )\n }\n\n /**\n * GFA text: S lines by reference position, then L lines, then a W line per\n * fragment, the reference's first and the rest by name, the same bytes for\n * the same rows\n */\n format(kept: Set<number>, fragments: WalkFragment[]) {\n const held: (WalkNode & { id: number })[] = []\n for (const id of kept) {\n const node = this.nodes.get(id)\n if (node) {\n held.push({ ...node, id })\n }\n }\n held.sort((x, y) =>\n x.refName < y.refName\n ? -1\n : x.refName > y.refName\n ? 1\n : x.start - y.start || x.id - y.id,\n )\n const lines = ['H\\tVN:Z:1.1']\n for (const { id, refName, start, end, rank } of held) {\n lines.push(\n `S\\t${id}\\t*\\tLN:i:${end - start}\\tSN:Z:${refName}\\tSO:i:${start}\\tSR:i:${rank}`,\n )\n }\n const seen = new Set<string>()\n const links: string[] = []\n for (let i = 0; i < this.links.length; i += 2) {\n const a = this.links[i]!\n const b = this.links[i + 1]!\n const source = Math.floor(a / 2)\n const target = Math.floor(b / 2)\n if (kept.has(source) && kept.has(target)) {\n const line = `L\\t${source}\\t${a % 2 ? '-' : '+'}\\t${target}\\t${b % 2 ? '-' : '+'}\\t0M`\n if (!seen.has(line)) {\n seen.add(line)\n links.push(line)\n }\n }\n }\n links.sort()\n return [\n ...lines,\n ...links,\n ...this.referenceFirst(fragments).map(formatWalk),\n ].join('\\n')\n }\n\n // The view anchors on the first walk when no walk names the assembly, as\n // gbz-base's cut has it; in file order that was whichever haplotype the\n // chunk listed first, CHM13 on a GRCh38 window\n private referenceFirst(fragments: WalkFragment[]) {\n const { refName } = this.window\n return [...fragments].sort(\n (a, b) =>\n Number(b.name === refName) - Number(a.name === refName) ||\n (a.name < b.name ? -1 : a.name > b.name ? 1 : a.hapStart - b.hapStart),\n )\n }\n}\n\nfunction endpoint(line: string, from: number, to: number) {\n return (\n +line.slice(from, to - 1) * 2 + (line.charCodeAt(to - 1) === 45 ? 1 : 0)\n )\n}\n\n/**\n * The zoom-in notice for a cut whose walk rows hold more steps than `budget`,\n * or undefined when they fit. A window reads whole chunks, those before it\n * included, so the span that fits is counted in chunks from the window's\n * start; when the chunks a window there always reads are over on their own,\n * no zoom fits and the notice asks for fewer haplotypes. A cut for every\n * haplotype is also offered fewer where the reference and one haplotype, at\n * the walks' average steps, would fit the whole window.\n */\nexport function stepBudgetError(\n rows: WalkRow[],\n budget: number,\n window: { start: number; end: number },\n chunk: number,\n filtered: boolean,\n) {\n let total = 0\n const perChunk = new Map<number, number>()\n const walks = new Set<string>()\n for (const row of rows) {\n total += row.n\n perChunk.set(row.chunkStart, (perChunk.get(row.chunkStart) ?? 0) + row.n)\n walks.add(row.name)\n }\n if (total <= budget) {\n return undefined\n }\n const windowBp = window.end - window.start\n let read = 0\n let fitsBp = 0\n for (const cs of [...perChunk.keys()].sort((a, b) => a - b)) {\n read += perChunk.get(cs)!\n if (read > budget) {\n break\n }\n fitsBp = Math.max(fitsBp, cs + chunk - window.start)\n }\n const fewerFit =\n !filtered && walks.size > 2 && (2 * total) / walks.size <= budget\n const error = new NodeLimitError(budget, windowBp, Math.max(fitsBp, 1))\n error.message =\n fitsBp > 0\n ? `Zoom in to about ${getBpDisplayStr(fitsBp)}${fewerFit ? ', or choose fewer haplotypes,' : ''} to see the graph`\n : `Too many haplotype steps here to draw ${filtered ? 'these haplotypes' : 'every haplotype'} (${read.toLocaleString()} against walkStepBudget ${budget.toLocaleString()}); choose fewer haplotypes`\n return error\n}\n\n/**\n * The zoom-in notice for a cut whose three files would fetch more than\n * `budget` compressed bytes, or undefined when they fit. `bytesTo(end)` is the\n * indexes' estimate for a read from the window's first query base to `end`;\n * the span that fits grows a chunk at a time from the chunk holding the\n * window's start, and when that chunk and those before it are over on their\n * own, no zoom fits.\n */\nexport async function byteBudgetError(\n bytesTo: (end: number) => Promise<number>,\n budget: number,\n window: { start: number; end: number },\n chunk: number,\n) {\n const bytes = await bytesTo(window.end)\n if (bytes <= budget) {\n return undefined\n }\n let fitsBp = 0\n let least: number | undefined\n for (\n let cs = Math.floor(window.start / chunk) * chunk;\n cs < window.end;\n cs += chunk\n ) {\n const read = await bytesTo(cs + 1)\n least ??= read\n if (read > budget) {\n break\n }\n fitsBp = cs + chunk - window.start\n }\n const windowBp = window.end - window.start\n const error = new NodeLimitError(budget, windowBp, Math.max(fitsBp, 1))\n error.message =\n fitsBp > 0\n ? `Zoom in to about ${getBpDisplayStr(fitsBp)} to see the graph`\n : `Too much graph here to fetch (${megabytes(least ?? bytes)} against walkByteBudget ${megabytes(budget)})`\n return error\n}\n\nconst megabytes = (bytes: number) => `${(bytes / 1e6).toFixed(1)} MB`\n"],
|
|
5
|
+
"mappings": "iUACA,IAAAA,EAGO,UACPC,EAA4C,SAC5CC,GAAiC,UCiC1B,SAASC,EAAgBC,EAAc,CAC5C,IAAMC,EAAOD,EAAK,MAAM,GAAI,EACtBE,EAAWD,EAAK,QAAU,EAC1BE,EAAMD,EAAW,EAAI,EAC3B,MAAO,CACL,SAAAA,EACA,QAAS,CACP,QAASD,EAAKE,CAAG,EACjB,MAAO,CAACF,EAAKE,EAAM,CAAC,EACpB,IAAK,CAACF,EAAKE,EAAM,CAAC,EAClB,GAAIF,EAAK,CAAC,EACV,KAAM,CAACA,EAAK,CAAC,EACb,KAAMA,EAAKC,EAAW,EAAI,CAAC,GAAK,EAClC,CACF,CACF,CAiBO,SAASE,E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F,MAAMA,EAER,IAAMI,EAAQ,IAAI,gBACZC,EAAO,IAAM,CACjBD,EAAM,MAAM1C,GAAQ,MAAM,CAC5B,EACAA,GAAQ,iBAAiB,QAAS2C,EAAM,CAAE,KAAM,EAAK,CAAC,EACtD,IAAMC,EAAkB,CAAC,EACnBC,EAAQ,IAAIC,EAAU,CAC1B,QAAAzE,EACA,MAAOoC,EAAO,MACd,IAAKA,EAAO,IACZ,QAAS9B,EACX,CAAC,EACKoE,EAAO,CACXtE,EACAuE,IAEAxE,EAASC,EAAMJ,EAAS+D,EAAM3B,EAAO,IAAK,CACxC,OAAQiC,EAAM,OACd,aAAAM,CACF,CAAC,EACH,GAAI,CACF,MAAM,QAAQ,IAAI,CAChBD,EAAK/D,EAAOoB,GAAQ,EACd2B,IAAS,QAAaA,EAAKkB,GAAY7C,CAAI,CAAC,IAC9CwC,EAAK,KAAKM,GAAa9C,CAAI,CAAC,CAEhC,CAAC,EAAE,KAAK,IAAM,CACZ,IAAM+C,EAAQC,GACZR,EACAd,EACArB,EACArB,EACA2C,IAAS,MACX,EACA,GAAIoB,EACF,MAAMA,CAEV,CAAC,EACDJ,EAAKpC,EAAM,SAAUP,GAAQ,CAC3ByC,EAAM,QAAQzC,CAAI,CACpB,CAAC,EACD2C,EAAKpC,EAAM,MAAOP,GAAQ,CACxByC,EAAM,QAAQzC,CAAI,CACpB,CAAC,CACH,CAAC,CACH,OAAS+C,EAAO,CACd,MAAAT,EAAM,MAAM,EACNS,CACR,QAAE,CACAnD,GAAQ,oBAAoB,QAAS2C,CAAI,CAC3C,CACA,GAAM,CAAE,KAAAU,GAAM,UAAAC,EAAU,EAAIC,GAAQC,GAAWZ,CAAI,EAAGC,EAAM,KAAK,EACjE,OAAOA,EAAM,OAAOQ,GAAMC,EAAS,CACrC,CACF",
|
|
6
|
+
"names": ["import_BaseAdapter", "import_util", "import_rxjs", "parseSegmentRow", "line", "cols", "anchored", "own", "segmentSamples", "segment", "tag", "t", "samples", "s", "parseEndpoint", "field", "parseLinkLine", "source", "target", "linkKey", "link", "anchoredCut", "under", "found", "window", "side", "segments", "links", "closingSpans", "held", "unread", "outside", "mergedSpans", "maxGap", "sorted", "b", "compare", "spans", "span", "refName", "start", "end", "closingLinks", "inside", "GFA_TAG", "formatSegment", "id", "rank", "tags", "valid", "extra", "formatLink", "sourceStrand", "targetStrand", "a", "formatSubgraph", "sortedSegments", "sortedLinks", "k", "import_util", "walkRowName", "line", "at", "k", "parseWalkRow", "c", "integerTag", "tag", "match", "walkHeader", "lines", "header", "key", "value", "lookbackChunks", "maxNode", "chunk", "chunkQueryStart", "start", "lookback", "walkNameFilter", "wanted", "referenceHaplotype", "name", "panSNMatchesPrefix", "prefix", "decodeSteps", "enc", "n", "ids", "rev", "prev", "v", "neg", "p", "ch", "d", "r", "joinPieces", "rows", "byPath", "row", "list", "runs", "pieces", "b", "from", "i", "decodeRun", "sum", "walkCut", "nodes", "onWindow", "node", "kept", "id", "spans", "run", "first", "last", "length", "fragments", "hapStart", "hapEnd", "formatWalk", "sample", "haplotype", "contig", "steps", "tabs", "out", "WalkGraph", "window", "t", "rank", "refName", "end", "endpoint", "held", "x", "y", "seen", "links", "a", "source", "target", "to", "stepBudgetError", "budget", "filtered", "total", "perChunk", "walks", "windowBp", "read", "fitsBp", "cs", "fewerFit", "error", "NodeLimitError", "byteBudgetError", "bytesTo", "bytes", "least", "megabytes", "offReference", "segments", "segment", "checkRange", "refName", "start", "end", "getLines", "file", "opts", "WALK_CONTEXT", "RgfaTabixAdapter", "config", "getSubAdapter", "pluginManager", "walks", "header", "walkHeader", "slot", "chunk", "lookbackChunks", "under", "openTabixSlot", "walksLocation", "hasWalks", "PanSNRefNames", "lookback", "chunkQueryStart", "haplotypes", "tier", "query", "signal", "statusCallback", "observer", "tabixRefName", "line", "anchored", "parseSegmentRow", "samples", "segmentSamples", "region", "hops", "index", "links", "addLinksOver", "reached", "link", "parseLinkLine", "linkKey", "layout", "row", "found", "cut", "anchoredCut", "formatSubgraph", "frontier", "hop", "spans", "closingSpans", "span", "closingLinks", "budget", "keep", "walkNameFilter", "lane", "resolvePanSNPrefix", "panSNHaplotype", "from", "files", "tooLarge", "byteBudgetError", "sum", "bytes", "reads", "stop", "rows", "graph", "WalkGraph", "read", "lineCallback", "walkRowName", "parseWalkRow", "error", "stepBudgetError", "kept", "fragments", "walkCut", "joinPieces"]
|
|
7
|
+
}
|
|
@@ -4,5 +4,5 @@ import{a as K,b as Bn,c as Ra,d as Sa,e as Ze,f as Ht,g as $t}from"./chunks/chun
|
|
|
4
4
|
`)&&(e.hoveredRowWalks=t)},setHoveredWalkRow(t){e.hoveredWalkRow=t},setHoveredBubble(t){e.hoveredBubble=t},setPointerInPane(t){e.pointerInPane=t},setWalkStrip(t){e.walkStrip=t,e.stripHover=null},setStripHover(t){e.stripHover=t;let n=e.walkStripRows,r=e.walkStripFrame,o=t&&n?[n.reference,...n.rows].find(i=>i.name===t.row):void 0,a=o&&r&&e.graph?Oo(e.graph,o,t.offset,r.scaleX):void 0;e.hoveredNode=a??null},setLegendSize(t){e.legendSize=t},setHoveredEdge(t){e.hoveredEdge=t},setSelectedNode(t){e.selectedNode=t},setDraggingNode(t){e.draggingNode=t},setPanning(t){e.isPanning=t},stopDragging(){e.draggingNode=null,e.isPanning=!1},clearInteractionState(){e.hoveredNode=null,e.hoveredWalkRow=null,e.hoveredBubble=null,e.hoveredEdge=null,e.selectedNode=null,e.draggingNode=null,e.isPanning=!1},showNodeDetails(t){let n=e.nodeById?.get(t),r=e.nodeById,o=e.nodeNeighbors;if(n&&r&&o){let a=(0,lt.getSession)(e),i=e.graphRegion,s=i?be({nodeId:t,nodeById:r,neighbors:o}):void 0;(0,lt.isSessionModelWithWidgets)(a)&&a.showWidget(a.addWidget("BaseFeatureWidget","baseFeature",{featureData:{id:n.id,name:n.name,length:n.length,depth:n.depth,rank:n.stable?.rank,stableName:n.stable?.refName,contributingAssembly:Ke(n)?.sample,contributingHaplotype:Ke(n)?.haplotype,sampleCount:n.samples?.length,samples:n.samples,...i&&s?{refName:i.refName,assemblyName:i.assemblyName,start:s.start,end:s.end}:{}}}))}},setTransform(t,n,r){let{host:o}=e;e.viewportOwner==="host"&&o?o.horizontalScroll(e.translateX-n):(e.viewportOwner="user",e.scale=xn(t),e.translateX=n),e.translateY=r,e.keepDrawingInView()},zoom(t,n,r){let{host:o}=e;if(e.viewportOwner==="host"&&o){o.zoomTo(o.bpPerPx/t,n);return}e.viewportOwner="user";let a=no(e,t,n,r,e.pixelRows);e.scale=a.scale,e.translateX=a.translateX,e.translateY=a.translateY,e.keepDrawingInView()},setViewportDirty(){e.viewportRebuildPending=!1,e.viewportDirty++},setPositionsDirty(){e.positionsVersion++},zoomToFit(){if(e.viewportOwner==="host"){let n=e.layoutBounds,r=e.facetGrid!==void 0,o=r?ee:W,a=r?ee:e.fitPadTop,i=e.viewBox.height-a-o;n&&i>0&&(e.translateY=Ln(n,i,e.scaleY,a));return}let t=e.fittedTransform;t&&(e.scale=t.scale,e.translateX=t.translateX,e.translateY=t.translateY)},clearPerfMetrics(){e.lastFetchMs=void 0,e.lastLayoutMs=void 0,e.lastGeometryMs=void 0,e.lastGeometryStrokeCount=void 0,e.builtViewport=void 0}})).actions(e=>({hostTransform(t,n){let r=e.viewportOwner!=="host";r&&(e.viewportOwner="host"),e.scale=t,e.translateX=n,r&&e.zoomToFit()},followNewLayout(t){let n=e.layoutBounds;if(e.viewportOwner!=="user"||!n||t===e.layoutResult)return;let r=t?.referenceAxis===!0&&e.xIsReferenceBp;t===void 0||r&&(!e.paneMeasured||Wi(n,e,e.viewBox))?e.keepDrawingInView():(e.viewportOwner="fit",e.zoomToFit())},refitView(){e.viewportOwner==="user"&&(e.viewportOwner="fit"),e.zoomToFit()},releaseHost(){e.viewportOwner==="host"&&(e.xIsReferenceBp?e.viewportOwner="user":(e.viewportOwner="fit",e.zoomToFit()))}})).actions(e=>{function t(){clearTimeout(e.viewportDirtyTimer),e.viewportRebuildPending=!0,e.viewportDirtyTimer=setTimeout(()=>{(0,cr.isAlive)(e)&&e.setViewportDirty()},Mo)}function n(){cancelAnimationFrame(e.positionsDirtyFrame),e.positionsDirtyFrame=requestAnimationFrame(()=>{(0,cr.isAlive)(e)&&e.setPositionsDirty()})}return{moveNode(r,o,a){let i=e.layoutResult?.nodePositions;if(i?.[r]){for(let s of i[r])s.x+=o,s.y+=a;n()}},scheduleViewportDirty:t}});var Xi=ji.actions(e=>{let t,n;function r(u){let{rpcManager:h}=(0,U.getSession)(e);return h.call((0,U.getRpcSessionId)(e),"GraphComputeLayout",{...u,signal:t?.signal,statusCallback:S=>{e.setStatusMessage((0,U.statusMessageText)(S)??"")}})}function o(){return Sn({engine:e.layoutEngine,quality:e.layoutQuality,linearLayout:e.linearLayout,bubbleSpread:e.bubbleSpread,showDeletionEdges:e.showDeletionEdges})}function*a(u){let h=performance.now(),S=Ge.has(e.chosenLayoutMode),L=e.graphRegion,G=S&&L?ni(u,L):u,N=S&&e.tubeMapFold>0&&!G.reads?oi(G,e.tubeMapFold):void 0,v=O(e.chosenLayoutMode).run(N?.graph??G,e.graphRegion,e.host?e.layoutResult?.sampleRows:void 0);if(v)return{result:N&&v.tubeMap?{...v,tubeMap:{...v.tubeMap,coarse:N}}:v,duration:performance.now()-h};let D=o(),b=Ue.ready(u,D);return b?{result:b,duration:performance.now()-h}:yield Ue.layout(u,D,r)}let i=0,s,c,d=new Map;function*f(u){let h=++i,S=()=>e.graph===u&&h===i,L=t?.signal,G;try{if(e.modeDrawsNodes&&u.nodes.length>e.maxGraphNodes)throw new Error(`Graph too large to draw: ${u.nodes.length.toLocaleString()} nodes (limit ${e.maxGraphNodes.toLocaleString()}). Pick Layout \u2192 Walk rows, zoom in to a smaller region, or raise the node limit in Settings.`);G=yield*a(u)}catch(v){if(!S()||L?.aborted)return!1;throw s=v,v}let N=S();if(N){s!==void 0&&e.error===s&&(e.error=void 0),s=void 0;let v=e.layoutResult;c=u,e.layoutResult=G.result,e.setLayoutMs(G.duration),e.followNewLayout(v)}return N}function w(u,h){let S=u.anchorPaths;return u.anchoredBy==="paths"&&S?(un(u,e.assemblySpellings(h.assemblyName))??fn(S,h.assemblyName))?.name:void 0}function*p(u,h,S,L=!1,G){let N=t?.signal;e.setStatusMessage("Parsing GFA");let v=kn(u,h,{referencePath:e.referencePath||S?.assemblyName}),D=S?w(v,S):void 0,b=!e.referencePath&&D!==void 0&&D!==v.referencePath?$e(v,D):v;if(G){e.setStatusMessage("Reading alignments");try{let{records:x,total:P}=yield G(b);b.reads=x,e.readsShown={shown:x.length,total:P}}catch(x){if(N?.aborted)return;console.warn("[GraphGenomeView] no reads for this graph",x),e.readsShown=void 0}if(N?.aborted)return}else e.readsShown=void 0;let C=L?e.selectedNode:null;e.graph=b,e.graphRegion=S,e.loadedReferencePath=D,e.indexBubbles=void 0,e.geneTrackFeatures=void 0,e.walkGeneFeatures=void 0,d.clear(),e.repeatArrays=void 0,e.popStack=[],e.clearInteractionState(),C!==null&&b.nodes.some(x=>x.id===C)&&(e.selectedNode=C),e.setStatusMessage("Computing layout"),yield*f(b)}let l=0,R;function M(){let u=++l;return t?.abort(),t=new AbortController,R=u,e.loadCanceled=!1,{isLive:()=>u===l,signal:t.signal}}function A(){R=void 0,e.finishLoading()}function g(){R===void 0&&e.finishLoading()}function*k(u,h,S,L){let G=xo(u);if(!(u.type!=="RgfaTabixAdapter"||G===void 0))try{let N=yield(0,U.getSession)(e).rpcManager.call((0,U.getRpcSessionId)(e),"CoreGetFeatures",{adapterConfig:{type:"MinigraphBubbleAdapter",uri:`${G}.bubbles.bed.gz`,baseUri:u.baseUri,assemblyNameToPanSN:u.assemblyNameToPanSN},regions:[h],signal:L});if(S()){let v=N.map(C=>({refName:h.refName,start:C.get("start"),end:C.get("end"),segmentCount:C.get("segmentCount"),pathCount:C.get("pathCount")??0,inversion:C.get("inversion"),shortestAlleleLength:C.get("shortestAlleleLength"),longestAlleleLength:C.get("longestAlleleLength"),segments:C.get("segments"),shortestAllele:void 0,longestAllele:void 0})),[D,...b]=e.popStack;D?e.popStack=[{...D,indexBubbles:v},...b]:e.indexBubbles=v}}catch(N){console.warn("[GraphGenomeView] no bubble index for this graph",N)}}function*T(u,h,S,L){let G=(0,U.getSession)(e),N=u?G.tracks.find(v=>v.trackId===u):void 0;if(N)try{return yield G.rpcManager.call((0,U.getRpcSessionId)(e),"CoreGetFeatures",{adapterConfig:(0,zi.readConfObject)(N,"adapter"),regions:[h],signal:L})}catch(v){console.warn(`[GraphGenomeView] no ${S} for this graph`,v);return}}function*B(u,h,S){let L=yield*T(e.geneTrack?.trackId,u,"genes",S);L&&h()&&(e.geneTrackFeatures=L)}function*V(u,h,S){let L=yield*T(e.repeatTrack?.trackId,u,"repeats",S);L&&h()&&(e.repeatArrays=Ti(L))}function*y(u,h,S){let{isLive:L,signal:G}=M();e.isLoading=!0,e.error=void 0;try{let N=typeof h=="string"?h:yield h(G);L()&&(yield*p(N,u,S))}catch(N){L()&&(console.error("[GraphGenomeView.loadWholeGFA]",N),e.error=N)}finally{L()&&A()}return L()}function I(){t?.abort(),t=void 0,R=void 0,l++,i++}function E(){I(),e.graph=void 0,e.graphRegion=void 0,e.loadedReferencePath=void 0,e.layoutResult=void 0,e.indexBubbles=void 0,e.geneTrackFeatures=void 0,e.walkGeneFeatures=void 0,d.clear(),e.repeatArrays=void 0,e.readsShown=void 0,e.popStack=[],e.error=void 0,e.isLoading=!1,e.loadCanceled=!1,e.statusMessage="",e.clearInteractionState(),e.clearPerfMetrics(),e.viewportOwner==="user"&&(e.viewportOwner="fit")}return{clearGraph(){E()},cancelLoad(){e.canCancelLoad&&(E(),e.loadCanceled=!0)},stopLoad(){I(),e.graph!==c&&(e.layoutResult=void 0),e.isLoading=!1,e.statusMessage="",e.loadCanceled=!0},beforeDestroy(){I()},loadGFA:(0,_.flow)(function*(u,h="Imported GFA"){yield*y(h,u)}),loadGFAFromLocation:(0,_.flow)(function*(u,h){e.setStatusMessage("Fetching GFA");let S=yield*y(Ye(u)||"GFA",L=>(0,dr.openLocation)(u).readFile({encoding:"utf8",signal:L}),h);if(h&&S&&e.graph){let L=()=>e.graphRegion===h;yield Promise.all([(0,_.flow)(B)(h,L),(0,_.flow)(V)(h,L)])}}),cutSubgraph:(0,_.flow)(function*(u,h,S={}){let{isLive:L,signal:G}=M();e.isLoading=!0,e.error=void 0,e.setStatusMessage("Fetching subgraph");try{let N=performance.now(),v=yield(0,U.getSession)(e).rpcManager.call((0,U.getRpcSessionId)(e),"GetSubgraph",{adapterConfig:u,region:h,opts:S,signal:G});if(!L())return;if(e.setFetchMs(performance.now()-N),!v)throw new Error("Adapter returned no GFA \u2014 region may be outside indexed data or the adapter does not implement getSubgraph");if(yield*p(v,Je(h),h,!0,Fa(u)?D=>(0,U.getSession)(e).rpcManager.call((0,U.getRpcSessionId)(e),"GetGraphReads",{adapterConfig:u,nodeNames:D.nodes.map(b=>b.name),signal:G}):void 0),!L())return;e.setStatusMessage("Reading annotations"),yield Promise.all([S.tier==="coarse"?void 0:(0,_.flow)(k)(u,h,L,G),(0,_.flow)(B)(h,L,G),(0,_.flow)(V)(h,L,G)])}catch(N){L()&&(console.error("[GraphGenomeView.cutSubgraph]",N),e.error=N)}finally{L()&&A()}}),reloadRepeats:(0,_.flow)(function*(){let u=e.graphRegion,h=e.repeatTrack?.trackId;u&&(e.repeatArrays=void 0,yield*V(u,()=>e.graphRegion===u&&e.repeatTrack?.trackId===h))}),loadWalkRowSampleTable:(0,_.flow)(function*(){let u=e.walkRowSamplesTsv,h=u?JSON.stringify(u):void 0;if(h!==n&&(n=h,e.walkRowSampleTable=void 0,!!u))try{let S=yield(0,dr.openLocation)(u).readFile("utf8");(0,_.isAlive)(e)&&h===n&&(e.walkRowSampleTable=oo(S))}catch(S){(0,_.isAlive)(e)&&h===n&&(0,U.getSession)(e).notify(`Walk rows cannot be grouped: the samples table did not load (${String(S)})`,"warning")}}),loadWalkGenes:(0,_.flow)(function*(){let u=e.walkGeneReads?.reads??[],h=JSON.stringify(u),S=e.graph,L=new Map;yield Promise.all(u.map(({row:G,trackId:N,region:v})=>(0,_.flow)(function*(){let D=`${N} ${v.refName}:${v.start}-${v.end}`,b=d.get(D);if(!b){let C=yield*T(N,v,"haplotype genes");if(!C)return;b=qt(C).map(x=>({...x,refName:v.refName})),d.set(D,b)}L.set(G,b)})())),(0,_.isAlive)(e)&&e.graph===S&&JSON.stringify(e.walkGeneReads?.reads??[])===h&&(e.walkGeneFeatures=u.length?L:void 0)}),reloadGenes:(0,_.flow)(function*(){d.clear();let u=e.graphRegion,h=e.geneTrack?.trackId;u&&(e.geneTrackFeatures=void 0,yield*B(u,()=>e.graphRegion===u&&e.geneTrack?.trackId===h))}),popBubble:(0,_.flow)(function*(u){let h=e.graph;if(!h)return;let S=$n(h,Et(u));if(S.nodes.length===0){(0,U.getSession)(e).notify("None of the segments of this bubble are in the cut; widen the graph context to open it","info");return}e.popStack=[...e.popStack,{graph:h,layoutMode:e.layoutMode,label:h.name,indexBubbles:e.indexBubbles}],e.indexBubbles=void 0;let L=`${Co[Bt(u,e.repeatArrays).kind]} at ${u.refName}:${u.start.toLocaleString()}`;e.graph={...S,name:L},e.clearInteractionState(),e.viewportOwner="fit",e.isLoading=!0;try{(yield*f(e.graph))&&g()}catch(G){e.error=G,g()}}),unpopBubble:(0,_.flow)(function*(){let u=e.poppedFrom;if(u){e.popStack=e.popStack.slice(0,-1),e.graph=u.graph,e.layoutMode=u.layoutMode,e.indexBubbles=u.indexBubbles,e.clearInteractionState(),e.viewportOwner="fit",e.isLoading=!0;try{(yield*f(u.graph))&&g()}catch(h){e.error=h,g()}}}),recomputeLayout:(0,_.flow)(function*(){let u=e.graph;if(u){e.isLoading=!0,e.setStatusMessage("Computing layout");try{(yield*f(u))&&g()}catch(h){console.error("[GraphGenomeView.recomputeLayout]",h),e.error=h,g()}}})}});function rd(e){return q(e)&&typeof e.get=="function"}function od(e){let t=rd(e)?e.get("name"):q(e)?e.name:void 0;return typeof t=="string"?t:void 0}function Yi(e){let t;if(q(e)&&q(e.hoverPosition)){let{refName:n,coord:r,coord0:o,assemblyName:a}=e.hoverPosition;typeof n=="string"&&typeof r=="number"&&(t={refName:n,coord:typeof o=="number"?o:r-1,assemblyName:typeof a=="string"?a:void 0,featureName:od(e.hoverFeature)})}return t}function Ui(e,t){return(e.assemblyName===void 0||e.assemblyName===t.assemblyName)&&e.refName===t.refName&&e.coord>=t.start&&e.coord<t.end}function Ki({hover:e,nodes:t}){let n,r;for(let o of t)o.name===e.featureName?n=o.id:r===void 0&&Z(o)&&e.coord>=o.stable.start&&e.coord<o.stable.start+o.length&&(r=o.id);return n??r??null}var ad=/^(.+) HP(\d+)$/,id=/^(.+)\.(\d+)$/;function sd(e){let t=ad.exec(e),n=id.exec(e);return[...t?[{sample:t[1],haplotype:String(Number(t[2])+1)}]:[],...n?[{sample:n[1],haplotype:n[2]}]:[],{sample:e,haplotype:void 0}]}function cd(e){return Q(e).name.split("#")[1]}function qi(e,t){let n=t.map(r=>r.name);for(let{sample:r,haplotype:o}of sd(e)){let a=n.filter(i=>Tr(Q(i).name)===r&&(o===void 0||cd(i)===o));if(a.length>0)return a}return[]}var Zi=Xi.actions(e=>({startRenderingBackend(t){if(!e.autorunsInstalled){(0,ie.addDisposer)(e,(0,z.autorun)(()=>{e.fittedTransform&&(0,z.untracked)(()=>e.viewportOwner==="fit")&&e.zoomToFit()})),(0,ie.addDisposer)(e,(0,z.reaction)(()=>`${e.viewBox.width} ${e.viewBox.height}`,()=>{e.keepDrawingInView()})),(0,ie.addDisposer)(e,(0,z.reaction)(()=>{let r=e.facetGrid;return r?`${e.facet.field} ${e.facetPanels?.length} ${r.columns}`:""},()=>{e.refitView()})),(0,ie.addDisposer)(e,(0,z.reaction)(()=>({graph:e.graph,reads:JSON.stringify(e.walkGeneReads?.reads??[])}),()=>{e.loadWalkGenes()},{fireImmediately:!0,equals:(r,o)=>r.graph===o.graph&&r.reads===o.reads})),(0,ie.addDisposer)(e,(0,z.reaction)(()=>e.chosenLayoutMode==="walkrows"?JSON.stringify(e.walkRowSamplesTsv??null):void 0,r=>{r!==void 0&&e.loadWalkRowSampleTable()},{fireImmediately:!0})),(0,ie.addDisposer)(e,(0,z.reaction)(()=>e.fitPadTop,()=>{e.viewportOwner==="host"&&e.zoomToFit()})),(0,ie.addDisposer)(e,(0,z.autorun)(()=>{let r=Yi((0,Ji.getSession)(e).hovered);(0,z.untracked)(()=>{let o=e.graphRegion,a=e.graph,i=r&&o&&Ui(r,o)?r:void 0,s=i?.featureName&&a?.paths?qi(i.featureName,a.paths):[];o&&a&&!e.pointerInPane&&e.setHoveredNode(i&&s.length===0?Ki({hover:i,nodes:a.nodes}):null),e.setHoveredRowWalks(s)})})),(0,ie.addDisposer)(e,(0,z.reaction)(()=>`${e.scale}-${e.translateX}-${e.translateY}`,()=>{e.setHoveredNode(null),e.setHoveredBubble(null),e.setHoveredEdge(null)},{name:"GraphClearHoverOnViewportChange"}));let n=!0;(0,ie.addDisposer)(e,(0,z.autorun)(()=>{let{scale:r}=e,o=Ct(e);if(n){n=!1;return}let a=(0,z.untracked)(()=>e.builtViewport);a?.scale===r&&to(a.bounds,o)||e.scheduleViewportDirty()})),(0,ie.addDisposer)(e,(0,z.autorun)(()=>{let r=e.currentRenderingBackend;he(e.geometryVersion),r&&(e.applyHighlights(r),e.renderNow())}))}e.attachRenderingBackend(t,()=>({upload:n=>{if(n.resize(e.paneWidth,e.canvasHeight),e.layoutResult?.tubeMap||e.facetPanels)return he(e.viewportDirty),n.uploadGeometry(To),e.setGeometryMetrics(0,0,{scale:(0,z.untracked)(()=>e.scale),bounds:(0,z.untracked)(()=>e.viewportToBuild())}),!0;let r=performance.now(),o=e.buildDrawing(e.walkLift,e.effectiveDrawPaths);return o?(n.uploadGeometry(o.batch),e.setGeometryMetrics(performance.now()-r,o.batch.nodeStrokes.length,{scale:(0,z.untracked)(()=>e.scale),bounds:o.viewportBounds}),!0):!1},render:n=>e.nodePositions?(e.paint(n),e.markPainted(),!0):!1,releaseTargets:n=>{n.releaseOffscreenTargets()}}))}})).actions(e=>({switchLayout(t){return e.setLayoutMode(t),e.recomputeLayout()},toggleDeletionEdges(){return e.setShowDeletionEdges(!e.showDeletionEdges),e.usesLayoutEngine?e.recomputeLayout():void 0},retryLoad(){},afterAttach(){e.isDefaultViewport||(e.viewportOwner="user")}}));var en=m(K(),1);var dd="FeatureTrack";function Qi({session:e,assemblyName:t,first:n}){let r=fe(e,t),o=[];for(let a of e.tracks){let i=(0,en.readConfObject)(a,"type"),s=(0,en.readConfObject)(a,"assemblyNames"),c=(0,en.readConfObject)(a,"trackId");i===dd&&Array.isArray(s)&&s.some(d=>typeof d=="string"&&fe(e,d)===r)&&typeof c=="string"&&c!==n&&o.push(c)}return n?[n,...o]:o}var tn=m(K(),1),es=m(oc(),1),nn=m(ae(),1);var pd="SyntenyTrack",ud="Synteny adapters";function md(e){if((0,tn.readConfObject)(e,"type")===pd)return!0;let t=e.adapter?.type;if(typeof t!="string"||!(0,nn.isStateTreeNode)(e))return!1;let{pluginManager:n}=(0,nn.getEnv)(e);return!!n?.hasAdapterType(t)&&n.getAdapterType(t).adapterMetadata?.category===ud}function ts(e,t){let n=new Set(t),r=[];for(let o of e.tracks){let a=(0,tn.readConfObject)(o,"assemblyNames"),i=(0,tn.readConfObject)(o,"trackId");if(md(o)&&typeof i=="string"&&Array.isArray(a)){let s=a.filter(c=>typeof c=="string"&&n.has(fe(e,c))).length;s>=2&&r.push({trackId:i,name:(0,es.getTrackName)(o,e),coverage:s})}}return r.sort((o,a)=>a.coverage-o.coverage)}function ns(e,t,n="image/svg+xml"){let r=URL.createObjectURL(new Blob([e],{type:n})),o=document.createElement("a");o.href=r,o.download=t,o.click(),setTimeout(()=>{URL.revokeObjectURL(r)},0)}var os=Zi.actions(e=>({showInLinearView(t){let n=(0,ge.getSession)(e),r=t.assembly===e.graphRegion?.assemblyName,o=Ci({session:n,location:t.location,assembly:t.assembly,connectedViewId:e.connectedViewId,tracks:Qi({session:n,assemblyName:t.assembly,first:r?e.sourceTrackId:void 0})});r&&e.pairWithLinearView(o)},highlightInLinearView(t){Bi({session:(0,ge.getSession)(e),location:t.location,assembly:t.assembly,connectedViewId:e.connectedViewId})},showSyntenyView(t){Ei({session:(0,ge.getSession)(e),contributors:e.launchableAssemblies,trackId:t,graphTrackId:e.sourceTrackId})}})).views(e=>({get syntenyLaunchTracks(){let t=e.launchableAssemblies.map(n=>n.sample);return t.length>=2?ts((0,ge.getSession)(e),t):[]}})).views(e=>({walkRowSampleMenuItems(){let{disagreeing:t}=e.walkRowSampleChoices,n=e.walkRowSamples,r=o=>o.join(`
|
|
5
5
|
`)===n?.join(`
|
|
6
6
|
`);return[{type:"radio",label:"Every sample",checked:n===void 0,onClick:()=>{e.setWalkRowSamples(void 0)}},...t.length>0?[{type:"radio",label:"Where walk and call disagree",checked:r(t),onClick:()=>{e.setWalkRowSamples(t)}}]:[],{type:"radio",label:"Choose samples...",checked:n!==void 0&&!r(t),onClick:()=>{(0,ge.getSession)(e).queueDialog(o=>[yo,{model:e,onClose:o}])}}]},walkRowGroupMenuItems(){let t=e.walkRowGroups?e.walkRowGroupBy?.field:void 0;return[{type:"radio",label:"None",checked:t===void 0,onClick:()=>{e.setWalkRowGroupBy(void 0)}},...e.walkRowGroupFields.map(n=>({type:"radio",label:n,checked:t===n,onClick:()=>{e.setWalkRowGroupBy({field:n})}}))]},layoutOptionMenuItems({repeat:t=!0}={}){return[...Ge.has(e.chosenLayoutMode)?[{label:"Fold variants",subMenu:So.map(({bp:n,label:r})=>({type:"radio",label:r,checked:e.tubeMapFold===n,disabled:n>0&&e.graph?.reads!==void 0,onClick:()=>{e.setTubeMapFold(n),e.recomputeLayout()}}))}]:[],...t&&e.chosenLayoutMode==="walkrows"&&e.repeatChoices.length>0?[{label:"Repeat",subMenu:[{type:"radio",label:"Whole window",checked:!e.selectedRepeat,onClick:()=>{e.setRepeatKey("")}},...e.repeatChoices.map(({key:n,name:r,unit:o})=>({type:"radio",label:`${r} \xB7 ${o.toLocaleString()} bp unit`,checked:e.repeatKey===n,onClick:()=>{e.setRepeatKey(n)}}))]}]:[],...e.chosenLayoutMode==="walkrows"&&e.walkRowBars?[{label:"Samples",subMenu:this.walkRowSampleMenuItems()}]:[],...e.chosenLayoutMode==="walkrows"&&e.walkRowBars&&e.walkRowGroupFields.length>0?[{label:"Group by...",subMenu:this.walkRowGroupMenuItems()}]:[]]},showMenuItems(){return[{type:"checkbox",label:"Show bubble halos",checked:e.showBubbles,onClick:()=>{e.setShowBubbles(!e.showBubbles)}},{type:"checkbox",label:"Show deletion edges",checked:e.showDeletionEdges,onClick:()=>{e.toggleDeletionEdges()}},{type:"checkbox",label:"Show hover highlight",checked:e.chosenHighlightOnHover,onClick:()=>{e.setHighlightOnHover(!e.chosenHighlightOnHover)}},{type:"checkbox",label:"Show genes on the backbone",checked:e.showGenes,onClick:()=>{e.setShowGenes(!e.showGenes)}},...e.referenceStripApplies?[{type:"checkbox",label:"Show reference strip",checked:e.showReferenceStrip,onClick:()=>{e.setShowReferenceStrip(!e.showReferenceStrip)}}]:[]]},exportMenuItems(){return[{label:"Export SVG",icon:ti,disabled:e.figureUnavailable!==void 0,disabledHelpText:e.figureUnavailable,onClick:()=>{let t=e.figure();t&&ns(t,`${(e.graph?.name??"graph").replaceAll(/[^\w.-]+/g,"_")}.svg`)}},{label:"Copy figure spec",icon:qa,disabled:e.figureSpecUnavailable!==void 0,disabledHelpText:e.figureSpecUnavailable,onClick:()=>{let t=e.figureSpec(),n=(0,ge.getSession)(e);navigator.clipboard.writeText(`${JSON.stringify(t,null,2)}
|
|
7
|
-
`).then(()=>{n.notify("Figure spec copied. Save it as spec.json and run: npx -p @jbrowse/bandage-core bandage-figure spec.json -o figure.svg","info")}).catch(r=>{n.notify(`Could not copy the figure spec: ${String(r)}`)})}}]},highlightMenuItems({picks:t=!0}={}){let n=t?e.walkChoices:[];if(e.walkChoices.length===0||!e.liftsWalks||!t&&e.walkLayers.length===0)return[];let r=a=>e.walkLayers.some(i=>i.walk===a),o=n.length>Ro;return[{type:"subHeader",label:"Highlight"},...o?[{label:"Choose haplotypes...",onClick:()=>{(0,ge.getSession)(e).queueDialog(a=>[wo,{model:e,onClose:a}])}}]:[],...(o?n.filter(a=>r(a.name)):n).map(a=>({type:"checkbox",label:a.label,checked:r(a.name),onClick:()=>{e.toggleWalk(a.name)}})),{label:"Clear highlights",disabled:e.walkLayers.length===0,onClick:()=>{e.setWalkLayers([])}},...e.drawnWalks.length>0?[{label:"Color highlighted...",onClick:()=>{(0,ge.getSession)(e).queueDialog(a=>[ko,{model:e,onClose:a}])}}]:[],...e.walkLayers.length>1&&e.modeDrawsNodes?[{type:"subHeader",label:"Arrange"},...Jr.map(({value:a,label:i})=>({type:"radio",label:a==="walk"?"A panel per haplotype":i,checked:e.facet.field===a,onClick:()=>{e.setFacet(a)}}))]:[]]},colorSchemeLabel(t){let n=yn.find(r=>r.value===t)?.label??t;return t==="auto"?`${n} (${this.colorSchemeLabel(e.effectiveColorScheme)})`:n},graphMenuItems(){let t=this.layoutOptionMenuItems();return[{label:`Layout: ${O(e.chosenLayoutMode).label.replace(/ layout$/,"")}`,icon:Za,subMenu:[...Yr.map(n=>({type:"radio",label:n.label,checked:e.chosenLayoutMode===n.value,disabled:e.graph?!n.available(e.graph):!1,disabledHelpText:n.description,onClick:()=>{e.switchLayout(n.value)}})),...t.length>0?[{type:"divider"},...t]:[],...e.hostPlacesX?[]:[{type:"divider"},{label:"Zoom to fit",onClick:()=>{e.refitView()}}]]},{label:`Color: ${this.colorSchemeLabel(e.chosenColorScheme)}`,icon:ei,subMenu:yn.map(n=>({type:"radio",label:this.colorSchemeLabel(n.value),checked:e.chosenColorScheme===n.value,onClick:()=>{e.setColorScheme(n.value)}}))},{label:"Show...",icon:Qr,subMenu:this.showMenuItems()}]},launchMenuItems(){let t=[];for(let n of ka({contributors:e.launchableAssemblies,syntenyTracks:e.syntenyLaunchTracks,onShowLinear:r=>{e.showInLinearView(r)},onShowSynteny:r=>{e.showSyntenyView(r)}}))(0,rs.pushLaunchViewMenuItem)(t,n);return t}}));function rn(){return os}function pr(){return Y.types.compose("GraphGenomeView",as.BaseViewModel,rn(),Y.types.model({type:Y.types.literal("GraphGenomeView"),gfaLocation:Y.types.maybe(Y.types.frozen()),loadedRegion:Y.types.maybe(Y.types.frozen()),loadedTrackId:Y.types.optional(Y.types.string,""),subgraphContext:Y.types.optional(Y.types.number,1),subgraphHaplotypes:Y.types.maybe(Y.types.frozen()),maxRegionBp:Y.types.optional(Y.types.number,Xe)})).volatile(()=>({widthMeasured:!1})).actions(e=>{let t=e.setWidth;return{setWidth(n){t(n),e.widthMeasured=!0}}}).views(e=>({get rpcSessionId(){return e.id},get paneWidth(){return e.width},get paneMeasured(){return e.widthMeasured},get cutHaplotypes(){let t=this.sourceTrack;return e.subgraphHaplotypes??(t?Ze(le(e,t)):void 0)},get sourceGfaLocation(){return e.gfaLocation},get sourceTrack(){return e.loadedTrackId?(0,is.getSession)(e).tracks.find(t=>t.trackId===e.loadedTrackId):void 0},get canRetryLoad(){return e.gfaLocation!==void 0||e.loadedTrackId!==""&&e.loadedRegion!==void 0}})).views(e=>({get hasPendingSource(){return e.canRetryLoad&&!e.graph&&!e.loadCanceled},menuItems(){return[...e.exportMenuItems(),...e.launchMenuItems()]}})).actions(e=>{let t=e.clearGraph;return{clearGraph(){t(),e.gfaLocation=void 0,e.loadedRegion=void 0,e.loadedTrackId=""},load(){let n=e.loadedRegion;if(e.gfaLocation)return e.displayName||e.setDisplayName(Ye(e.gfaLocation)),e.loadGFAFromLocation(e.gfaLocation,n);if(!e.loadedTrackId||!n)return;let r=e.sourceTrack,o=n.end-n.start,a=r?$t(Ht(r),n.assemblyName):void 0;if(!r)e.setError(new Error(`The track this graph was cut from, "${e.loadedTrackId}", is not in this session`));else if(a)e.setError(new Error(a));else if(o>e.maxRegionBp)e.setError(new Error(`Region too large (${ye(o)}) \u2014 zoom in to view graph (max ${ye(e.maxRegionBp)})`));else return e.cutSubgraph(le(e,r),n,{hops:e.subgraphContext,haplotypes:e.cutHaplotypes,...e.cutsWholeWalks?{snarls:"overlapping"}:{}})}}}).actions(e=>({retryLoad(){e.load()},switchLayout(t){let n=e.cutsWholeWalks;return e.setLayoutMode(t),e.loadedTrackId&&e.cutsWholeWalks!==n?e.load():e.recomputeLayout()},afterAttach(){e.graph||e.load(),(0,Y.addDisposer)(e,(0,ss.reaction)(()=>e.walkStrip,()=>{e.loadedTrackId&&!O(e.chosenLayoutMode).wholeWalks&&e.load()}))}}))}var ld=(0,ps.defineLaunchKeys)()({});function ur(e){e.addViewType(()=>new ds.default({name:"GraphGenomeView",displayName:"Graph genome view",stateModel:pr(),launchKeys:ld,ReactComponent:(0,cs.lazy)(()=>import("./chunks/GraphGenomeView-WPF4JRXE.js"))}))}var us=m(K(),1),Pe=m(me(),1),mr=["MultiWaySyntenyDisplay","LinearSyntenyDisplay","DotplotDisplay","ChordSyntenyDisplay"];function gd(e){let t=e.getElementTypesInGroup("display"),n=o=>t.find(a=>a.name===o),r=o=>o&&Object.assign(Object.create(o),{adapterCapabilities:["headerLanes"]});return[n("LinearGraphDisplay"),n("LinearBasicDisplay"),...mr.map(o=>r(n(o)))].filter(o=>o!==void 0)}function lr(e){e.addTrackType(()=>{let t=(0,us.ConfigurationSchema)("GraphTrack",{},{baseConfiguration:(0,Pe.createBaseTrackConfig)(e),explicitIdentifier:"trackId"}),n=new Pe.TrackType({name:"GraphTrack",displayName:"Pangenome graph track",configSchema:t,stateModel:(0,Pe.createBaseTrackModel)(e,"GraphTrack",t)});for(let r of gd(e))n.addDisplayType(r);return n})}function gr(e){e.addToExtensionPoint("LaunchView-GraphGenomeView",t=>{let{session:n,...r}=t;return n.addView("GraphGenomeView",r),t})}var Cs=m(wt(),1),Bs=m(ls(),1);var fs=m(K(),1),bs=m(hs(),1),hr=m(ae(),1);function ys(){return(0,fs.ConfigurationSchema)("LinearGraphDisplay",{layoutMode:{type:"stringEnum",model:hr.types.enumeration("LayoutMode",Ur),defaultValue:"auto"},colorScheme:{type:"stringEnum",model:hr.types.enumeration("ColorScheme",qr),defaultValue:"auto"},highlightOnHover:{type:"boolean",defaultValue:!0},...(0,bs.trackHeightConfigSchemaFields)({defaultHeight:300,height:"the height of the track the graph is drawn in"})},{explicitlyTyped:!0,explicitIdentifier:"displayId"})}var Ts=m(wt(),1);var Ce=m(K(),1),Gs=m(me(),1),Ns=m(ks(),1),As=m(Fr(),1),Be=m(ne(),1),Ps=m(Ss(),1),F=m(ae(),1),on=m(Ls(),1);var Ie=m(yt(),1);function Ms(e){return e instanceof Error&&(e.name==="NodeLimitError"||e.regionTooLarge===!0||/reads more than nodeLimit|^Subgraph size limit of \d+ nodes exceeded/.test(e.message))}function vs(e,t){if(e?.refName!==t.refName||e.assemblyName!==t.assemblyName)return!1;let n=e.end-e.start;return t.end-t.start>=n&&t.end>e.start-n&&t.start<e.end+n}var hd=(0,Ts.lazy)(()=>import("./chunks/GraphTrackSettingsDialog-H4QX5DAF.js"));function Is(e){return F.types.compose("LinearGraphDisplay",Gs.BaseDisplay,(0,Ps.default)(),rn(),F.types.model({type:F.types.literal("LinearGraphDisplay"),configuration:(0,Ce.ConfigurationReference)(e),pane:F.types.maybe(F.types.frozen()),overviewRowsChoice:F.types.maybe(F.types.frozen()),overviewRowOrder:F.types.maybe(F.types.frozen()),cutRegion:F.types.maybe(F.types.frozen()),coarseCut:F.types.optional(F.types.boolean,!1),maxRegionBp:F.types.optional(F.types.number,Xe),subgraphContext:F.types.optional(F.types.number,1),subgraphHaplotypes:F.types.maybe(F.types.frozen())})).preProcessSnapshot(t=>{let{pane:n,overviewRowsChoice:r,overviewRowOrder:o,...a}=t;if(!n)return a;let{type:i,...s}=n;return{...s,...a}}).volatile(()=>({recuts:0,settledWindow:void 0,dense:void 0,haplotypeNames:void 0})).views(t=>({get adapterConfig(){return le(t,t.parentTrack.configuration)},get defaultLayoutMode(){return(0,Ce.getConf)(t,"layoutMode")},get defaultColorScheme(){return(0,Ce.getConf)(t,"colorScheme")},get defaultHighlightOnHover(){return(0,Ce.getConf)(t,"highlightOnHover")},get drawsGenomicCoordinates(){return t.layoutResult===void 0||t.hostPlacesX},get canvasHeight(){return t.height},get canRetryLoad(){return t.cutRegion!==void 0},get cutHaplotypes(){return this.chosenHaplotypes},get chosenHaplotypes(){return t.subgraphHaplotypes??Ze(this.adapterConfig)??Bn(t.parentTrack.configuration)},get coarseAboveBpPerPx(){let r=t.adapterConfig.coarse?.aboveBpPerPx;return typeof r=="number"?r:void 0}})).views(t=>({tierAt(n){let r=t.coarseAboveBpPerPx;return r!==void 0&&n>r?"coarse":"fine"},capFor(n){return n==="coarse"?1/0:t.maxRegionBp},get cutTier(){return t.coarseCut&&t.coarseAboveBpPerPx!==void 0?"coarse":"fine"}})).views(t=>({get settledCapBp(){let n=t.settledWindow;return n?t.capFor(t.tierAt(n.bpPerPx)):1/0}})).views(t=>({get regionTooLarge(){let n=t.settledWindow;return n!==void 0&&n.end-n.start>t.settledCapBp},get regionTooLargeReason(){let n=t.settledWindow;return n?`Region too large for a graph cut (${ye(n.end-n.start)}, max ${ye(t.settledCapBp)})`:""},get zoomCanReleaseGate(){return!0},get fetchCanceled(){return t.loadCanceled}})).views(t=>({get svgReady(){return(0,Ns.computeSvgReady)({error:t.error,regionTooLarge:t.regionTooLarge,extraTerminal:!1,fetchCanceled:t.loadCanceled},()=>!t.isLoading&&t.hasGraph&&!!t.layoutResult)}})).views(t=>({get displayPhase(){return(0,on.computeDisplayStatusPhase)({regionTooLarge:t.regionTooLarge,error:t.error??t.renderError},()=>(0,on.computeActivityPhase)({isMinimized:t.isMinimized,fetchInert:!1,viewportEmpty:t.host?.initialized===!0&&t.host.hasVisibleContent===!1,isLoading:t.isLoading||!t.hasGraph,fetchCanceled:t.loadCanceled,awaitingDependentData:!1,rendersCanvas:!0,canvasDrawn:t.painted&&t.geometryPainted},()=>!0,()=>t.host?.effectiveBodyMounted??!0))}})).actions(t=>({setSubgraphContext(n){t.subgraphContext=n},setSubgraphHaplotypes(n){t.subgraphHaplotypes=n,t.dense=void 0},setDense(n){t.dense=n},setHaplotypeNames(n){t.haplotypeNames=n},setMaxRegionBp(n){t.maxRegionBp=n},cut(){let n=t.cutRegion;if(!n)return;let r=$t(Ht(t.parentTrack.configuration),n.assemblyName);if(r){t.clearGraph(),t.setError(new Error(r));return}let o=t.cutTier==="coarse";return t.cutSubgraph(t.adapterConfig,n,{hops:o?0:t.subgraphContext,haplotypes:t.chosenHaplotypes,tier:o?"coarse":void 0,...O(t.chosenLayoutMode).wholeWalks?{snarls:"overlapping"}:{}})}})).actions(t=>({recutAt(n){let r=t.tierAt(n.bpPerPx);return t.coarseCut=r==="coarse",t.cutRegion=Un(n,t.capFor(r),O(t.chosenLayoutMode).cutMargins),t.recuts++,t.cut()}})).actions(t=>({settleOn(n){t.settledWindow=n;let r=O(t.chosenLayoutMode).cutMargins;return t.regionTooLarge||vs(t.dense,n)||!t.loadCanceled&&t.tierAt(n.bpPerPx)===t.cutTier&&bi(t.cutRegion,n,r)?!1:(Promise.resolve(t.recutAt(n)).then(()=>{(0,F.isAlive)(t)&&Ms(t.error)&&this.refuseDenseCut(n)}),!0)},refuseDenseCut(n){t.setDense(n),t.cutRegion=void 0,this.settleOn(t.settledWindow??n)},switchLayout(n){let r=O(t.chosenLayoutMode);t.setLayoutMode(n);let o=O(n),a=t.host?Yt(t.host):void 0;return a&&!t.regionTooLarge&&(o.cutMargins!==r.cutMargins||o.wholeWalks!==r.wholeWalks)?t.recutAt(a):t.recomputeLayout()},retryLoad(){t.cut()},reload(){t.cut()},cancelFetchByUser(){t.stopLoad()}})).actions(t=>({async fetchHaplotypeNames(n){try{let r=await(0,Be.getSession)(t).rpcManager.call((0,Be.getRpcSessionId)(t),"GetGraphHaplotypes",{adapterConfig:n});(0,F.isAlive)(t)&&t.setHaplotypeNames(r)}catch(r){console.warn("[LinearGraphDisplay] no haplotype names",r)}}})).actions(t=>({forceLoad(){let n=t.settledWindow;n&&(t.setMaxRegionBp(Math.ceil(n.end-n.start)),t.settleOn(n))},afterAttach(){t.cutRegion&&!t.graph&&t.cut(),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>Ra(t.adapterConfig)?t.adapterConfig:void 0,n=>{t.setHaplotypeNames(void 0),n&&t.fetchHaplotypeNames(n)},{fireImmediately:!0,name:"GraphHaplotypeNames"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>t.hostPlacesX,n=>{n||t.releaseHost()},{name:"GraphHostPlacesX"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>t.hostFrame,n=>{n&&t.hostTransform(n.scale,n.translateX)},{equals:(n,r)=>n?.scale===r?.scale&&n?.translateX===r?.translateX,fireImmediately:!0,name:"GraphHostFrame"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>`${t.facet.field} ${t.facetPlacement?.count}`,()=>{let n=t.facetGridIn(t.paneCeiling)?.total??0;(t.facetGrid?.total??0)>t.height&&t.setHeight(Math.max(t.height,Math.ceil(n)))},{name:"GraphFacetHeight"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>t.host?.coarseDynamicBlocks,n=>{let{host:r}=t,o=n&&r?Yt(r):void 0;o&&t.settleOn(o)},{fireImmediately:!0,name:"GraphHostSettle"}))}})).views(t=>({get graphViewSpec(){let n=t.host?Yt(t.host):void 0,r=t.sourceTrackId;if(!n||!r||!t.hasGraph||t.coarseCut||t.regionTooLarge)return;let o=Math.floor(n.start),a=Math.ceil(n.end);return{loadedTrackId:r,loadedRegion:{refName:n.refName,assemblyName:n.assemblyName,start:o,end:a},subgraphContext:t.subgraphContext,subgraphHaplotypes:t.chosenHaplotypes,maxRegionBp:Math.max(t.maxRegionBp,a-o),layoutMode:t.chosenLayoutMode,colorScheme:t.chosenColorScheme,referencePath:t.referencePath,geneTrackId:t.geneTrackId,showGenes:t.showGenes,showBubbles:t.showBubbles,showDeletionEdges:t.showDeletionEdges,walkLayers:t.walkLayers,facet:(0,F.getSnapshot)(t.facet)}}})).actions(t=>({openGraphView(){let n=t.graphViewSpec;n&&(0,Be.getSession)(t).addView("GraphGenomeView",n)}})).views(t=>({cutMenuItems(){if(!Sa(t.adapterConfig))return[];let n=Ze(t.adapterConfig),r=Bn(t.parentTrack.configuration),o=t.haplotypeNames,a=t.subgraphHaplotypes,i=s=>{t.setSubgraphHaplotypes(s),t.cut()};return[{type:"subHeader",label:"Load"},{type:"radio",label:o?`Every haplotype in the graph (${o.length.toLocaleString()})`:"Every haplotype in the graph",checked:a?a.length===0:!n&&!r,onClick:()=>{i([])}},...n||r?[{type:"radio",label:n?"The track's default haplotypes":`The track's ${r?.length} assemblies`,checked:a===void 0,onClick:()=>{i(void 0)}}]:[],{type:"radio",label:"Chosen in Settings...",checked:(a?.length??0)>0,onClick:()=>{this.openSettings()}}]},openSettings(){(0,Be.getSession)(t).queueDialog(n=>[hd,{model:t,open:!0,onClose:n}])},async renderSvg(n){let{renderGraphTrackSvg:r}=await import("./chunks/renderSvg-35VDH2K7.js");return r(t,n)},trackMenuItems(){let n=t.launchMenuItems();(0,As.pushLaunchViewMenuItem)(n,{label:"Graph genome view",icon:_t,disabled:!t.graphViewSpec,disabledHelpText:"Zoom in until the track cuts a graph",onClick:()=>{t.openGraphView()}});let r=[...this.cutMenuItems(),...t.highlightMenuItems()];return[...r.length>0?[{label:"Haplotypes",icon:xa,subMenu:r}]:[],...t.graphMenuItems(),{label:"Settings",icon:La,onClick:()=>{this.openSettings()}},...n]}}))}function fr(e){e.addDisplayType(()=>{let t=ys();return Object.assign(new Bs.default({name:"LinearGraphDisplay",displayName:"Graph",configSchema:t,stateModel:Is(t),trackType:["GraphTrack","FeatureTrack","SyntenyTrack"],viewType:"LinearGenomeView",ReactComponent:(0,Cs.lazy)(()=>import("./chunks/LinearGraphDisplay-ZJNR2KCT.js"))}),{adapterCapabilities:["getSubgraph"]})})}var Ds=m(Wt(),1);var br=m(K(),1),Es=m(ae(),1);function yr(e){let{uri:t,baseUri:n,csi:r}=e;return typeof t=="string"?{...e,bubblesLocation:{uri:t,baseUri:n},index:{indexType:r?"CSI":"TBI",location:{uri:`${t}.${r?"csi":"tbi"}`,baseUri:n}}}:e}var fd=(0,br.ConfigurationSchema)("MinigraphBubbleAdapter",{bubblesLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.bb.bed.gz",locationType:"UriLocation"}},index:(0,br.ConfigurationSchema)("MinigraphBubbleIndex",{indexType:{model:Es.types.enumeration("IndexType",["TBI","CSI"]),type:"stringEnum",defaultValue:"TBI"},location:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.bb.bed.gz.tbi",locationType:"UriLocation"}}}),assemblyNameToPanSN:{type:"frozen",defaultValue:{}}},{explicitlyTyped:!0,preProcessSnapshot:yr}),Fs=fd;function wr(e){e.addAdapterType(()=>new Ds.default({name:"MinigraphBubbleAdapter",displayName:"Minigraph bubble BED adapter",normalizeSnapshot:yr,configSchema:Fs,adapterMetadata:{category:"Graph adapters"},getAdapterClass:()=>import("./chunks/MinigraphBubbleAdapter-PP3LVTLY.js").then(t=>t.default)}))}var Os=m(Wt(),1);var an=m(K(),1),Hs=m(ae(),1);function gt(e,t,n){return{indexType:n?"CSI":"TBI",location:{uri:`${e}.${n?"csi":"tbi"}`,baseUri:t}}}function Vs(e){let{uri:t,baseUri:n,csi:r}=e;return typeof t=="string"?{...e,segmentsLocation:{uri:`${t}.segs.bed.gz`,baseUri:n},segmentsIndex:gt(`${t}.segs.bed.gz`,n,r),linksLocation:{uri:`${t}.links.bed.gz`,baseUri:n},linksIndex:gt(`${t}.links.bed.gz`,n,r)}:e}function bd(e){let{walksUri:t,baseUri:n,csi:r}=e;if(typeof t!="string")return e;let o=a=>`${t}.${a}.bed.gz`;return{...e,walksLocation:{uri:o("walks"),baseUri:n},walksIndex:gt(o("walks"),n,r),segmentsLocation:{uri:o("nodes"),baseUri:n},segmentsIndex:gt(o("nodes"),n,r),linksLocation:{uri:o("links"),baseUri:n},linksIndex:gt(o("links"),n,r)}}function kr(e){let{coarse:t,baseUri:n,csi:r}=e;return bd(Vs(typeof t=="object"&&t!==null?{...e,coarse:Vs({baseUri:n,csi:r,...t})}:e))}var ht=(e,t)=>(0,an.ConfigurationSchema)(e,{indexType:{model:Hs.types.enumeration("IndexType",["TBI","CSI"]),type:"stringEnum",defaultValue:"TBI"},location:{type:"fileLocation",defaultValue:{uri:t,locationType:"UriLocation"}}}),yd=(0,an.ConfigurationSchema)("RgfaTabixCoarseTier",{aboveBpPerPx:{type:"maybeNumber"},segmentsLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.tier.segs.bed.gz",locationType:"UriLocation"}},segmentsIndex:ht("RgfaCoarseSegmentsIndex","/path/to/graph.tier.segs.bed.gz.tbi"),linksLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.tier.links.bed.gz",locationType:"UriLocation"}},linksIndex:ht("RgfaCoarseLinksIndex","/path/to/graph.tier.links.bed.gz.tbi")}),wd=(0,an.ConfigurationSchema)("RgfaTabixAdapter",{segmentsLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.segs.bed.gz",locationType:"UriLocation"}},segmentsIndex:ht("RgfaSegmentsIndex","/path/to/graph.segs.bed.gz.tbi"),linksLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.links.bed.gz",locationType:"UriLocation"}},linksIndex:ht("RgfaLinksIndex","/path/to/graph.links.bed.gz.tbi"),walksLocation:{type:"fileLocation",defaultValue:{uri:"",locationType:"UriLocation"}},walksIndex:ht("RgfaWalksIndex",""),walkChunk:{type:"integer",defaultValue:65536},walkStepBudget:{type:"integer",defaultValue:4e6},walkByteBudget:{type:"integer",defaultValue:8e6},defaultHaplotypes:{type:"stringArray",defaultValue:[]},assemblyNameToPanSN:{type:"frozen",defaultValue:{}},coarse:yd},{explicitlyTyped:!0,preProcessSnapshot:kr}),$s=wd;function Rr(e){e.addAdapterType(()=>new Os.default({name:"RgfaTabixAdapter",displayName:"Indexed rGFA adapter",normalizeSnapshot:kr,configSchema:$s,adapterCapabilities:["getSubgraph"],adapterMetadata:{category:"Graph adapters"},getAdapterClass:()=>import("./chunks/RgfaTabixAdapter-2CIFHOB3.js").then(t=>t.default)}))}var kd=new Set(["RgfaTabixAdapter","GbzBaseSyntenyAdapter"]);function Rd(e){return Er(e).toLowerCase().endsWith(".gbz.db")}function Sd(e){let t=e.adapter;return t?.type==="GbzBaseSyntenyAdapter"&&!t.assemblyNames?.length&&Array.isArray(e.assemblyNames)&&e.assemblyNames.length>0?{...e,adapter:{...t,assemblyNames:e.assemblyNames}}:e}function xd(e,t,n){if((!n||n==="GbzBaseSyntenyAdapter")&&Rd(e))return{type:"GbzBaseSyntenyAdapter",gbzDbLocation:e,...t?{haplotypeIndexLocation:t}:{}};if((!n||n==="RgfaTabixAdapter")&&Dr(e))return Vr({choice:"RgfaTabixAdapter",loc:e,indexLoc:t,assembly:"",sample:""})}function Sr(e){e.addToExtensionPoint("Core-preProcessTrackConfig",Sd),e.addToExtensionPoint("Core-guessAdapterForLocation",t=>(n,r,o)=>xd(n,r,o)??t(n,r,o)),e.addToExtensionPoint("Core-guessTrackTypeForLocation",t=>(n,r)=>kd.has(n)?"GraphTrack":t(n,r))}var zs=m(ne(),1),sn=m(ic(),1),xr=m(ac(),1),Xs=m(sc(),1);function _s(e){let t;if(q(e)){let{refName:n,start:r,end:o,assemblyName:a}=e;typeof n=="string"&&typeof r=="number"&&typeof o=="number"&&(t={refName:n,start:r,end:o,assemblyName:typeof a=="string"?a:void 0})}return t}function Ld(e,t,n){let r=e.connectedViewId;return r===void 0||r===t||!n.has(r)}function Ws(e,t){return e.assemblyName===void 0||t===void 0||t.includes(e.assemblyName)}function Md(e){return(Array.isArray(e.tracks)?e.tracks:[]).flatMap(n=>q(n)&&Array.isArray(n.displays)?n.displays.filter(r=>q(r)&&r.type==="LinearGraphDisplay"):[])}function js(e,t,n){let r=[],o=ut(e),a=new Set(o.map(i=>q(i)?i.id:void 0));for(let i of o){if(q(i)&&i.id===t)for(let s of Md(i)){let c=_s(s.hoverHighlight);c&&Ws(c,n)&&r.push({key:typeof s.id=="string"?s.id:"graph-track",region:c})}if(q(i)&&i.type==="GraphGenomeView"&&Ld(i,t,a)){let s=_s(i.hoverHighlight);s&&Ws(s,n)&&r.push({key:typeof i.id=="string"?i.id:"graph",region:s})}}return r}var Ee=m(ue(),1),vd=(0,Xs.makeStyles)()(e=>({highlight:{height:"100%",position:"absolute",background:(0,sn.alpha)(e.palette.primary.main,.08),borderLeft:`1px solid ${(0,sn.alpha)(e.palette.primary.main,.4)}`,borderRight:`1px solid ${(0,sn.alpha)(e.palette.primary.main,.4)}`,pointerEvents:"none",zIndex:10}})),Td=(0,xr.observer)(function({model:t,region:n}){let{classes:r}=vd(),o=t.getHighlightCoords(n);return o?(0,Ee.jsx)("div",{"data-testid":"graph-node-highlight",className:r.highlight,style:{left:o.left,width:o.width}}):null}),Gd=(0,xr.observer)(function({model:t}){let{views:n}=(0,zs.getSession)(t);return(0,Ee.jsx)(Ee.Fragment,{children:js([...n],t.id,t.assemblyNames).map(({key:r,region:o})=>(0,Ee.jsx)(Td,{model:t,region:o},`graph-hover-${r}`))})}),Ys=Gd;var Us=m(ue(),1),Nd="LinearGenomeView-TracksContainerComponent";function Lr(e){e.contributeToExtensionPoint(Nd,({model:t})=>(0,Us.jsx)(Ys,{model:t},"graphgenomeview-hover-highlight"))}var Ks=m(me(),1);function Ad(e){return e.views(t=>({get adapterConfig(){return le(t,t.parentTrack.configuration)}}))}function Mr(e){e.addToExtensionPoint("Core-extendPluggableElement",t=>(t instanceof Ks.DisplayType&&mr.includes(t.name)&&t.extendStateModel(Ad),t))}var qs="GraphGenomeView";var Js="6.9.1";var vr=class extends Zs.default{constructor(){super(...arguments);this.name=qs;this.version=Js}install(n){ur(n),fr(n),lr(n),gr(n),Lr(n),Rr(n),wr(n),Dn(n),Vn(n),Sr(n),Mr(n),n.addRpcMethod(()=>new nt(n)),n.addRpcMethod(()=>new tt(n)),n.addRpcMethod(()=>new et(n)),n.addRpcMethod(()=>new Qe(n))}configure(n){try{(0,Qs.isAbstractMenuManager)(n.rootModel)&&n.rootModel.appendToSubMenu(["Add"],{label:"Graph genome view",icon:_t,onClick:r=>{r.addView("GraphGenomeView",{})}})}catch(r){console.warn("[GraphGenomeView] could not add the Add menu entry",r)}}};export{vr as default};
|
|
7
|
+
`).then(()=>{n.notify("Figure spec copied. Save it as spec.json and run: npx -p @jbrowse/bandage-core bandage-figure spec.json -o figure.svg","info")}).catch(r=>{n.notify(`Could not copy the figure spec: ${String(r)}`)})}}]},highlightMenuItems({picks:t=!0}={}){let n=t?e.walkChoices:[];if(e.walkChoices.length===0||!e.liftsWalks||!t&&e.walkLayers.length===0)return[];let r=a=>e.walkLayers.some(i=>i.walk===a),o=n.length>Ro;return[{type:"subHeader",label:"Highlight"},...o?[{label:"Choose haplotypes...",onClick:()=>{(0,ge.getSession)(e).queueDialog(a=>[wo,{model:e,onClose:a}])}}]:[],...(o?n.filter(a=>r(a.name)):n).map(a=>({type:"checkbox",label:a.label,checked:r(a.name),onClick:()=>{e.toggleWalk(a.name)}})),{label:"Clear highlights",disabled:e.walkLayers.length===0,onClick:()=>{e.setWalkLayers([])}},...e.drawnWalks.length>0?[{label:"Color highlighted...",onClick:()=>{(0,ge.getSession)(e).queueDialog(a=>[ko,{model:e,onClose:a}])}}]:[],...e.walkLayers.length>1&&e.modeDrawsNodes?[{type:"subHeader",label:"Arrange"},...Jr.map(({value:a,label:i})=>({type:"radio",label:a==="walk"?"A panel per haplotype":i,checked:e.facet.field===a,onClick:()=>{e.setFacet(a)}}))]:[]]},colorSchemeLabel(t){let n=yn.find(r=>r.value===t)?.label??t;return t==="auto"?`${n} (${this.colorSchemeLabel(e.effectiveColorScheme)})`:n},graphMenuItems(){let t=this.layoutOptionMenuItems();return[{label:`Layout: ${O(e.chosenLayoutMode).label.replace(/ layout$/,"")}`,icon:Za,subMenu:[...Yr.map(n=>({type:"radio",label:n.label,checked:e.chosenLayoutMode===n.value,disabled:e.graph?!n.available(e.graph):!1,disabledHelpText:n.description,onClick:()=>{e.switchLayout(n.value)}})),...t.length>0?[{type:"divider"},...t]:[],...e.hostPlacesX?[]:[{type:"divider"},{label:"Zoom to fit",onClick:()=>{e.refitView()}}]]},{label:`Color: ${this.colorSchemeLabel(e.chosenColorScheme)}`,icon:ei,subMenu:yn.map(n=>({type:"radio",label:this.colorSchemeLabel(n.value),checked:e.chosenColorScheme===n.value,onClick:()=>{e.setColorScheme(n.value)}}))},{label:"Show...",icon:Qr,subMenu:this.showMenuItems()}]},launchMenuItems(){let t=[];for(let n of ka({contributors:e.launchableAssemblies,syntenyTracks:e.syntenyLaunchTracks,onShowLinear:r=>{e.showInLinearView(r)},onShowSynteny:r=>{e.showSyntenyView(r)}}))(0,rs.pushLaunchViewMenuItem)(t,n);return t}}));function rn(){return os}function pr(){return Y.types.compose("GraphGenomeView",as.BaseViewModel,rn(),Y.types.model({type:Y.types.literal("GraphGenomeView"),gfaLocation:Y.types.maybe(Y.types.frozen()),loadedRegion:Y.types.maybe(Y.types.frozen()),loadedTrackId:Y.types.optional(Y.types.string,""),subgraphContext:Y.types.optional(Y.types.number,1),subgraphHaplotypes:Y.types.maybe(Y.types.frozen()),maxRegionBp:Y.types.optional(Y.types.number,Xe)})).volatile(()=>({widthMeasured:!1})).actions(e=>{let t=e.setWidth;return{setWidth(n){t(n),e.widthMeasured=!0}}}).views(e=>({get rpcSessionId(){return e.id},get paneWidth(){return e.width},get paneMeasured(){return e.widthMeasured},get cutHaplotypes(){let t=this.sourceTrack;return e.subgraphHaplotypes??(t?Ze(le(e,t)):void 0)},get sourceGfaLocation(){return e.gfaLocation},get sourceTrack(){return e.loadedTrackId?(0,is.getSession)(e).tracks.find(t=>t.trackId===e.loadedTrackId):void 0},get canRetryLoad(){return e.gfaLocation!==void 0||e.loadedTrackId!==""&&e.loadedRegion!==void 0}})).views(e=>({get hasPendingSource(){return e.canRetryLoad&&!e.graph&&!e.loadCanceled},menuItems(){return[...e.exportMenuItems(),...e.launchMenuItems()]}})).actions(e=>{let t=e.clearGraph;return{clearGraph(){t(),e.gfaLocation=void 0,e.loadedRegion=void 0,e.loadedTrackId=""},load(){let n=e.loadedRegion;if(e.gfaLocation)return e.displayName||e.setDisplayName(Ye(e.gfaLocation)),e.loadGFAFromLocation(e.gfaLocation,n);if(!e.loadedTrackId||!n)return;let r=e.sourceTrack,o=n.end-n.start,a=r?$t(Ht(r),n.assemblyName):void 0;if(!r)e.setError(new Error(`The track this graph was cut from, "${e.loadedTrackId}", is not in this session`));else if(a)e.setError(new Error(a));else if(o>e.maxRegionBp)e.setError(new Error(`Region too large (${ye(o)}) \u2014 zoom in to view graph (max ${ye(e.maxRegionBp)})`));else return e.cutSubgraph(le(e,r),n,{hops:e.subgraphContext,haplotypes:e.cutHaplotypes,...e.cutsWholeWalks?{snarls:"overlapping"}:{}})}}}).actions(e=>({retryLoad(){e.load()},switchLayout(t){let n=e.cutsWholeWalks;return e.setLayoutMode(t),e.loadedTrackId&&e.cutsWholeWalks!==n?e.load():e.recomputeLayout()},afterAttach(){e.graph||e.load(),(0,Y.addDisposer)(e,(0,ss.reaction)(()=>e.walkStrip,()=>{e.loadedTrackId&&!O(e.chosenLayoutMode).wholeWalks&&e.load()}))}}))}var ld=(0,ps.defineLaunchKeys)()({});function ur(e){e.addViewType(()=>new ds.default({name:"GraphGenomeView",displayName:"Graph genome view",stateModel:pr(),launchKeys:ld,ReactComponent:(0,cs.lazy)(()=>import("./chunks/GraphGenomeView-WPF4JRXE.js"))}))}var us=m(K(),1),Pe=m(me(),1),mr=["MultiWaySyntenyDisplay","LinearSyntenyDisplay","DotplotDisplay","ChordSyntenyDisplay"];function gd(e){let t=e.getElementTypesInGroup("display"),n=o=>t.find(a=>a.name===o),r=o=>o&&Object.assign(Object.create(o),{adapterCapabilities:["headerLanes"]});return[n("LinearGraphDisplay"),n("LinearBasicDisplay"),...mr.map(o=>r(n(o)))].filter(o=>o!==void 0)}function lr(e){e.addTrackType(()=>{let t=(0,us.ConfigurationSchema)("GraphTrack",{},{baseConfiguration:(0,Pe.createBaseTrackConfig)(e),explicitIdentifier:"trackId"}),n=new Pe.TrackType({name:"GraphTrack",displayName:"Pangenome graph track",configSchema:t,stateModel:(0,Pe.createBaseTrackModel)(e,"GraphTrack",t)});for(let r of gd(e))n.addDisplayType(r);return n})}function gr(e){e.addToExtensionPoint("LaunchView-GraphGenomeView",t=>{let{session:n,...r}=t;return n.addView("GraphGenomeView",r),t})}var Cs=m(wt(),1),Bs=m(ls(),1);var fs=m(K(),1),bs=m(hs(),1),hr=m(ae(),1);function ys(){return(0,fs.ConfigurationSchema)("LinearGraphDisplay",{layoutMode:{type:"stringEnum",model:hr.types.enumeration("LayoutMode",Ur),defaultValue:"auto"},colorScheme:{type:"stringEnum",model:hr.types.enumeration("ColorScheme",qr),defaultValue:"auto"},highlightOnHover:{type:"boolean",defaultValue:!0},...(0,bs.trackHeightConfigSchemaFields)({defaultHeight:300,height:"the height of the track the graph is drawn in"})},{explicitlyTyped:!0,explicitIdentifier:"displayId"})}var Ts=m(wt(),1);var Ce=m(K(),1),Gs=m(me(),1),Ns=m(ks(),1),As=m(Fr(),1),Be=m(ne(),1),Ps=m(Ss(),1),F=m(ae(),1),on=m(Ls(),1);var Ie=m(yt(),1);function Ms(e){return e instanceof Error&&(e.name==="NodeLimitError"||e.regionTooLarge===!0||/reads more than nodeLimit|^Subgraph size limit of \d+ nodes exceeded/.test(e.message))}function vs(e,t){if(e?.refName!==t.refName||e.assemblyName!==t.assemblyName)return!1;let n=e.end-e.start;return t.end-t.start>=n&&t.end>e.start-n&&t.start<e.end+n}var hd=(0,Ts.lazy)(()=>import("./chunks/GraphTrackSettingsDialog-H4QX5DAF.js"));function Is(e){return F.types.compose("LinearGraphDisplay",Gs.BaseDisplay,(0,Ps.default)(),rn(),F.types.model({type:F.types.literal("LinearGraphDisplay"),configuration:(0,Ce.ConfigurationReference)(e),pane:F.types.maybe(F.types.frozen()),overviewRowsChoice:F.types.maybe(F.types.frozen()),overviewRowOrder:F.types.maybe(F.types.frozen()),cutRegion:F.types.maybe(F.types.frozen()),coarseCut:F.types.optional(F.types.boolean,!1),maxRegionBp:F.types.optional(F.types.number,Xe),subgraphContext:F.types.optional(F.types.number,1),subgraphHaplotypes:F.types.maybe(F.types.frozen())})).preProcessSnapshot(t=>{let{pane:n,overviewRowsChoice:r,overviewRowOrder:o,...a}=t;if(!n)return a;let{type:i,...s}=n;return{...s,...a}}).volatile(()=>({recuts:0,settledWindow:void 0,dense:void 0,haplotypeNames:void 0})).views(t=>({get adapterConfig(){return le(t,t.parentTrack.configuration)},get defaultLayoutMode(){return(0,Ce.getConf)(t,"layoutMode")},get defaultColorScheme(){return(0,Ce.getConf)(t,"colorScheme")},get defaultHighlightOnHover(){return(0,Ce.getConf)(t,"highlightOnHover")},get drawsGenomicCoordinates(){return t.layoutResult===void 0||t.hostPlacesX},get canvasHeight(){return t.height},get canRetryLoad(){return t.cutRegion!==void 0},get cutHaplotypes(){return this.chosenHaplotypes},get chosenHaplotypes(){return t.subgraphHaplotypes??Ze(this.adapterConfig)??Bn(t.parentTrack.configuration)},get coarseAboveBpPerPx(){let r=t.adapterConfig.coarse?.aboveBpPerPx;return typeof r=="number"?r:void 0}})).views(t=>({tierAt(n){let r=t.coarseAboveBpPerPx;return r!==void 0&&n>r?"coarse":"fine"},capFor(n){return n==="coarse"?1/0:t.maxRegionBp},get cutTier(){return t.coarseCut&&t.coarseAboveBpPerPx!==void 0?"coarse":"fine"}})).views(t=>({get settledCapBp(){let n=t.settledWindow;return n?t.capFor(t.tierAt(n.bpPerPx)):1/0}})).views(t=>({get regionTooLarge(){let n=t.settledWindow;return n!==void 0&&n.end-n.start>t.settledCapBp},get regionTooLargeReason(){let n=t.settledWindow;return n?`Region too large for a graph cut (${ye(n.end-n.start)}, max ${ye(t.settledCapBp)})`:""},get zoomCanReleaseGate(){return!0},get fetchCanceled(){return t.loadCanceled}})).views(t=>({get svgReady(){return(0,Ns.computeSvgReady)({error:t.error,regionTooLarge:t.regionTooLarge,extraTerminal:!1,fetchCanceled:t.loadCanceled},()=>!t.isLoading&&t.hasGraph&&!!t.layoutResult)}})).views(t=>({get displayPhase(){return(0,on.computeDisplayStatusPhase)({regionTooLarge:t.regionTooLarge,error:t.error??t.renderError},()=>(0,on.computeActivityPhase)({isMinimized:t.isMinimized,fetchInert:!1,viewportEmpty:t.host?.initialized===!0&&t.host.hasVisibleContent===!1,isLoading:t.isLoading||!t.hasGraph,fetchCanceled:t.loadCanceled,awaitingDependentData:!1,rendersCanvas:!0,canvasDrawn:t.painted&&t.geometryPainted},()=>!0,()=>t.host?.effectiveBodyMounted??!0))}})).actions(t=>({setSubgraphContext(n){t.subgraphContext=n},setSubgraphHaplotypes(n){t.subgraphHaplotypes=n,t.dense=void 0},setDense(n){t.dense=n},setHaplotypeNames(n){t.haplotypeNames=n},setMaxRegionBp(n){t.maxRegionBp=n},cut(){let n=t.cutRegion;if(!n)return;let r=$t(Ht(t.parentTrack.configuration),n.assemblyName);if(r){t.clearGraph(),t.setError(new Error(r));return}let o=t.cutTier==="coarse";return t.cutSubgraph(t.adapterConfig,n,{hops:o?0:t.subgraphContext,haplotypes:t.chosenHaplotypes,tier:o?"coarse":void 0,...O(t.chosenLayoutMode).wholeWalks?{snarls:"overlapping"}:{}})}})).actions(t=>({recutAt(n){let r=t.tierAt(n.bpPerPx);return t.coarseCut=r==="coarse",t.cutRegion=Un(n,t.capFor(r),O(t.chosenLayoutMode).cutMargins),t.recuts++,t.cut()}})).actions(t=>({settleOn(n){t.settledWindow=n;let r=O(t.chosenLayoutMode).cutMargins;return t.regionTooLarge||vs(t.dense,n)||!t.loadCanceled&&t.tierAt(n.bpPerPx)===t.cutTier&&bi(t.cutRegion,n,r)?!1:(Promise.resolve(t.recutAt(n)).then(()=>{(0,F.isAlive)(t)&&Ms(t.error)&&this.refuseDenseCut(n)}),!0)},refuseDenseCut(n){t.setDense(n),t.cutRegion=void 0,this.settleOn(t.settledWindow??n)},switchLayout(n){let r=O(t.chosenLayoutMode);t.setLayoutMode(n);let o=O(n),a=t.host?Yt(t.host):void 0;return a&&!t.regionTooLarge&&(o.cutMargins!==r.cutMargins||o.wholeWalks!==r.wholeWalks)?t.recutAt(a):t.recomputeLayout()},retryLoad(){t.cut()},reload(){t.cut()},cancelFetchByUser(){t.stopLoad()}})).actions(t=>({async fetchHaplotypeNames(n){try{let r=await(0,Be.getSession)(t).rpcManager.call((0,Be.getRpcSessionId)(t),"GetGraphHaplotypes",{adapterConfig:n});(0,F.isAlive)(t)&&t.setHaplotypeNames(r)}catch(r){console.warn("[LinearGraphDisplay] no haplotype names",r)}}})).actions(t=>({forceLoad(){let n=t.settledWindow;n&&(t.setMaxRegionBp(Math.ceil(n.end-n.start)),t.settleOn(n))},afterAttach(){t.cutRegion&&!t.graph&&t.cut(),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>Ra(t.adapterConfig)?t.adapterConfig:void 0,n=>{t.setHaplotypeNames(void 0),n&&t.fetchHaplotypeNames(n)},{fireImmediately:!0,name:"GraphHaplotypeNames"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>t.hostPlacesX,n=>{n||t.releaseHost()},{name:"GraphHostPlacesX"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>t.hostFrame,n=>{n&&t.hostTransform(n.scale,n.translateX)},{equals:(n,r)=>n?.scale===r?.scale&&n?.translateX===r?.translateX,fireImmediately:!0,name:"GraphHostFrame"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>`${t.facet.field} ${t.facetPlacement?.count}`,()=>{let n=t.facetGridIn(t.paneCeiling)?.total??0;(t.facetGrid?.total??0)>t.height&&t.setHeight(Math.max(t.height,Math.ceil(n)))},{name:"GraphFacetHeight"})),(0,F.addDisposer)(t,(0,Ie.reaction)(()=>t.host?.coarseDynamicBlocks,n=>{let{host:r}=t,o=n&&r?Yt(r):void 0;o&&t.settleOn(o)},{fireImmediately:!0,name:"GraphHostSettle"}))}})).views(t=>({get graphViewSpec(){let n=t.host?Yt(t.host):void 0,r=t.sourceTrackId;if(!n||!r||!t.hasGraph||t.coarseCut||t.regionTooLarge)return;let o=Math.floor(n.start),a=Math.ceil(n.end);return{loadedTrackId:r,loadedRegion:{refName:n.refName,assemblyName:n.assemblyName,start:o,end:a},subgraphContext:t.subgraphContext,subgraphHaplotypes:t.chosenHaplotypes,maxRegionBp:Math.max(t.maxRegionBp,a-o),layoutMode:t.chosenLayoutMode,colorScheme:t.chosenColorScheme,referencePath:t.referencePath,geneTrackId:t.geneTrackId,showGenes:t.showGenes,showBubbles:t.showBubbles,showDeletionEdges:t.showDeletionEdges,walkLayers:t.walkLayers,facet:(0,F.getSnapshot)(t.facet)}}})).actions(t=>({openGraphView(){let n=t.graphViewSpec;n&&(0,Be.getSession)(t).addView("GraphGenomeView",n)}})).views(t=>({cutMenuItems(){if(!Sa(t.adapterConfig))return[];let n=Ze(t.adapterConfig),r=Bn(t.parentTrack.configuration),o=t.haplotypeNames,a=t.subgraphHaplotypes,i=s=>{t.setSubgraphHaplotypes(s),t.cut()};return[{type:"subHeader",label:"Load"},{type:"radio",label:o?`Every haplotype in the graph (${o.length.toLocaleString()})`:"Every haplotype in the graph",checked:a?a.length===0:!n&&!r,onClick:()=>{i([])}},...n||r?[{type:"radio",label:n?"The track's default haplotypes":`The track's ${r?.length} assemblies`,checked:a===void 0,onClick:()=>{i(void 0)}}]:[],{type:"radio",label:"Chosen in Settings...",checked:(a?.length??0)>0,onClick:()=>{this.openSettings()}}]},openSettings(){(0,Be.getSession)(t).queueDialog(n=>[hd,{model:t,open:!0,onClose:n}])},async renderSvg(n){let{renderGraphTrackSvg:r}=await import("./chunks/renderSvg-35VDH2K7.js");return r(t,n)},trackMenuItems(){let n=t.launchMenuItems();(0,As.pushLaunchViewMenuItem)(n,{label:"Graph genome view",icon:_t,disabled:!t.graphViewSpec,disabledHelpText:"Zoom in until the track cuts a graph",onClick:()=>{t.openGraphView()}});let r=[...this.cutMenuItems(),...t.highlightMenuItems()];return[...r.length>0?[{label:"Haplotypes",icon:xa,subMenu:r}]:[],...t.graphMenuItems(),{label:"Settings",icon:La,onClick:()=>{this.openSettings()}},...n]}}))}function fr(e){e.addDisplayType(()=>{let t=ys();return Object.assign(new Bs.default({name:"LinearGraphDisplay",displayName:"Graph",configSchema:t,stateModel:Is(t),trackType:["GraphTrack","FeatureTrack","SyntenyTrack"],viewType:"LinearGenomeView",ReactComponent:(0,Cs.lazy)(()=>import("./chunks/LinearGraphDisplay-ZJNR2KCT.js"))}),{adapterCapabilities:["getSubgraph"]})})}var Ds=m(Wt(),1);var br=m(K(),1),Es=m(ae(),1);function yr(e){let{uri:t,baseUri:n,csi:r}=e;return typeof t=="string"?{...e,bubblesLocation:{uri:t,baseUri:n},index:{indexType:r?"CSI":"TBI",location:{uri:`${t}.${r?"csi":"tbi"}`,baseUri:n}}}:e}var fd=(0,br.ConfigurationSchema)("MinigraphBubbleAdapter",{bubblesLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.bb.bed.gz",locationType:"UriLocation"}},index:(0,br.ConfigurationSchema)("MinigraphBubbleIndex",{indexType:{model:Es.types.enumeration("IndexType",["TBI","CSI"]),type:"stringEnum",defaultValue:"TBI"},location:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.bb.bed.gz.tbi",locationType:"UriLocation"}}}),assemblyNameToPanSN:{type:"frozen",defaultValue:{}}},{explicitlyTyped:!0,preProcessSnapshot:yr}),Fs=fd;function wr(e){e.addAdapterType(()=>new Ds.default({name:"MinigraphBubbleAdapter",displayName:"Minigraph bubble BED adapter",normalizeSnapshot:yr,configSchema:Fs,adapterMetadata:{category:"Graph adapters"},getAdapterClass:()=>import("./chunks/MinigraphBubbleAdapter-PP3LVTLY.js").then(t=>t.default)}))}var Os=m(Wt(),1);var an=m(K(),1),Hs=m(ae(),1);function gt(e,t,n){return{indexType:n?"CSI":"TBI",location:{uri:`${e}.${n?"csi":"tbi"}`,baseUri:t}}}function Vs(e){let{uri:t,baseUri:n,csi:r}=e;return typeof t=="string"?{...e,segmentsLocation:{uri:`${t}.segs.bed.gz`,baseUri:n},segmentsIndex:gt(`${t}.segs.bed.gz`,n,r),linksLocation:{uri:`${t}.links.bed.gz`,baseUri:n},linksIndex:gt(`${t}.links.bed.gz`,n,r)}:e}function bd(e){let{walksUri:t,baseUri:n,csi:r}=e;if(typeof t!="string")return e;let o=a=>`${t}.${a}.bed.gz`;return{...e,walksLocation:{uri:o("walks"),baseUri:n},walksIndex:gt(o("walks"),n,r),segmentsLocation:{uri:o("nodes"),baseUri:n},segmentsIndex:gt(o("nodes"),n,r),linksLocation:{uri:o("links"),baseUri:n},linksIndex:gt(o("links"),n,r)}}function kr(e){let{coarse:t,baseUri:n,csi:r}=e;return bd(Vs(typeof t=="object"&&t!==null?{...e,coarse:Vs({baseUri:n,csi:r,...t})}:e))}var ht=(e,t)=>(0,an.ConfigurationSchema)(e,{indexType:{model:Hs.types.enumeration("IndexType",["TBI","CSI"]),type:"stringEnum",defaultValue:"TBI"},location:{type:"fileLocation",defaultValue:{uri:t,locationType:"UriLocation"}}}),yd=(0,an.ConfigurationSchema)("RgfaTabixCoarseTier",{aboveBpPerPx:{type:"maybeNumber"},segmentsLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.tier.segs.bed.gz",locationType:"UriLocation"}},segmentsIndex:ht("RgfaCoarseSegmentsIndex","/path/to/graph.tier.segs.bed.gz.tbi"),linksLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.tier.links.bed.gz",locationType:"UriLocation"}},linksIndex:ht("RgfaCoarseLinksIndex","/path/to/graph.tier.links.bed.gz.tbi")}),wd=(0,an.ConfigurationSchema)("RgfaTabixAdapter",{segmentsLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.segs.bed.gz",locationType:"UriLocation"}},segmentsIndex:ht("RgfaSegmentsIndex","/path/to/graph.segs.bed.gz.tbi"),linksLocation:{type:"fileLocation",defaultValue:{uri:"/path/to/graph.links.bed.gz",locationType:"UriLocation"}},linksIndex:ht("RgfaLinksIndex","/path/to/graph.links.bed.gz.tbi"),walksLocation:{type:"fileLocation",defaultValue:{uri:"",locationType:"UriLocation"}},walksIndex:ht("RgfaWalksIndex",""),walkChunk:{type:"integer",defaultValue:65536},walkStepBudget:{type:"integer",defaultValue:4e6},walkByteBudget:{type:"integer",defaultValue:8e6},defaultHaplotypes:{type:"stringArray",defaultValue:[]},assemblyNameToPanSN:{type:"frozen",defaultValue:{}},coarse:yd},{explicitlyTyped:!0,preProcessSnapshot:kr}),$s=wd;function Rr(e){e.addAdapterType(()=>new Os.default({name:"RgfaTabixAdapter",displayName:"Indexed rGFA adapter",normalizeSnapshot:kr,configSchema:$s,adapterCapabilities:["getSubgraph"],adapterMetadata:{category:"Graph adapters"},getAdapterClass:()=>import("./chunks/RgfaTabixAdapter-KOIMYOR3.js").then(t=>t.default)}))}var kd=new Set(["RgfaTabixAdapter","GbzBaseSyntenyAdapter"]);function Rd(e){return Er(e).toLowerCase().endsWith(".gbz.db")}function Sd(e){let t=e.adapter;return t?.type==="GbzBaseSyntenyAdapter"&&!t.assemblyNames?.length&&Array.isArray(e.assemblyNames)&&e.assemblyNames.length>0?{...e,adapter:{...t,assemblyNames:e.assemblyNames}}:e}function xd(e,t,n){if((!n||n==="GbzBaseSyntenyAdapter")&&Rd(e))return{type:"GbzBaseSyntenyAdapter",gbzDbLocation:e,...t?{haplotypeIndexLocation:t}:{}};if((!n||n==="RgfaTabixAdapter")&&Dr(e))return Vr({choice:"RgfaTabixAdapter",loc:e,indexLoc:t,assembly:"",sample:""})}function Sr(e){e.addToExtensionPoint("Core-preProcessTrackConfig",Sd),e.addToExtensionPoint("Core-guessAdapterForLocation",t=>(n,r,o)=>xd(n,r,o)??t(n,r,o)),e.addToExtensionPoint("Core-guessTrackTypeForLocation",t=>(n,r)=>kd.has(n)?"GraphTrack":t(n,r))}var zs=m(ne(),1),sn=m(ic(),1),xr=m(ac(),1),Xs=m(sc(),1);function _s(e){let t;if(q(e)){let{refName:n,start:r,end:o,assemblyName:a}=e;typeof n=="string"&&typeof r=="number"&&typeof o=="number"&&(t={refName:n,start:r,end:o,assemblyName:typeof a=="string"?a:void 0})}return t}function Ld(e,t,n){let r=e.connectedViewId;return r===void 0||r===t||!n.has(r)}function Ws(e,t){return e.assemblyName===void 0||t===void 0||t.includes(e.assemblyName)}function Md(e){return(Array.isArray(e.tracks)?e.tracks:[]).flatMap(n=>q(n)&&Array.isArray(n.displays)?n.displays.filter(r=>q(r)&&r.type==="LinearGraphDisplay"):[])}function js(e,t,n){let r=[],o=ut(e),a=new Set(o.map(i=>q(i)?i.id:void 0));for(let i of o){if(q(i)&&i.id===t)for(let s of Md(i)){let c=_s(s.hoverHighlight);c&&Ws(c,n)&&r.push({key:typeof s.id=="string"?s.id:"graph-track",region:c})}if(q(i)&&i.type==="GraphGenomeView"&&Ld(i,t,a)){let s=_s(i.hoverHighlight);s&&Ws(s,n)&&r.push({key:typeof i.id=="string"?i.id:"graph",region:s})}}return r}var Ee=m(ue(),1),vd=(0,Xs.makeStyles)()(e=>({highlight:{height:"100%",position:"absolute",background:(0,sn.alpha)(e.palette.primary.main,.08),borderLeft:`1px solid ${(0,sn.alpha)(e.palette.primary.main,.4)}`,borderRight:`1px solid ${(0,sn.alpha)(e.palette.primary.main,.4)}`,pointerEvents:"none",zIndex:10}})),Td=(0,xr.observer)(function({model:t,region:n}){let{classes:r}=vd(),o=t.getHighlightCoords(n);return o?(0,Ee.jsx)("div",{"data-testid":"graph-node-highlight",className:r.highlight,style:{left:o.left,width:o.width}}):null}),Gd=(0,xr.observer)(function({model:t}){let{views:n}=(0,zs.getSession)(t);return(0,Ee.jsx)(Ee.Fragment,{children:js([...n],t.id,t.assemblyNames).map(({key:r,region:o})=>(0,Ee.jsx)(Td,{model:t,region:o},`graph-hover-${r}`))})}),Ys=Gd;var Us=m(ue(),1),Nd="LinearGenomeView-TracksContainerComponent";function Lr(e){e.contributeToExtensionPoint(Nd,({model:t})=>(0,Us.jsx)(Ys,{model:t},"graphgenomeview-hover-highlight"))}var Ks=m(me(),1);function Ad(e){return e.views(t=>({get adapterConfig(){return le(t,t.parentTrack.configuration)}}))}function Mr(e){e.addToExtensionPoint("Core-extendPluggableElement",t=>(t instanceof Ks.DisplayType&&mr.includes(t.name)&&t.extendStateModel(Ad),t))}var qs="GraphGenomeView";var Js="6.9.2";var vr=class extends Zs.default{constructor(){super(...arguments);this.name=qs;this.version=Js}install(n){ur(n),fr(n),lr(n),gr(n),Lr(n),Rr(n),wr(n),Dn(n),Vn(n),Sr(n),Mr(n),n.addRpcMethod(()=>new nt(n)),n.addRpcMethod(()=>new tt(n)),n.addRpcMethod(()=>new et(n)),n.addRpcMethod(()=>new Qe(n))}configure(n){try{(0,Qs.isAbstractMenuManager)(n.rootModel)&&n.rootModel.appendToSubMenu(["Add"],{label:"Graph genome view",icon:_t,onClick:r=>{r.addView("GraphGenomeView",{})}})}catch(r){console.warn("[GraphGenomeView] could not add the Add menu entry",r)}}};export{vr as default};
|
|
8
8
|
//# sourceMappingURL=jbrowse-plugin-graphgenomeviewer.esm.js.map
|