chromosomix 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{by as Gl,bz as Gn,bA as Oa,bB as Vl,bC as Hl,bD as kl,bE as Wl}from"./index-CPxipgOR.js";/**
1
+ import{bz as Gl,bA as Gn,bB as Oa,bC as Vl,bD as Hl,bE as kl,bF as Wl}from"./index-Cys9FWNc.js";/**
2
2
  * @license
3
3
  * Copyright 2010-2026 Three.js Authors
4
4
  * SPDX-License-Identifier: MIT
@@ -1 +1 @@
1
- import{E as Se,F as qe,L as Te,G as xe,H as Ae}from"./index-CPxipgOR.js";const m="4DNESC23ZYOF",A="4dn",r="chr15",oe="4DNFIKI77KEM",re="4DNFI3OPG4RB",ae="4DNFI4GZZC7Z",v={start:3e7,end:6e7},S={start:381e5,end:50025e3},$e=15e6,$=5e3,q=4,d={rows:45662501,cols:48312501},E=47215001,Ee=25e3,Oe="1",De="analysis:compartment-e1",Ne="analysis:insulation-w",O="analysis:insulation:insulation-domains";function f(e){return e instanceof HTMLElement&&e.getClientRects().length>0}function i(e,n=document){for(const c of n.querySelectorAll(e))if(f(c))return c;return null}function l(e){return(e?.textContent??"").replace(/\s+/g," ").trim()}function p(){return i(".analysis-drawer:not(.collapsed)")}function se(e){for(const n of document.querySelectorAll(".analysis-row"))if(f(n)&&l(n.querySelector(".analysis-row-title"))===e)return n;return null}function y(e){const n=e.charAt(0).toUpperCase()+e.slice(1);return i(`.panel-${e} .panel-tab`)??i(`.head-panels button[aria-label="${n} panel"]`)}function ie(e){return i(`.panel-${e}:not(.collapsed) .panel-column-body`)??y(e)}function Ie(e){for(const n of document.querySelectorAll(".panel-analysis section.analysis-card"))if(f(n)&&l(n.querySelector(".card-head")).startsWith(e))return n;return null}function le(){return i('select.res-pick, [role="radiogroup"][aria-label="resolution"]')}function ge(){for(const e of document.querySelectorAll(".controls-card"))if(f(e)&&l(e.querySelector(".controls-title"))==="Map")return e;return null}function ce(e){for(const n of ge()?.querySelectorAll("label.field")??[])if(l(n.querySelector(".field-label"))===e)return n.querySelector("select, input");return null}function Ce(){for(const e of ge()?.querySelectorAll("button")??[])if(l(e)==="O/E")return e;return null}function _(e){for(const n of p()?.querySelectorAll(".param-field")??[]){if(l(n.querySelector(".field-label"))!==e)continue;const c=n.querySelector('input[type="number"]')??n.querySelector('input:not([type="range"])');return c instanceof HTMLInputElement?c:null}return null}function Me(e,n){e!==null&&(e.value=n,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})))}function H(){for(const e of document.querySelectorAll("section.annotation-card"))if(f(e)&&l(e.querySelector(".card-head, .card-title, h3")).startsWith("Manual annotations"))return e;return null}function D(e){for(const n of H()?.querySelectorAll(".manual-form")??[])if(l(n.querySelector(".manual-form-title"))===e)return n;return null}function ue(e){for(const n of e?.querySelectorAll("button")??[])if(l(n)==="add")return n;return null}function N(){for(const e of document.querySelectorAll(".controls-card"))if(f(e)&&l(e.querySelector(".controls-title"))==="Export")return e.querySelector(".export-row");return null}function Re(e){for(const n of p()?.querySelectorAll("label.param-field")??[]){if(l(n.querySelector(".field-label"))!==e)continue;const c=n.querySelector("select");return c instanceof HTMLSelectElement?c:null}return null}function Le(){const e=Re("phase by gene density");e===null||e.value===""||(e.value="",e.dispatchEvent(new Event("change",{bubbles:!0})))}function de(e){for(const n of p()?.querySelectorAll(".analysis-figure")??[])if(l(n.querySelector(".analysis-figure-head")).startsWith(e))return n;return null}function he(){for(const e of document.querySelectorAll(".store-drawer .portal-group"))if(f(e)&&l(e.querySelector(".portal-group-key"))===m)return e;return null}function I(){const e=i(".store-drawer .portal-search");return e instanceof HTMLInputElement?e:null}function pe(){const e=p()?.querySelector(".param-sequences");return e==null?null:[...e.querySelectorAll("label.param-check")].filter(n=>n.querySelector("input")?.checked===!0).map(n=>l(n.querySelector("span")))}function Pe(e){for(const n of p()?.querySelectorAll(".param-sequences label.param-check")??[])if(l(n.querySelector("span"))===e)return n;return null}function Fe(e){if(e===void 0)return null;for(const n of p()?.querySelectorAll("label.param-check")??[])if(l(n.querySelector("span"))===e.label)return n;return null}function me(){return p()?.querySelector(".analysis-run > button")??null}function C(e,n){return e!==null&&e.length===n.length&&e.every((c,M)=>c===n[M])}function z(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):null}function Be(e){return e===null||e.view!=="region"||e.region===void 0?null:e.region.split(":")[0]}function Ue(e){if(e===null||e.view!=="region"||e.region===void 0)return null;const n=/^([^:]+):([\d,]+)-([\d,]+)$/.exec(e.region);return n===null?null:{contig:n[1],start:Number(n[2].replace(/,/g,"")),end:Number(n[3].replace(/,/g,""))}}function fe(e){return i(`.content .tviewport .tr .td[title="${e}"]`)}function be(e){const n=i(".content input.input-region");n instanceof HTMLInputElement&&(n.value=e,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",bubbles:!0})))}function s(e){return e.toLocaleString("en-US")}function _e(e){const n=()=>e.view()?.uri.includes(oe)===!0||e.file()?.includes(oe)===!0,c=()=>Be(e.view())===r,M=t=>e.runs(t).some(o=>C(z(o.provenance.params.sequences),[r])),Z=t=>e.tracks()?.entries.find(o=>o.source.kind==="remote"&&o.source.url.includes(t)),ke=()=>e.tracks()?.byId(De),G=()=>e.tracks()?.entries.filter(t=>t.id.startsWith(Ne))??[],R=()=>{const t=G()[0];return t===void 0?null:i(`.ann-row[data-id="${t.id}"]`)},K=()=>R()?.querySelector(".ann-more")?.getAttribute("aria-expanded")==="true",Y=t=>e.saved().some(o=>o.toLowerCase().endsWith(t)),w=(t,o)=>t.contig===r&&Math.abs(t.bp-o)<=Ee,ye=()=>(e.marks()??[]).some(t=>t.kind==="arrowhead"&&(w(t.a,d.rows)&&w(t.b,d.cols)||w(t.a,d.cols)&&w(t.b,d.rows))),we=()=>(e.marks()??[]).some(t=>t.kind==="line"&&t.axis!=="horizontal"&&w(t.at,E)),T=()=>i(`.ann-row[data-id="${O}"]`),x=()=>T()?.querySelector(".ann-more")?.getAttribute("aria-expanded")==="true",L=()=>{const t=e.tracks()?.byId(O);return t!==void 0&&qe(t)==="lane"},V=()=>{const t=e.tracks()?.laneFor(O,Te)?.placement;return t===void 0?null:{bottom:t.bottom,left:t.left}},j=t=>{for(const o of T()?.querySelectorAll(".ann-place")??[])if(f(o)&&new RegExp(`\\b${t} edge\\b`).test(o.title))return o;return null},b=()=>i(".content .panel-grid"),P=t=>()=>t()??y("aesthetics"),Q=t=>()=>{const o=i(".content .heatmap-canvas");if(o===null)return null;const a=e.square({contig:r,...t});return a===null?o:{within:o,box:{left:a.left,top:a.top,right:a.right,bottom:a.bottom}}},X=Se()?"⇧ Shift and ⌥ Option":"Shift and Alt";let F=!1;const ve=()=>{if(F||fe(r)!==null)return;const t=i(".content .tviewport"),o=e.sequences()?.indexOf(r)??-1;if(t===null||o<0)return;F=!0;const a=t.querySelector(".tr")?.offsetHeight??28;t.scrollTop=Math.max(0,o*a-t.clientHeight/2),t.dispatchEvent(new Event("scroll"))},J=(t,o)=>({id:t,chapter:o,title:"Open the Analysis panel",text:"Analyses run here, in this page, on the map on screen.",target:()=>y("analysis"),done:()=>e.panelOpen("analysis"),needs:{holds:n,back:"open-set"}}),ee=(t,o,a,u,h)=>({id:t,chapter:o,title:u,text:h,action:"choose",target:P(()=>ce("score")),done:()=>e.score()===a,needs:{holds:n,back:"open-set"}}),te=(t,o,a,u,h={})=>{const W=`analysis-${o}`,g=()=>e.task()===o;return[J(W,t),...h.tour?.(W)??[],{id:o,chapter:t,title:`Choose ${a}`,text:u.choose,target:()=>se(a),done:g,needs:{holds:()=>e.panelOpen("analysis"),back:W},missing:"Not in the list — empty the box over it if a word is typed there."},{id:`${o}-none`,chapter:t,title:"Untick every sequence",text:u.none,prepare:h.setup,target:()=>p()?.querySelector('button[title="Untick every sequence"]')??null,done:()=>{const k=pe();return k!==null&&(k.length===0||C(k,[r]))},needs:{holds:g,back:o}},{id:`${o}-sequence`,chapter:t,title:`Tick ${r}`,text:u.tick,target:()=>Pe(r),done:()=>C(pe(),[r]),needs:{holds:g,back:o}},...h.form?.(g)??[],{id:`${o}-run`,chapter:t,title:"Run it",text:u.run,prepare:h.setup,target:me,done:()=>h.ran===void 0?M(o):e.runs(o).some(k=>C(z(k.provenance.params.sequences),[r])&&h.ran(k.provenance.params)),needs:{holds:()=>g()||e.running(o),back:o}},...h.after?.(g)??[],{id:`${o}-close`,chapter:t,title:"Back to the map",text:"The result is a track as well as a figure. Close the drawer to see it beside the map.",target:()=>p()?.querySelector(".analysis-drawer-head .btn-close")??null,done:()=>e.task()===null}]},ne=()=>{const t=G();return[Z(ae),Z(re),ke(),...t.length===0?[void 0]:t]},B=()=>ne().map(t=>Fe(t)),U=(t,o,a,u)=>({id:t,chapter:"Compartments",title:o,text:a,target:()=>Ie(o),needs:{holds:()=>e.panelOpen("analysis"),back:u}});return[{id:"welcome",chapter:"Welcome",title:"A first session, on real data",text:`Open a Hi-C map from the 4D Nucleome project, find its compartments, domains and a loop on ${r}, save what you made, and set it against 4DN’s own — in the real app, one step at a time.`,hero:!0,agenda:!0,next:"let’s go"},{id:"stores",chapter:"The 4DN store",title:"Open the data stores",text:"Stores are catalogues of published data, read from where they are kept. Press this button to open the drawer that holds them.",target:()=>i('.head-files button[aria-label="stores"]'),done:()=>e.store()!==null},{id:"store",chapter:"The 4DN store",title:"Switch to 4DN",text:"It opens on the lab’s own store, RSG. Press 4DN to switch to the 4D Nucleome project’s.",target:()=>i(`.store-drawer .store-tile[data-store="${A}"]`),done:()=>e.store()===A,needs:{holds:()=>e.store()!==null,back:"stores"}},{id:"search",chapter:"The 4DN store",title:"Find an experiment",text:["Type ",{name:m,copy:!0}," in the search box: Hi-C on K562 cells, about 190 million contacts."],action:"type",target:I,focus:!0,done:()=>I()?.value.toUpperCase().includes(m)===!0&&he()!==null,mistake:()=>{const t=(I()?.value??"").trim().toUpperCase();return t===""||m.startsWith(t)||t.includes(m)?null:t},needs:{holds:()=>e.store()===A,back:"store"},assist:{label:"type it for me",title:`Put ${m} in the search box`,run:()=>{const t=I();t!==null&&(t.value=m,t.dispatchEvent(new Event("input",{bubbles:!0})))}}},{id:"open-set",chapter:"The 4DN store",title:"Open it with its tracks",text:"One press opens the contact map with the tracks 4DN computed from it — compartments, insulation and boundaries — without downloading its 1.9 GB.",target:()=>he()?.querySelector(".portal-session")??null,done:n,needs:{holds:()=>e.store()===A||n(),back:"store"},missing:`Not on screen — type ${m} in the store’s search box again.`},{id:"look-general",chapter:"The map",title:"The General panel",text:"What the file is: its bin size and contacts under File, its sequences under Sequences, and anything else it carries under Metadata.",target:()=>ie("general")},{id:"resolution-250",chapter:"The map",title:"Pick 250 kb",text:"A map is stored at several resolutions, the size of one bin. 250 kb is coarse enough to show a whole chromosome’s compartments.",action:"choose",target:le,done:()=>e.binsize()===25e4,needs:{holds:n,back:"open-set"},missing:"Waiting for the map to open."},{id:"chromosome",chapter:"The map",title:`Open ${r}`,text:`Press ${r} in the table to open its map.`,prepare:()=>{F=!1},target:()=>(ve(),fe(r)),done:c,needs:{holds:n,back:"open-set"},missing:`Not on screen — scroll the table to ${r}.`},{id:"look-map",chapter:"The map",title:"The contact map",text:`Each pixel is how often two stretches of ${r} touch; 4DN’s tracks are drawn under it. Scroll to zoom into the picture at this resolution, drag to move around, and double-click to fit it back.`,target:b},{id:"look-aesthetics",chapter:"The map",title:"The Aesthetics panel",text:"How the picture is drawn: the Map card sets its score, smoothing and colours, the Tracks card its tracks, and Export saves it as a figure.",target:()=>ie("aesthetics")},ee("score-correlation","Compartments",xe,"Draw it as a correlation","In the Map card, set score to correlation."),{id:"look-correlation",chapter:"Compartments",title:"The plaid",text:"Red where two stretches share a compartment, blue where they do not. Compartments sums this pattern up as one track, E1, positive in one compartment and negative in the other.",target:b},...te("Compartments","compartments","Compartments",{choose:"It splits a chromosome into A and B compartments from the map’s plaid.",none:"It runs on every sequence of the file to begin with. Press none…",tick:`…then tick ${r}, the chromosome on screen.`,run:"Press run. It takes a few seconds."},{tour:t=>[U("tasks-2d","2D tasks","These read the contact map: its decay with distance, insulation, compartments, loops and more.",t),U("tasks-3d","3D tasks","These build a model of the chromosome’s shape from the map, or set one against it.",t),U("tasks-1d","1D tasks","These read tracks rather than the map: peaks, profiles over features, correlations between tracks.",t)],setup:Le,after:t=>[{id:"look-saddle",chapter:"Compartments",title:"The saddle",text:"Bins sorted by E1, low to high: bright corners on the diagonal mean like touches like, A with A and B with B. The numbers under it say how much.",target:()=>de("Saddle"),needs:{holds:t,back:"compartments"}}]}),{id:"look-compartments",chapter:"Compartments",title:"Your compartments",text:"E1 and its A and B calls are drawn left of the map. Compare them with 4DN’s compartment track under it.",target:b},ee("score-balanced","Zooming in",Ae,"Back to contacts","Domains are about how often stretches touch, not how alike they are: set score back to balanced."),{id:"zoom",chapter:"Zooming in",title:"Zoom along the diagonal",text:`Hold ${X}, then drag across the lit square, from one corner to the other: that stretch opens.`,action:"drag",target:Q(v),done:()=>{const t=e.view();return c()&&t?.region?.includes(":")===!0&&t.region2===void 0},needs:{holds:c,back:"chromosome"},assist:{label:"zoom for me",title:`Open ${r}:${s(v.start)}-${s(v.end)}`,run:()=>be(`${r}:${s(v.start)}-${s(v.end)}`)}},{id:"resolution-5",chapter:"Zooming in",title:"Switch to 5 kb",text:"At 5 kb the domains along the diagonal come into view, and the loops at their corners.",action:"choose",target:le,done:()=>e.binsize()===$,needs:{holds:n,back:"open-set"}},{id:"zoom-domains",chapter:"Zooming in",title:"Closer, on a few domains",text:`Once more: hold ${X} and drag across the lit square.`,action:"drag",target:Q(S),done:()=>{const t=Ue(e.view());return t!==null&&t.contig===r&&t.end-t.start<=$e&&e.binsize()===$},needs:{holds:()=>c()&&e.binsize()===$,back:"resolution-5"},missing:"Not in view — press zoom for me, or go back a step.",assist:{label:"zoom for me",title:`Open ${r}:${s(S.start)}-${s(S.end)}`,run:()=>be(`${r}:${s(S.start)}-${s(S.end)}`)}},{id:"look-domains",chapter:"Zooming in",title:"Domains",text:"Each dark square along the diagonal is a domain, or TAD: a stretch that touches itself more than its neighbours. Most sit inside bigger ones — the big square from 45.7 to 48.3 Mb holds two.",target:b},{id:"oe-on",chapter:"Zooming in",title:"Turn on O/E",text:"O/E divides each pixel by what its distance predicts, so what is left is structure rather than distance.",target:P(Ce),done:()=>e.view()?.oe===!0,needs:{holds:n,back:"open-set"}},{id:"smooth",chapter:"Zooming in",title:"Smooth it",text:"At 5 kb most pixels hold a handful of contacts. Set smooth to 3 × 3, which averages each pixel with the eight around it.",action:"choose",target:P(()=>ce("smooth")),done:()=>e.view()?.smooth===Oe,needs:{holds:n,back:"open-set"}},{id:"look-oe",chapter:"Zooming in",title:"Domains and compartments",text:"Red is more contact than the distance predicts, blue less: the domains are red squares, and the checkerboard behind them is A and B again.",target:b},...te("Insulation","insulation","Diamond insulation",{choose:"It scores how much contact crosses each bin; its dips are the boundaries between domains.",none:"Again, press none…",tick:`…then tick ${r}.`,run:"Press run. Four windows over a whole chromosome at 5 kb take a little while."},{form:t=>[{id:"insulation-scales",chapter:"Insulation",title:"Four scales",text:`Set scales to ${q}. The window is 10 bins, 50 kb here, and each scale doubles it: 50, 100, 200 and 400 kb, one insulation track each.`,action:"type",target:()=>_("scales"),focus:!0,done:()=>Number(_("scales")?.value)===q,needs:{holds:t,back:"insulation"},assist:{label:"set it for me",title:`Set scales to ${q}`,run:()=>Me(_("scales"),String(q))}}],ran:t=>t.scales===q&&e.binsize()===$}),{id:"look-insulation",chapter:"Insulation",title:"Your insulation, at four scales",text:"Four scores are drawn left of the map, one per window, with the boundaries and the domains between them. The scales are the TAD hierarchy: the 50 kb window dips at the edge of every small domain, the 400 kb one only at the borders of the big ones. A border every window finds is high in the hierarchy; one only the narrow windows see is a subTAD’s, nested inside a bigger domain.",target:b},{id:"annotations",chapter:"Marks",title:"Open the Annotations panel",text:"Every track has a row here, the ones you computed among them, and so do the marks you draw.",target:()=>y("annotations"),done:()=>e.panelOpen("annotations"),needs:{holds:n,back:"open-set"}},{id:"mark-loop",chapter:"Marks",title:"Mark the loop",text:["The big domain has a dot at its corner: a loop, its two borders held together. In Manual annotations, under Arrowheads, type ",{name:`${r}:${s(d.rows)}`,copy:!0}," in rows and ",{name:`${r}:${s(d.cols)}`,copy:!0}," in columns, then press add."],target:()=>D("Arrowheads")??H(),done:ye,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"Not on screen — scroll the Annotations panel to Manual annotations.",assist:{label:"mark it for me",title:`An arrowhead at ${r}:${s(d.rows)} × ${r}:${s(d.cols)}`,run:()=>{const t=D("Arrowheads"),[o,a]=[...t?.querySelectorAll("input")??[]];o===void 0||a===void 0||(o.value=`${r}:${s(d.rows)}`,a.value=`${r}:${s(d.cols)}`,ue(t)?.click())}}},{id:"mark-border",chapter:"Marks",title:"Mark the weak border",text:["Inside that domain one border is weak: the 400 kb window barely dips there, 4DN calls it Weak, and it splits the domain into two subTADs. Under Lines, keep vertical, type ",{name:`${r}:${s(E)}`,copy:!0}," and press add."],target:()=>D("Lines")??H(),done:we,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"Not on screen — scroll the Annotations panel to Manual annotations.",assist:{label:"mark it for me",title:`A vertical line at ${r}:${s(E)}`,run:()=>{const t=D("Lines"),o=t?.querySelector("select"),a=t?.querySelector("input");o==null||a===null||a===void 0||(o.value="vertical",a.value=`${r}:${s(E)}`,ue(t)?.click())}}},{id:"look-marks",chapter:"Marks",title:"A loop and a subTAD border",text:"The arrowhead points at the loop closing the big domain, and the line marks the border inside it. Find the same place on your four insulation tracks, left of the map: a deep dip at 50 kb, barely one at 400 kb — that is the hierarchy, read off one bin.",target:b},{id:"insulation-row",chapter:"Tracks",title:"Unfold your insulation’s settings",text:"A computed track is a track like any other: press the arrow on your first insulation row.",target:()=>R()?.querySelector(".ann-more")??null,done:K,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"No insulation row — run Diamond insulation again."},{id:"insulation-bigwig",chapter:"Tracks",title:"Save it as a bigWig",text:"Press bigWig to save the score as a file IGV, deepTools and pyBigWig open — written here, in this page, with nothing uploaded.",target:()=>{for(const t of R()?.querySelectorAll(".ann-exports button")??[])if(l(t)==="bigWig")return t;return null},done:()=>Y(".bw"),needs:{holds:()=>e.panelOpen("annotations")&&K(),back:"insulation-row"}},{id:"domains",chapter:"Tracks",title:"Unfold the domains’ settings",text:"Press the arrow on the Insulation domains row.",target:()=>T()?.querySelector(".ann-more")??null,done:x,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"No Insulation domains row — run Diamond insulation with its domains on."},{id:"domains-display",chapter:"Tracks",title:"Draw the domains as a 1D track",text:"Domains are outlined on the map. Choose 1D track to draw them as a lane beside it instead.",action:"choose",target:()=>T()?.querySelector(`select[data-display="${O}"]`)??null,done:L,needs:{holds:x,back:"domains"}},{id:"domains-bottom",chapter:"Tracks",title:"Put it under the map",text:"Press the bottom edge to draw the lane under the map…",target:()=>j("bottom"),done:()=>V()?.bottom===!0,needs:{holds:()=>x()&&L(),back:"domains-display"}},{id:"domains-left",chapter:"Tracks",title:"Take it off the side",text:"…and the left edge to take it off the left.",target:()=>j("left"),done:()=>{const t=V();return t!==null&&t.bottom&&!t.left},needs:{holds:()=>x()&&L(),back:"domains-display"}},{id:"export-format",chapter:"The figure",title:"Choose PDF",text:"The Export card at the top of the Aesthetics panel saves what is on screen — the map, your marks and every track — as a figure. Choose PDF (vector): lines and text stay sharp at any size.",action:"choose",target:()=>N()?.querySelector("select.select-format")??y("aesthetics"),done:()=>N()?.querySelector("select.select-format")?.value==="pdf",needs:{holds:n,back:"open-set"}},{id:"export-save",chapter:"The figure",title:"Save the figure",text:"Press the download button beside it.",target:()=>N()?.querySelector(".export-acts button")??y("aesthetics"),done:()=>Y(".pdf"),needs:{holds:()=>N()?.querySelector("select.select-format")?.value==="pdf",back:"export-format"}},J("analysis-trackcorr","Track correlation"),{id:"trackcorr",chapter:"Track correlation",title:"Choose Track correlation",text:"It measures how closely every pair of loaded tracks agrees.",target:()=>se("Track correlation"),done:()=>e.task()==="trackcorr",needs:{holds:()=>e.panelOpen("analysis"),back:"analysis-trackcorr"},missing:"Not in the list — empty the box over it if a word is typed there."},{id:"tick-tracks",chapter:"Track correlation",title:"Tick every track",text:[{name:ae}," and ",{name:re},", 4DN’s insulation and E1, your E1, and your insulation at all four scales."],target:()=>B().map(t=>t?.closest(".param-field")??null).find(t=>t!==null)??null,done:()=>B().every(t=>t?.querySelector("input")?.checked===!0),needs:{holds:()=>e.task()==="trackcorr",back:"trackcorr"},missing:"Not in the list — a track did not load, or was closed.",assist:{label:"tick them for me",title:"Tick every track in the list",run:()=>{for(const t of B()){const o=t?.querySelector("input");o!=null&&!o.checked&&o.click()}}}},{id:"trackcorr-run",chapter:"Track correlation",title:"Run it",text:`Every pair is compared over the windows all of them have values in, which is ${r}.`,target:me,done:()=>{const t=ne();return t.some(o=>o===void 0)?!1:e.runs("trackcorr").some(o=>{const a=new Set(z(o.provenance.params.tracks)??[]);return t.every(u=>u!==void 0&&a.has(u.id))})},needs:{holds:()=>e.task()==="trackcorr"||e.running("trackcorr"),back:"trackcorr"}},{id:"look-trackcorr",chapter:"Track correlation",title:"Yours against 4DN’s",text:"Each square compares two tracks: red where they rise and fall together, blue where one rises as the other falls. Find yours against 4DN’s — an unphased E1 can match upside down, at −1 — and your four scales against each other: neighbouring windows agree most, the hierarchy again.",target:()=>de("Track correlation")},{id:"console",chapter:"The console",title:"Every step is a command",text:"Open the console: each file you opened and each run you made is a line you can paste into a terminal to do it again.",target:()=>i('.head-actions button[aria-label="console"]')??i('button[aria-label="console"]'),done:()=>e.consoleOpen()},{id:"finish",chapter:"Done",title:"That’s the tour",text:`You opened a map from 4DN, called compartments and domains at four scales on ${r}, marked a loop and a subTAD border, saved a track and a figure, and set it all against 4DN’s own. The tutorial is on the landing page and in About whenever you want it again.`,hero:!0}]}export{r as TUTORIAL_SEQUENCE,m as TUTORIAL_SET,A as TUTORIAL_STORE,_e as tutorialSteps};
1
+ import{E as Se,F as qe,L as Te,G as xe,H as Ae}from"./index-Cys9FWNc.js";const m="4DNESC23ZYOF",A="4dn",r="chr15",oe="4DNFIKI77KEM",re="4DNFI3OPG4RB",ae="4DNFI4GZZC7Z",v={start:3e7,end:6e7},S={start:381e5,end:50025e3},$e=15e6,$=5e3,q=4,d={rows:45662501,cols:48312501},E=47215001,Ee=25e3,Oe="1",De="analysis:compartment-e1",Ne="analysis:insulation-w",O="analysis:insulation:insulation-domains";function f(e){return e instanceof HTMLElement&&e.getClientRects().length>0}function i(e,n=document){for(const c of n.querySelectorAll(e))if(f(c))return c;return null}function l(e){return(e?.textContent??"").replace(/\s+/g," ").trim()}function p(){return i(".analysis-drawer:not(.collapsed)")}function se(e){for(const n of document.querySelectorAll(".analysis-row"))if(f(n)&&l(n.querySelector(".analysis-row-title"))===e)return n;return null}function y(e){const n=e.charAt(0).toUpperCase()+e.slice(1);return i(`.panel-${e} .panel-tab`)??i(`.head-panels button[aria-label="${n} panel"]`)}function ie(e){return i(`.panel-${e}:not(.collapsed) .panel-column-body`)??y(e)}function Ie(e){for(const n of document.querySelectorAll(".panel-analysis section.analysis-card"))if(f(n)&&l(n.querySelector(".card-head")).startsWith(e))return n;return null}function le(){return i('select.res-pick, [role="radiogroup"][aria-label="resolution"]')}function ge(){for(const e of document.querySelectorAll(".controls-card"))if(f(e)&&l(e.querySelector(".controls-title"))==="Map")return e;return null}function ce(e){for(const n of ge()?.querySelectorAll("label.field")??[])if(l(n.querySelector(".field-label"))===e)return n.querySelector("select, input");return null}function Ce(){for(const e of ge()?.querySelectorAll("button")??[])if(l(e)==="O/E")return e;return null}function _(e){for(const n of p()?.querySelectorAll(".param-field")??[]){if(l(n.querySelector(".field-label"))!==e)continue;const c=n.querySelector('input[type="number"]')??n.querySelector('input:not([type="range"])');return c instanceof HTMLInputElement?c:null}return null}function Me(e,n){e!==null&&(e.value=n,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})))}function H(){for(const e of document.querySelectorAll("section.annotation-card"))if(f(e)&&l(e.querySelector(".card-head, .card-title, h3")).startsWith("Manual annotations"))return e;return null}function D(e){for(const n of H()?.querySelectorAll(".manual-form")??[])if(l(n.querySelector(".manual-form-title"))===e)return n;return null}function ue(e){for(const n of e?.querySelectorAll("button")??[])if(l(n)==="add")return n;return null}function N(){for(const e of document.querySelectorAll(".controls-card"))if(f(e)&&l(e.querySelector(".controls-title"))==="Export")return e.querySelector(".export-row");return null}function Re(e){for(const n of p()?.querySelectorAll("label.param-field")??[]){if(l(n.querySelector(".field-label"))!==e)continue;const c=n.querySelector("select");return c instanceof HTMLSelectElement?c:null}return null}function Le(){const e=Re("phase by gene density");e===null||e.value===""||(e.value="",e.dispatchEvent(new Event("change",{bubbles:!0})))}function de(e){for(const n of p()?.querySelectorAll(".analysis-figure")??[])if(l(n.querySelector(".analysis-figure-head")).startsWith(e))return n;return null}function he(){for(const e of document.querySelectorAll(".store-drawer .portal-group"))if(f(e)&&l(e.querySelector(".portal-group-key"))===m)return e;return null}function I(){const e=i(".store-drawer .portal-search");return e instanceof HTMLInputElement?e:null}function pe(){const e=p()?.querySelector(".param-sequences");return e==null?null:[...e.querySelectorAll("label.param-check")].filter(n=>n.querySelector("input")?.checked===!0).map(n=>l(n.querySelector("span")))}function Pe(e){for(const n of p()?.querySelectorAll(".param-sequences label.param-check")??[])if(l(n.querySelector("span"))===e)return n;return null}function Fe(e){if(e===void 0)return null;for(const n of p()?.querySelectorAll("label.param-check")??[])if(l(n.querySelector("span"))===e.label)return n;return null}function me(){return p()?.querySelector(".analysis-run > button")??null}function C(e,n){return e!==null&&e.length===n.length&&e.every((c,M)=>c===n[M])}function z(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):null}function Be(e){return e===null||e.view!=="region"||e.region===void 0?null:e.region.split(":")[0]}function Ue(e){if(e===null||e.view!=="region"||e.region===void 0)return null;const n=/^([^:]+):([\d,]+)-([\d,]+)$/.exec(e.region);return n===null?null:{contig:n[1],start:Number(n[2].replace(/,/g,"")),end:Number(n[3].replace(/,/g,""))}}function fe(e){return i(`.content .tviewport .tr .td[title="${e}"]`)}function be(e){const n=i(".content input.input-region");n instanceof HTMLInputElement&&(n.value=e,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",bubbles:!0})))}function s(e){return e.toLocaleString("en-US")}function _e(e){const n=()=>e.view()?.uri.includes(oe)===!0||e.file()?.includes(oe)===!0,c=()=>Be(e.view())===r,M=t=>e.runs(t).some(o=>C(z(o.provenance.params.sequences),[r])),Z=t=>e.tracks()?.entries.find(o=>o.source.kind==="remote"&&o.source.url.includes(t)),ke=()=>e.tracks()?.byId(De),G=()=>e.tracks()?.entries.filter(t=>t.id.startsWith(Ne))??[],R=()=>{const t=G()[0];return t===void 0?null:i(`.ann-row[data-id="${t.id}"]`)},K=()=>R()?.querySelector(".ann-more")?.getAttribute("aria-expanded")==="true",Y=t=>e.saved().some(o=>o.toLowerCase().endsWith(t)),w=(t,o)=>t.contig===r&&Math.abs(t.bp-o)<=Ee,ye=()=>(e.marks()??[]).some(t=>t.kind==="arrowhead"&&(w(t.a,d.rows)&&w(t.b,d.cols)||w(t.a,d.cols)&&w(t.b,d.rows))),we=()=>(e.marks()??[]).some(t=>t.kind==="line"&&t.axis!=="horizontal"&&w(t.at,E)),T=()=>i(`.ann-row[data-id="${O}"]`),x=()=>T()?.querySelector(".ann-more")?.getAttribute("aria-expanded")==="true",L=()=>{const t=e.tracks()?.byId(O);return t!==void 0&&qe(t)==="lane"},V=()=>{const t=e.tracks()?.laneFor(O,Te)?.placement;return t===void 0?null:{bottom:t.bottom,left:t.left}},j=t=>{for(const o of T()?.querySelectorAll(".ann-place")??[])if(f(o)&&new RegExp(`\\b${t} edge\\b`).test(o.title))return o;return null},b=()=>i(".content .panel-grid"),P=t=>()=>t()??y("aesthetics"),Q=t=>()=>{const o=i(".content .heatmap-canvas");if(o===null)return null;const a=e.square({contig:r,...t});return a===null?o:{within:o,box:{left:a.left,top:a.top,right:a.right,bottom:a.bottom}}},X=Se()?"⇧ Shift and ⌥ Option":"Shift and Alt";let F=!1;const ve=()=>{if(F||fe(r)!==null)return;const t=i(".content .tviewport"),o=e.sequences()?.indexOf(r)??-1;if(t===null||o<0)return;F=!0;const a=t.querySelector(".tr")?.offsetHeight??28;t.scrollTop=Math.max(0,o*a-t.clientHeight/2),t.dispatchEvent(new Event("scroll"))},J=(t,o)=>({id:t,chapter:o,title:"Open the Analysis panel",text:"Analyses run here, in this page, on the map on screen.",target:()=>y("analysis"),done:()=>e.panelOpen("analysis"),needs:{holds:n,back:"open-set"}}),ee=(t,o,a,u,h)=>({id:t,chapter:o,title:u,text:h,action:"choose",target:P(()=>ce("score")),done:()=>e.score()===a,needs:{holds:n,back:"open-set"}}),te=(t,o,a,u,h={})=>{const W=`analysis-${o}`,g=()=>e.task()===o;return[J(W,t),...h.tour?.(W)??[],{id:o,chapter:t,title:`Choose ${a}`,text:u.choose,target:()=>se(a),done:g,needs:{holds:()=>e.panelOpen("analysis"),back:W},missing:"Not in the list — empty the box over it if a word is typed there."},{id:`${o}-none`,chapter:t,title:"Untick every sequence",text:u.none,prepare:h.setup,target:()=>p()?.querySelector('button[title="Untick every sequence"]')??null,done:()=>{const k=pe();return k!==null&&(k.length===0||C(k,[r]))},needs:{holds:g,back:o}},{id:`${o}-sequence`,chapter:t,title:`Tick ${r}`,text:u.tick,target:()=>Pe(r),done:()=>C(pe(),[r]),needs:{holds:g,back:o}},...h.form?.(g)??[],{id:`${o}-run`,chapter:t,title:"Run it",text:u.run,prepare:h.setup,target:me,done:()=>h.ran===void 0?M(o):e.runs(o).some(k=>C(z(k.provenance.params.sequences),[r])&&h.ran(k.provenance.params)),needs:{holds:()=>g()||e.running(o),back:o}},...h.after?.(g)??[],{id:`${o}-close`,chapter:t,title:"Back to the map",text:"The result is a track as well as a figure. Close the drawer to see it beside the map.",target:()=>p()?.querySelector(".analysis-drawer-head .btn-close")??null,done:()=>e.task()===null}]},ne=()=>{const t=G();return[Z(ae),Z(re),ke(),...t.length===0?[void 0]:t]},B=()=>ne().map(t=>Fe(t)),U=(t,o,a,u)=>({id:t,chapter:"Compartments",title:o,text:a,target:()=>Ie(o),needs:{holds:()=>e.panelOpen("analysis"),back:u}});return[{id:"welcome",chapter:"Welcome",title:"A first session, on real data",text:`Open a Hi-C map from the 4D Nucleome project, find its compartments, domains and a loop on ${r}, save what you made, and set it against 4DN’s own — in the real app, one step at a time.`,hero:!0,agenda:!0,next:"let’s go"},{id:"stores",chapter:"The 4DN store",title:"Open the data stores",text:"Stores are catalogues of published data, read from where they are kept. Press this button to open the drawer that holds them.",target:()=>i('.head-files button[aria-label="stores"]'),done:()=>e.store()!==null},{id:"store",chapter:"The 4DN store",title:"Switch to 4DN",text:"It opens on the lab’s own store, RSG. Press 4DN to switch to the 4D Nucleome project’s.",target:()=>i(`.store-drawer .store-tile[data-store="${A}"]`),done:()=>e.store()===A,needs:{holds:()=>e.store()!==null,back:"stores"}},{id:"search",chapter:"The 4DN store",title:"Find an experiment",text:["Type ",{name:m,copy:!0}," in the search box: Hi-C on K562 cells, about 190 million contacts."],action:"type",target:I,focus:!0,done:()=>I()?.value.toUpperCase().includes(m)===!0&&he()!==null,mistake:()=>{const t=(I()?.value??"").trim().toUpperCase();return t===""||m.startsWith(t)||t.includes(m)?null:t},needs:{holds:()=>e.store()===A,back:"store"},assist:{label:"type it for me",title:`Put ${m} in the search box`,run:()=>{const t=I();t!==null&&(t.value=m,t.dispatchEvent(new Event("input",{bubbles:!0})))}}},{id:"open-set",chapter:"The 4DN store",title:"Open it with its tracks",text:"One press opens the contact map with the tracks 4DN computed from it — compartments, insulation and boundaries — without downloading its 1.9 GB.",target:()=>he()?.querySelector(".portal-session")??null,done:n,needs:{holds:()=>e.store()===A||n(),back:"store"},missing:`Not on screen — type ${m} in the store’s search box again.`},{id:"look-general",chapter:"The map",title:"The General panel",text:"What the file is: its bin size and contacts under File, its sequences under Sequences, and anything else it carries under Metadata.",target:()=>ie("general")},{id:"resolution-250",chapter:"The map",title:"Pick 250 kb",text:"A map is stored at several resolutions, the size of one bin. 250 kb is coarse enough to show a whole chromosome’s compartments.",action:"choose",target:le,done:()=>e.binsize()===25e4,needs:{holds:n,back:"open-set"},missing:"Waiting for the map to open."},{id:"chromosome",chapter:"The map",title:`Open ${r}`,text:`Press ${r} in the table to open its map.`,prepare:()=>{F=!1},target:()=>(ve(),fe(r)),done:c,needs:{holds:n,back:"open-set"},missing:`Not on screen — scroll the table to ${r}.`},{id:"look-map",chapter:"The map",title:"The contact map",text:`Each pixel is how often two stretches of ${r} touch; 4DN’s tracks are drawn under it. Scroll to zoom into the picture at this resolution, drag to move around, and double-click to fit it back.`,target:b},{id:"look-aesthetics",chapter:"The map",title:"The Aesthetics panel",text:"How the picture is drawn: the Map card sets its score, smoothing and colours, the Tracks card its tracks, and Export saves it as a figure.",target:()=>ie("aesthetics")},ee("score-correlation","Compartments",xe,"Draw it as a correlation","In the Map card, set score to correlation."),{id:"look-correlation",chapter:"Compartments",title:"The plaid",text:"Red where two stretches share a compartment, blue where they do not. Compartments sums this pattern up as one track, E1, positive in one compartment and negative in the other.",target:b},...te("Compartments","compartments","Compartments",{choose:"It splits a chromosome into A and B compartments from the map’s plaid.",none:"It runs on every sequence of the file to begin with. Press none…",tick:`…then tick ${r}, the chromosome on screen.`,run:"Press run. It takes a few seconds."},{tour:t=>[U("tasks-2d","2D tasks","These read the contact map: its decay with distance, insulation, compartments, loops and more.",t),U("tasks-3d","3D tasks","These build a model of the chromosome’s shape from the map, or set one against it.",t),U("tasks-1d","1D tasks","These read tracks rather than the map: peaks, profiles over features, correlations between tracks.",t)],setup:Le,after:t=>[{id:"look-saddle",chapter:"Compartments",title:"The saddle",text:"Bins sorted by E1, low to high: bright corners on the diagonal mean like touches like, A with A and B with B. The numbers under it say how much.",target:()=>de("Saddle"),needs:{holds:t,back:"compartments"}}]}),{id:"look-compartments",chapter:"Compartments",title:"Your compartments",text:"E1 and its A and B calls are drawn left of the map. Compare them with 4DN’s compartment track under it.",target:b},ee("score-balanced","Zooming in",Ae,"Back to contacts","Domains are about how often stretches touch, not how alike they are: set score back to balanced."),{id:"zoom",chapter:"Zooming in",title:"Zoom along the diagonal",text:`Hold ${X}, then drag across the lit square, from one corner to the other: that stretch opens.`,action:"drag",target:Q(v),done:()=>{const t=e.view();return c()&&t?.region?.includes(":")===!0&&t.region2===void 0},needs:{holds:c,back:"chromosome"},assist:{label:"zoom for me",title:`Open ${r}:${s(v.start)}-${s(v.end)}`,run:()=>be(`${r}:${s(v.start)}-${s(v.end)}`)}},{id:"resolution-5",chapter:"Zooming in",title:"Switch to 5 kb",text:"At 5 kb the domains along the diagonal come into view, and the loops at their corners.",action:"choose",target:le,done:()=>e.binsize()===$,needs:{holds:n,back:"open-set"}},{id:"zoom-domains",chapter:"Zooming in",title:"Closer, on a few domains",text:`Once more: hold ${X} and drag across the lit square.`,action:"drag",target:Q(S),done:()=>{const t=Ue(e.view());return t!==null&&t.contig===r&&t.end-t.start<=$e&&e.binsize()===$},needs:{holds:()=>c()&&e.binsize()===$,back:"resolution-5"},missing:"Not in view — press zoom for me, or go back a step.",assist:{label:"zoom for me",title:`Open ${r}:${s(S.start)}-${s(S.end)}`,run:()=>be(`${r}:${s(S.start)}-${s(S.end)}`)}},{id:"look-domains",chapter:"Zooming in",title:"Domains",text:"Each dark square along the diagonal is a domain, or TAD: a stretch that touches itself more than its neighbours. Most sit inside bigger ones — the big square from 45.7 to 48.3 Mb holds two.",target:b},{id:"oe-on",chapter:"Zooming in",title:"Turn on O/E",text:"O/E divides each pixel by what its distance predicts, so what is left is structure rather than distance.",target:P(Ce),done:()=>e.view()?.oe===!0,needs:{holds:n,back:"open-set"}},{id:"smooth",chapter:"Zooming in",title:"Smooth it",text:"At 5 kb most pixels hold a handful of contacts. Set smooth to 3 × 3, which averages each pixel with the eight around it.",action:"choose",target:P(()=>ce("smooth")),done:()=>e.view()?.smooth===Oe,needs:{holds:n,back:"open-set"}},{id:"look-oe",chapter:"Zooming in",title:"Domains and compartments",text:"Red is more contact than the distance predicts, blue less: the domains are red squares, and the checkerboard behind them is A and B again.",target:b},...te("Insulation","insulation","Diamond insulation",{choose:"It scores how much contact crosses each bin; its dips are the boundaries between domains.",none:"Again, press none…",tick:`…then tick ${r}.`,run:"Press run. Four windows over a whole chromosome at 5 kb take a little while."},{form:t=>[{id:"insulation-scales",chapter:"Insulation",title:"Four scales",text:`Set scales to ${q}. The window is 10 bins, 50 kb here, and each scale doubles it: 50, 100, 200 and 400 kb, one insulation track each.`,action:"type",target:()=>_("scales"),focus:!0,done:()=>Number(_("scales")?.value)===q,needs:{holds:t,back:"insulation"},assist:{label:"set it for me",title:`Set scales to ${q}`,run:()=>Me(_("scales"),String(q))}}],ran:t=>t.scales===q&&e.binsize()===$}),{id:"look-insulation",chapter:"Insulation",title:"Your insulation, at four scales",text:"Four scores are drawn left of the map, one per window, with the boundaries and the domains between them. The scales are the TAD hierarchy: the 50 kb window dips at the edge of every small domain, the 400 kb one only at the borders of the big ones. A border every window finds is high in the hierarchy; one only the narrow windows see is a subTAD’s, nested inside a bigger domain.",target:b},{id:"annotations",chapter:"Marks",title:"Open the Annotations panel",text:"Every track has a row here, the ones you computed among them, and so do the marks you draw.",target:()=>y("annotations"),done:()=>e.panelOpen("annotations"),needs:{holds:n,back:"open-set"}},{id:"mark-loop",chapter:"Marks",title:"Mark the loop",text:["The big domain has a dot at its corner: a loop, its two borders held together. In Manual annotations, under Arrowheads, type ",{name:`${r}:${s(d.rows)}`,copy:!0}," in rows and ",{name:`${r}:${s(d.cols)}`,copy:!0}," in columns, then press add."],target:()=>D("Arrowheads")??H(),done:ye,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"Not on screen — scroll the Annotations panel to Manual annotations.",assist:{label:"mark it for me",title:`An arrowhead at ${r}:${s(d.rows)} × ${r}:${s(d.cols)}`,run:()=>{const t=D("Arrowheads"),[o,a]=[...t?.querySelectorAll("input")??[]];o===void 0||a===void 0||(o.value=`${r}:${s(d.rows)}`,a.value=`${r}:${s(d.cols)}`,ue(t)?.click())}}},{id:"mark-border",chapter:"Marks",title:"Mark the weak border",text:["Inside that domain one border is weak: the 400 kb window barely dips there, 4DN calls it Weak, and it splits the domain into two subTADs. Under Lines, keep vertical, type ",{name:`${r}:${s(E)}`,copy:!0}," and press add."],target:()=>D("Lines")??H(),done:we,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"Not on screen — scroll the Annotations panel to Manual annotations.",assist:{label:"mark it for me",title:`A vertical line at ${r}:${s(E)}`,run:()=>{const t=D("Lines"),o=t?.querySelector("select"),a=t?.querySelector("input");o==null||a===null||a===void 0||(o.value="vertical",a.value=`${r}:${s(E)}`,ue(t)?.click())}}},{id:"look-marks",chapter:"Marks",title:"A loop and a subTAD border",text:"The arrowhead points at the loop closing the big domain, and the line marks the border inside it. Find the same place on your four insulation tracks, left of the map: a deep dip at 50 kb, barely one at 400 kb — that is the hierarchy, read off one bin.",target:b},{id:"insulation-row",chapter:"Tracks",title:"Unfold your insulation’s settings",text:"A computed track is a track like any other: press the arrow on your first insulation row.",target:()=>R()?.querySelector(".ann-more")??null,done:K,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"No insulation row — run Diamond insulation again."},{id:"insulation-bigwig",chapter:"Tracks",title:"Save it as a bigWig",text:"Press bigWig to save the score as a file IGV, deepTools and pyBigWig open — written here, in this page, with nothing uploaded.",target:()=>{for(const t of R()?.querySelectorAll(".ann-exports button")??[])if(l(t)==="bigWig")return t;return null},done:()=>Y(".bw"),needs:{holds:()=>e.panelOpen("annotations")&&K(),back:"insulation-row"}},{id:"domains",chapter:"Tracks",title:"Unfold the domains’ settings",text:"Press the arrow on the Insulation domains row.",target:()=>T()?.querySelector(".ann-more")??null,done:x,needs:{holds:()=>e.panelOpen("annotations"),back:"annotations"},missing:"No Insulation domains row — run Diamond insulation with its domains on."},{id:"domains-display",chapter:"Tracks",title:"Draw the domains as a 1D track",text:"Domains are outlined on the map. Choose 1D track to draw them as a lane beside it instead.",action:"choose",target:()=>T()?.querySelector(`select[data-display="${O}"]`)??null,done:L,needs:{holds:x,back:"domains"}},{id:"domains-bottom",chapter:"Tracks",title:"Put it under the map",text:"Press the bottom edge to draw the lane under the map…",target:()=>j("bottom"),done:()=>V()?.bottom===!0,needs:{holds:()=>x()&&L(),back:"domains-display"}},{id:"domains-left",chapter:"Tracks",title:"Take it off the side",text:"…and the left edge to take it off the left.",target:()=>j("left"),done:()=>{const t=V();return t!==null&&t.bottom&&!t.left},needs:{holds:()=>x()&&L(),back:"domains-display"}},{id:"export-format",chapter:"The figure",title:"Choose PDF",text:"The Export card at the top of the Aesthetics panel saves what is on screen — the map, your marks and every track — as a figure. Choose PDF (vector): lines and text stay sharp at any size.",action:"choose",target:()=>N()?.querySelector("select.select-format")??y("aesthetics"),done:()=>N()?.querySelector("select.select-format")?.value==="pdf",needs:{holds:n,back:"open-set"}},{id:"export-save",chapter:"The figure",title:"Save the figure",text:"Press the download button beside it.",target:()=>N()?.querySelector(".export-acts button")??y("aesthetics"),done:()=>Y(".pdf"),needs:{holds:()=>N()?.querySelector("select.select-format")?.value==="pdf",back:"export-format"}},J("analysis-trackcorr","Track correlation"),{id:"trackcorr",chapter:"Track correlation",title:"Choose Track correlation",text:"It measures how closely every pair of loaded tracks agrees.",target:()=>se("Track correlation"),done:()=>e.task()==="trackcorr",needs:{holds:()=>e.panelOpen("analysis"),back:"analysis-trackcorr"},missing:"Not in the list — empty the box over it if a word is typed there."},{id:"tick-tracks",chapter:"Track correlation",title:"Tick every track",text:[{name:ae}," and ",{name:re},", 4DN’s insulation and E1, your E1, and your insulation at all four scales."],target:()=>B().map(t=>t?.closest(".param-field")??null).find(t=>t!==null)??null,done:()=>B().every(t=>t?.querySelector("input")?.checked===!0),needs:{holds:()=>e.task()==="trackcorr",back:"trackcorr"},missing:"Not in the list — a track did not load, or was closed.",assist:{label:"tick them for me",title:"Tick every track in the list",run:()=>{for(const t of B()){const o=t?.querySelector("input");o!=null&&!o.checked&&o.click()}}}},{id:"trackcorr-run",chapter:"Track correlation",title:"Run it",text:`Every pair is compared over the windows all of them have values in, which is ${r}.`,target:me,done:()=>{const t=ne();return t.some(o=>o===void 0)?!1:e.runs("trackcorr").some(o=>{const a=new Set(z(o.provenance.params.tracks)??[]);return t.every(u=>u!==void 0&&a.has(u.id))})},needs:{holds:()=>e.task()==="trackcorr"||e.running("trackcorr"),back:"trackcorr"}},{id:"look-trackcorr",chapter:"Track correlation",title:"Yours against 4DN’s",text:"Each square compares two tracks: red where they rise and fall together, blue where one rises as the other falls. Find yours against 4DN’s — an unphased E1 can match upside down, at −1 — and your four scales against each other: neighbouring windows agree most, the hierarchy again.",target:()=>de("Track correlation")},{id:"console",chapter:"The console",title:"Every step is a command",text:"Open the console: each file you opened and each run you made is a line you can paste into a terminal to do it again.",target:()=>i('.head-actions button[aria-label="console"]')??i('button[aria-label="console"]'),done:()=>e.consoleOpen()},{id:"finish",chapter:"Done",title:"That’s the tour",text:`You opened a map from 4DN, called compartments and domains at four scales on ${r}, marked a loop and a subTAD border, saved a track and a figure, and set it all against 4DN’s own. The tutorial is on the landing page and in About whenever you want it again.`,hero:!0}]}export{r as TUTORIAL_SEQUENCE,m as TUTORIAL_SET,A as TUTORIAL_STORE,_e as tutorialSteps};
@@ -0,0 +1,12 @@
1
+ import{e as g,I as ys,J as q,K as vs,N as ge,O as Lt,P as ce,Q as qt,R as zt,V as hn,T as ws,U as ks,W as bt,X as Q,L as Z,Y as xs,Z as Ss,_ as be,$ as Ms,a0 as fn,a1 as $s,a2 as Es,a3 as Ts,a4 as Rt,a5 as st,a6 as Cs,a7 as At,a8 as As,a9 as Ns,aa as Ls,ab as Os,ac as Is,ad as Fs,ae as Ps,af as Bs,ag as mn,b as N,ah as z,ai as J,aj as qs,ak as zs,al as Rs,am as pn,an as gn,ao as bn,ap as Ds,aq as _s,ar as Vs,as as Ws,at as Gs,au as ye,av as Hs,aw as Ks,ax as Ys,ay as Us,az as yn,aA as vn,aB as wn,aC as kn,aD as Zs,aE as kt,aF as Xs,aG as Js,aH as Qs,aI as ve,aJ as js,aK as ti,aL as ei,aM as ni,aN as we,aO as si,aP as ii,aQ as oi,aR as ri,aS as ke,i as xe,aT as ai,aU as Xt,aV as li,aW as W,aX as ci,aY as X,aZ as yt,a_ as xn,a$ as Jt,b0 as ui,b1 as di,b2 as Qt,b3 as hi,b4 as Vt,b5 as fi,b6 as ct,b7 as Se,C as Me,b8 as mi,b9 as Sn,ba as pi,bb as gi,bc as bi,bd as Mn,be as yi,bf as $e,bg as vi,bh as wi,bi as ki,bj as ft,bk as xi,bl as Si,bm as Mi,bn as $i,bo as Ei,bp as Ti,bq as Ci,br as Ee,bs as Te,bt as Ai,bu as Ni,bv as Li,bw as $n,bx as Ce,by as Oi}from"./index-Cys9FWNc.js";function En(n,t){if(t===void 0)return"—";if(n.kind!=="number")return String(t);const e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?n.coordinate==="start"?ys(e):n.coordinate==="end"?q.pos(e):n.digits===void 0?q.int(e):n.scientific===!0&&e!==0&&Math.abs(e)<10**-n.digits?e.toExponential(2):e.toFixed(n.digits):"—"}function Ii(n,t){const e=t.filter.trim().toLowerCase();let s=n.rows;e!==""&&(s=s.filter(l=>n.columns.some(c=>En(c,l[c.key]).toLowerCase().includes(e))));const i=t.sortKey;if(i===null)return s;const o=n.columns.find(l=>l.key===i);if(o===void 0)return s;const r=t.sortDown?-1:1,a=l=>l===void 0||o.kind==="number"&&!Number.isFinite(Number(l));return[...s].sort((l,c)=>{const u=l[i],d=c[i];return a(u)!==a(d)?a(u)?1:-1:a(u)?0:o.kind==="number"?r*(Number(u)-Number(d)):r*String(u).localeCompare(String(d))})}function Fi(n,t){const e=t.columns;if(e===null)return n.columns;const s=n.columns.filter(i=>e.includes(i.key));return s.length===0?n.columns:s}function Pi(n,t,e){const s=Fi(n,t),i=Ii(n,t),o=g("thead",{class:"thead"},g("tr",{},...s.map(u=>{const d=t.sortKey===u.key,m=g("th",{class:`td figure-th${d?" is-sorted":""}${u.kind==="number"?" num":""}`,text:`${u.label}${d?t.sortDown?" ↓":" ↑":""}`,title:u.hint??`Sort by ${u.label}`,attrs:{role:"button",tabindex:"0"}}),f=()=>e(u.key,d?!t.sortDown:!1);return m.addEventListener("click",f),m.addEventListener("keydown",h=>{h.key!=="Enter"&&h.key!==" "||(h.preventDefault(),f())}),m}))),r=g("tbody",{});for(const u of i)r.appendChild(g("tr",{style:{borderTop:"1px solid var(--border)"}},...s.map(d=>g("td",{class:d.kind==="number"?"td num":"td",text:En(d,u[d.key])}))));const a=g("table",{style:{borderCollapse:"collapse",width:"100%",fontVariantNumeric:"tabular-nums"}},o,r),l=n.rows.length===0?"This run produced no rows.":`No row matches “${t.filter}”. ${n.rows.length} were produced.`;return{el:g("div",{class:"analysis-figure-scroll"},i.length===0?g("div",{class:"tempty",text:l}):a),destroy(){}}}function Bi(n,t){const e=n[t];return Array.isArray(e)?e.filter(s=>typeof s=="string"):typeof e=="string"&&e!==""?[e]:[]}function qi(n,t){let e=null;for(const s of n){if(s.kind!=="region")continue;const i=t[s.key];if(typeof i!="string"||i.trim()==="")continue;const o=s.many===!0?vs(i).map(ge).join(", "):ge(i);o!==i&&(e??={...t},e[s.key]=o)}return e??t}function zi(n,t){const e=n[t];return typeof e=="string"&&e!==""?e:null}function Ae(){const n=new Error("cancelled");return n.name="AbortError",n}function Ri(n){return n.rows[1]<=n.rows[0]&&n.cols[1]<=n.cols[0]}const Di="chromosomix",_i="count";function Tn(n){const t=[],e=[Di,n.task.id],{framing:s,params:i}=n.provenance,o=Ri(s);o||(e.push(G(s.uri)),Zi(s.uri)&&s.binsize>0&&e.push("--bin-size",String(s.binsize)));const r=n.task.params.some(p=>p.key==="window");if(!o&&!r){const p=Yi(s.rows,s.cols,n.context);p.locus!==null&&e.push("--window",G(p.locus)),p.note!==null&&t.push(p.note)}const a=n.task.params.find(p=>p.key==="balance"),l=a!==void 0&&Lt(a),c=l&&typeof i.balance=="boolean"?i.balance:s.balance;!o&&!c&&e.push("--no-balance"),!o&&l&&c!==s.balance&&t.push(`The map was drawn ${s.balance?"balanced":"unbalanced"} while the task read it ${c?"balanced":"unbalanced"}, and --no-balance sets both together. This follows the task, so the numbers match; only the framing line the run records will differ.`);const u=(s.circular??[]).filter(p=>p!=="");u.length>0&&e.push("--circular",G(u.join(",")));const d=Object.entries(s.origins??{}).filter(([p,w])=>p!==""&&Number.isFinite(w));if(d.length>0&&e.push("--origin",G(d.map(([p,w])=>`${p}:${w+1}`).join(","))),!o){s.value!==""&&s.value!==_i&&e.push("--value",G(s.value)),s.contacts!==void 0&&e.push("--contacts",String(s.contacts)),s.coarsen!==void 0&&e.push("--coarsen",String(s.coarsen)),s.edit!==void 0&&t.push("The map was drawn through an edit of its reference, which the command line cannot yet apply: this line measures the file as it is.");const p=n.context?.selectedCells??[];p.length>0?e.push("--cell",G(p.join(","))):n.context!==null&&(n.context.cells??0)>0&&(n.context.activeCells??n.context.cells??0)<(n.context.cells??0)&&t.push("The map was summed from a subset of the file’s cells, and the record does not name them. Add --cell <name> for each.")}if(n.task.needsPeers===!0){const p=n.context?.peers??[];for(const w of p)e.push("--against",G(w.uri));p.length===0&&t.push(`${n.task.id} compares this map with the others on screen, and the record does not name them. Add --against <file> for each.`)}const m=n.context?.entries??[],f=[],h=new Set,y=Vi(n.task);for(const p of n.task.params)if(Cn(p))for(const w of An(i[p.key])){const M=Nn(m,w);if(M===null){t.push(`--${p.key} named something with no file behind it${Hi(m,w)} — a set this app computed, most likely. Point it at a file, or export that row first.`);continue}const v=p.kind==="sequence"?"--sequence":p.kind==="pairSet"?"--pairs":p.kind==="track"?`--${p.key}`:"--features";(v===`--${p.key}`||p.kind==="sequence"&&p.key===y)&&h.add(p.key);const x=`${v} ${G(M)}`;f.includes(x)||f.push(x)}for(const p of f)e.push(...p.split(" "));for(const p of n.task.params){if(p.key==="balance"&&Lt(p)||h.has(p.key)||p.retired===!0&&Wi(p,i[p.key]))continue;const w=Gi(p,i[p.key],m);w!==null&&e.push(...w)}const b=e.join(" ");return{text:[...t.map(p=>`# ${p}`),b].join(`
2
+ `)}}function Vi(n){const t=n.params.filter(e=>e.kind==="sequence"&&e.multiple!==!0);return t.some(e=>e.key==="sequence")?"sequence":n.upstreamParams===void 0||(n.requires??[]).length===0?null:t.length===1?t[0].key:null}function Wi(n,t){const e=qt([n])[n.key];return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((s,i)=>s===t[i]):t===void 0||t===e}function Cn(n){return n.kind==="featureSet"||n.kind==="pairSet"||n.kind==="track"||n.kind==="sequence"}function An(n){return typeof n=="string"?n===""?[]:[n]:Array.isArray(n)?n.filter(t=>typeof t=="string"):[]}function Gi(n,t,e){if(t==null)return null;if(Cn(n)){const s=An(t).map(i=>Nn(e,i)).filter(i=>i!==null);return s.length===0?null:[`--${n.key}`,G(s.join(","))]}if(typeof t=="boolean")return[t?`--${n.key}`:`--${n.key}=false`];if(Array.isArray(t)){const s=t.filter(i=>i!=null).map(String);return s.length===0?null:[`--${n.key}`,G(s.join(","))]}return typeof t=="number"?Number.isFinite(t)?[`--${n.key}`,String(t)]:null:t===""?null:[`--${n.key}`,G(String(t))]}function Nn(n,t){const e=n.find(i=>i.id===t);if(e===void 0)return null;const s=e.source;return s.kind==="local"||s.kind==="detached"?s.name:s.kind==="remote"?Ki(s.url):null}function Hi(n,t){const e=n.find(s=>s.id===t);return e===void 0?"":` (“${e.label}”)`}function Ki(n){const e=n.split(/[?#]/)[0].split("/").filter(s=>s!=="").pop();return e===void 0||e===""?n:e}function Yi(n,t,e){if(e===null)return{locus:null,note:null};const s=e.nBins;if(n[0]===0&&n[1]>=s&&t[0]===0&&t[1]>=s||s===0)return{locus:null,note:null};if(n[0]!==t[0]||n[1]!==t[1])return{locus:null,note:"The view was an off-diagonal block — two different windows on the two axes — and --window names one. This runs over the whole file."};const o=e.genomes?.find(c=>c.extent[0]===n[0]&&c.extent[1]===n[1]);if(o!==void 0)return{locus:o.name,note:null};const r=Ui(e.contigs,n);if(r===null)return{locus:null,note:"The view covered several sequences without covering the file, and --window names one locus. This runs over the whole file."};if(n[0]===r.startBin&&n[1]>=r.startBin+r.bins)return{locus:r.name,note:null};const a=(n[0]-r.startBin)*e.binsize,l=Math.min(r.length,(n[1]-r.startBin)*e.binsize);return{locus:ce({contig:r.name,start:a,end:l}),note:null}}function Ui(n,t){for(const e of n){if(e.bins===0)continue;const s=e.startBin,i=e.startBin+e.bins;if(t[0]>=s&&t[1]<=i)return e}return null}function G(n){return n===""?"''":/^[A-Za-z0-9_@%+=:,./-]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function Zi(n){return/\.pairs(\.b?gz)?$/i.test(n.split("::")[0].split(/[?#]/)[0])}const Xi=[hn,ws].filter(n=>n!=="").join(" ");function Ji(n,t,e){return{task:n.id,taskVersion:n.version,params:t,framing:e,app:Xi,createdAt:new Date().toISOString()}}function Ne(n){const{task:t,provenance:e,context:s,where:i}=n,o=Tn({task:t,provenance:e,context:s}),r=zt(e),a=i===void 0?{}:{where:i},l=o.text.split(`
3
+ `);return{kind:"run",line:l[l.length-1],shell:!0,notes:l.slice(0,-1),detail:r,...a}}function Ln(n,t){return Qi(n.params,t.params)&&to(n.framing,t.framing)}function Qi(n,t){const e=Object.keys(n);if(e.length!==Object.keys(t).length)return!1;for(const s of e)if(!(s in t)||!ji(n[s],t[s]))return!1;return!0}function ji(n,t){return Array.isArray(n)||Array.isArray(t)?!Array.isArray(n)||!Array.isArray(t)||n.length!==t.length?!1:n.every((e,s)=>e===t[s]):Object.is(n,t)}function to(n,t){return n.uri===t.uri&&n.rows[0]===t.rows[0]&&n.rows[1]===t.rows[1]&&n.cols[0]===t.cols[0]&&n.cols[1]===t.cols[1]&&n.binsize===t.binsize&&n.binsPerCell===t.binsPerCell&&n.balance===t.balance&&n.value===t.value&&n.level===t.level&&(n.contacts??null)===(t.contacts??null)&&(n.edit??null)===(t.edit??null)&&(n.coarsen??null)===(t.coarsen??null)&&eo(n.circular??[],t.circular??[])&&no(n.origins??{},t.origins??{})}function eo(n,t){if(n.length!==t.length)return!1;const e=new Set(n);return t.every(s=>e.has(s))}function no(n,t){const e=Object.keys(n);return e.length===Object.keys(t).length&&e.every(s=>n[s]===t[s])}const so=100;function lt(n,t){return`${n}\0${t}`}const io=8;function Wt(n,t){return`${n}\0${t}`}function oo(n,t,e,s,i,o){const r=t===void 0||t.length===0?n:`${n}\0${t.join("\0")}`,a=e===void 0?r:`${r}\0${e.base}:${e.rungs}`,l=s===void 0?a:`${a}\0contacts:${s.contacts}:${s.seed??""}:${s.alpha??""}`,c=i===void 0?l:`${l}\0edit:${$s(i)}`;return o===void 0?c:`${c}\0coarsen:${o}`}function Le(n){return fn(n.label)}function ro(n){return{line:n.line,notes:n.notes??[],detail:n.detail??[]}}class ao{host;makeClient;client=null;mounted=null;states=new Map;results=new Map;history=new Map;resultTargets=new Map;queue=[];current=null;held=new Map;listeners=new Set;lastNotifiedAt=0;trailing=null;destroyed=!1;constructor(t,e=()=>new ks){this.host=t,this.makeClient=e}stateOf(t){return this.states.get(t)??{status:"idle"}}holdFile(t,e,s){const i=Wt(t,e);s===null?this.held.delete(i):this.held.set(i,s)}heldFile(t,e){return this.held.get(Wt(t,e))}resultOf(t,e){const s=e??this.homeOf(t);return this.results.get(lt(s,t))??null}homeOf(t){const e=this.host.task?.(t)??bt(t);return e!==void 0&&!Q(e)?Z:this.host.targetMap?.()??Z}runsOf(t,e){const s=e??this.homeOf(t),i=lt(s,t),o=this.results.get(i),r=this.history.get(i)??[];return o===void 0?[...r]:[o,...r]}resultsFor(t){const e=this.host.allTargets?.()??[],s=new Set,i=[];for(const o of e){const r=this.results.get(lt(o.map,t));r!==void 0&&(s.add(o.map),i.push({target:o,result:r}))}for(const[o,r]of this.results){const a=this.resultTargets.get(o);a===void 0||s.has(a.map)||o===lt(a.map,t)&&i.push({target:a,result:r})}return i}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}get busy(){return this.current!==null||this.queue.length>0}run(t,e){this.queueOne(t,e,null)}runAll(t,e,s){if(!Q(t)){this.queueOne(t,e,null);return}if(s.length!==0){if(s.length===1){this.queueOne(t,e,null,s[0]);return}this.cancel(t.id),s.forEach((i,o)=>{this.queueOne(t,e,{at:o,of:s.length},i)})}}queueOne(t,e,s,i){if(this.destroyed)return;const o=this.host.context(t);if(o===null){this.refuse(t,s,"nothing is open");return}const r=t.mapless===!0?Oe(o,"sequences"):o.framing??(t.venue==="annotations"?Oe(o):null);if(r===null){this.refuse(t,s,"this view has no contact map to run against");return}const a=Q(t)?i??this.hostTarget(r,t):{...this.hostTarget(r,t),map:Z};if(s===null){if(this.current?.task.id===t.id&&this.current.target.map===a.map)return;const l=this.queue.find(c=>c.task.id===t.id&&c.target.map===a.map);if(l!==void 0){l.params=e,l.framing=r;return}}this.queue.push({task:t,params:e,framing:r,target:a,batch:s,cancelled:!1,running:null}),this.setState(t.id,{status:"queued"}),this.pump()}targets(){return this.host.allTargets?.()??[]}async readyTargets(){return await this.host.allTargetsReady?.()??this.targets()}targetCount(){return this.host.targetCount?.()??this.targets().length}target(){const t=this.host.targetMap?.();return t===void 0?null:this.targets().find(e=>e.map===t)??null}hostTarget(t,e){const s=this.host.source(e);return{map:this.host.targetMap?.()??Z,uri:s?.uri??t.uri,...s===null?{}:{source:s.source},...s?.cells===void 0?{}:{cells:s.cells},...s?.binning===void 0?{}:{binning:s.binning},...s?.orientation===void 0?{}:{orientation:s.orientation},...s?.pairsStats===void 0?{}:{pairsStats:s.pairsStats},...s?.resample===void 0?{}:{resample:s.resample},...s?.edit===void 0?{}:{edit:s.edit},label:s?.label??t.uri}}cancel(t){let e=0;for(let i=this.queue.length-1;i>=0;i--)this.queue[i].task.id===t&&(this.queue.splice(i,1),e++);const s=this.current;if(s===null||s.task.id!==t){e>0&&this.setState(t,{status:"cancelled"});return}s.cancelled=!0,s.running?.handle.cancel()}destroy(){this.destroyed=!0;for(const t of this.queue)this.setState(t.task.id,{status:"cancelled"});this.queue.length=0,this.current!==null&&(this.current.cancelled=!0,this.setState(this.current.task.id,{status:"cancelled"})),this.trailing!==null&&(clearTimeout(this.trailing),this.trailing=null),this.client?.terminate(),this.client=null,this.mounted=null,this.listeners.clear()}pump(){if(this.current!==null||this.destroyed)return;const t=this.queue.shift();t!==void 0&&(this.current=t,this.execute(t).finally(()=>{this.current=null,this.pump()}))}batchOf(t){return t.batch===null?{}:{batch:{at:t.batch.at,of:t.batch.of,label:t.target.label}}}async execute(t){const e=performance.now();let s=null;const i=this.recordStart(t);let o=null;this.setState(t.task.id,{status:"running",done:0,total:0,note:"starting",startedAt:e,...this.batchOf(t)});try{const r=this.plan(t.task,t.params),a=this.ensureClient();r.some(c=>c.task.venue!=="annotations")&&await this.mount(t,a,e);const l={};for(let c=0;c<r.length;c++){if(s=r[c],t.cancelled)throw Ae();const u=s.task.id===t.task.id,d=this.results.get(lt(t.target.map,s.task.id));if(!u&&d!==void 0&&Ln(d.provenance,{params:s.params,framing:t.framing})){l[s.task.id]=d;continue}const m=await this.runStep(t,a,s,r,c,l,e);if(t.cancelled)throw Ae();const f=lt(t.target.map,s.task.id),h=this.results.get(f);if(h!==void 0&&h!==m){const y=this.history.get(f)??[];y.unshift(h),this.history.set(f,y.slice(0,io))}this.results.set(f,m),this.resultTargets.set(f,t.target),u?(this.setState(s.task.id,{status:"done",result:m,ms:performance.now()-e}),this.host.finished(t.task,m,t.target),o={status:"ok",ms:performance.now()-e,...ro(Ne({task:t.task,provenance:this.recordable(t,m.provenance),context:this.host.context(t.task),where:Le(t.target)}))}):(l[s.task.id]=m,this.setState(s.task.id,{status:"done",result:m,ms:m.ms}))}}catch(r){const a=t.cancelled||xs(r),l=a?{status:"cancelled"}:{status:"failed",message:r instanceof Error?r.message:String(r)};s!==null&&s.task.id!==t.task.id&&this.setState(s.task.id,l),this.setState(t.task.id,l),o=a?{status:"cancelled"}:{status:"failed",error:r instanceof Error?r.message:String(r)}}finally{t.running=null,Ss(i,o??{status:"cancelled"})}}refuse(t,e,s){this.setState(t.id,{status:"failed",message:s}),!(e!==null&&e.at>0)&&be({kind:"run",line:`ran ${t.title}`,status:"failed",error:s})}recordStart(t){const e=Ne({task:t.task,provenance:this.recordable(t,Ji(t.task,t.params,t.framing)),context:this.host.context(t.task),where:Le(t.target)});return be({...e,status:"running"})}recordable(t,e){const s=t.target.uri;return s===""||s===e.framing.uri?e:{...e,framing:{...e.framing,uri:s}}}async mount(t,e,s){const i=t.target;if(i.source===void 0)throw new Error(`${t.task.title} reads a contact map, and this session is browsing a genome without one.`);const o=t.framing.coarsen,r=oo(i.uri,i.cells,i.binning,i.resample,i.edit,o);this.mounted!==r&&(this.setState(t.task.id,{status:"running",done:0,total:0,note:"opening the file",startedAt:s,...this.batchOf(t)}),this.mounted=null,await e.request({kind:"open",uri:i.uri,source:i.source,...i.cells===void 0?{}:{cells:i.cells},...i.binning===void 0?{}:{binning:i.binning},...i.resample===void 0?{}:{resample:i.resample},...i.edit===void 0?{}:{edit:i.edit},...o===void 0?{}:{coarsen:o}}),this.mounted=r)}async runStep(t,e,s,i,o,r,a){const l=f=>{const h=f===void 0||f===""?"":f;if(i.length===1)return h===""?s.task.title:h;const y=`${s.task.title} (${o+1}/${i.length})`;return h===""?y:`${y} — ${h}`};this.setState(t.task.id,{status:"running",done:0,total:0,note:l(),startedAt:a,...this.batchOf(t)});const c=(f,h,y)=>{this.setState(t.task.id,{status:"running",done:f,total:h,note:l(y),startedAt:a,...this.batchOf(t)},!0)},u={kind:"run",task:s.task.id,params:qi(s.task.params,s.params),framing:t.framing,inputs:await this.inputsFor(s,t,r)};let d;if(s.task.venue==="annotations"){const f=this.host.annotations?.();if(f==null)throw new Error(`${s.task.title} runs against the loaded tracks, and this session has no annotations worker.`);const h=f.cancellable(u,c);t.running={id:s.task.id,handle:h},d=await h.promise,t.running=null}else{const f=e.cancellable(u,c);t.running={id:s.task.id,handle:f},d=await f.promise,t.running=null}const m=t.framing.normalise===null?d.notes:[...d.notes,`The map is drawn with ${t.framing.normalise.toUpperCase()} normalisation, which is computed from the block after it is read and cannot be asked of the file. These numbers are the underlying counts.`];return{...d,notes:m,provenance:{...d.provenance,params:s.params,taskVersion:s.task.version}}}ensureClient(){return this.client??=this.makeClient(),this.client}plan(t,e){const s=[],i=new Set,o=new Set,r=(a,l)=>{if(!i.has(a.id)){if(o.has(a.id))throw new Error(`the analysis task ${a.id} requires itself`);o.add(a.id);for(const c of a.requires??[]){const u=this.host.task?.(c)??bt(c);if(u===void 0)throw new Error(`${a.id} requires the task ${c}, which this session does not offer`);const d=Ms(a,c,l);d!==null&&r(u,{...qt(u.params),...d})}o.delete(a.id),i.add(a.id),s.push({task:a,params:l})}};return r(t,e),s}async inputsFor(t,e,s){const i=e.framing,o={},r={},a={},l={};for(const f of t.task.params)if(!(f.kind!=="featureSet"&&f.kind!=="pairSet"&&f.kind!=="track"&&f.kind!=="sequence"))for(const[h,y]of lo(f,t.params)){const b=this.host.label?.(y);if(b!==void 0&&b!==""&&(l[y]=b),f.kind==="track"||f.kind==="sequence"){if(t.task.venue==="annotations")continue;const p=await this.host.vector?.(y);p!==void 0&&(a[h]=p);continue}const k=this.host.payload(y);k!==void 0&&(f.kind==="featureSet"&&k.kind==="features"&&(o[h]=k.data),f.kind==="pairSet"&&k.kind==="pairs"&&(r[h]=k.data))}const c={};for(const f of t.task.params){if(f.kind!=="file")continue;const h=this.held.get(Wt(t.task.id,f.key));h!==void 0&&h.value===t.params[f.key]&&(c[f.key]=h.source)}const u={};if(Object.keys(c).length>0&&(u.sources=c),Object.keys(o).length>0&&(u.features=o),Object.keys(r).length>0&&(u.pairs=r),Object.keys(l).length>0&&(u.labels=l),t.task.venue==="annotations"){const f=this.host.contigLengths?.(e.task);f!==void 0&&(u.contigLengths=f)}if(Object.keys(a).length>0&&(u.vectors=a),Object.keys(s).length>0&&(u.upstream={...s}),e.target.orientation!==void 0&&(u.orientation=e.target.orientation),e.target.binning!==void 0&&e.target.source!==void 0&&(u.mapSource=e.target.source),e.target.pairsStats!==void 0&&(u.pairsStats=e.target.pairsStats),t.task.id==="hicrep"){const f=[],h=await this.host.allTargetsReady?.()??this.host.allTargets?.()??[];for(const y of h)y.map===e.target.map||y.source===void 0||f.push({label:y.label,uri:y.uri,source:y.source,...y.cells===void 0?{}:{cells:y.cells},...y.binning===void 0?{}:{binning:y.binning},...y.resample===void 0?{}:{resample:y.resample},...e.framing.coarsen===void 0?{}:{coarsen:e.framing.coarsen}});f.length>0&&(u.peers=f),e.target.label!==""&&(u.mapLabel=e.target.label)}t.task.id==="mapreport"&&e.target.source!==void 0&&e.target.binning===void 0&&(u.self={label:e.target.label,uri:e.target.uri,source:e.target.source,...e.target.cells===void 0?{}:{cells:e.target.cells},...e.target.resample===void 0?{}:{resample:e.target.resample}});const d=this.hostBlockFor(e),m=(i.contacts??null)===(e.target.resample?.contacts??null);return d!==null&&m&&co(d)&&uo(d,i)&&(u.block=d),u}hostBlockFor(t){const e=this.host.targetMap?.()??Z;return t.framing.coarsen!==void 0?null:t.target.map===e?this.host.block():null}setState(t,e,s=!1){this.states.set(t,e),s?this.notifySoon():this.notifyNow()}notifyNow(){this.trailing!==null&&(clearTimeout(this.trailing),this.trailing=null),this.lastNotifiedAt=performance.now();for(const t of[...this.listeners])t()}notifySoon(){const t=so-(performance.now()-this.lastNotifiedAt);if(t<=0){this.notifyNow();return}this.trailing===null&&(this.trailing=setTimeout(()=>{this.trailing=null,this.notifyNow()},t))}}function lo(n,t){if(n.multiple===!0)return Bi(t,n.key).map(s=>[`${n.key}:${s}`,s]);const e=zi(t,n.key);return e===null?[]:[[n.key,e]]}function co(n){return n.values.byteLength<=Es}function uo(n,t){return n.rowExtent[0]===t.rows[0]&&n.rowExtent[1]===t.rows[1]&&n.colExtent[0]===t.cols[0]&&n.colExtent[1]===t.cols[1]&&n.binsPerCell===t.binsPerCell}function Oe(n,t="loaded tracks"){return{uri:n.uri,rows:[0,0],cols:[0,0],binsize:n.binsize,binsPerCell:1,balance:!1,value:"count",normalise:null,level:"bin",label:`${fn(n.uri)} · ${t}, no contact map`,...n.circular===void 0?{}:{circular:[...n.circular]},...n.origins===void 0?{}:{origins:{...n.origins}}}}const ho="map";function fo(n,t){const e=new Map,s=[];for(const r of n)for(const a of r.result.outputs)e.has(a.id)||(e.set(a.id,[]),s.push(a.id)),e.get(a.id)?.push({label:r.label,output:a});const i=[],o=[];for(const r of s){const a=e.get(r)??[];if(a.some(d=>mo(d.output))){i.push(po(r,a));continue}const l=a.filter(d=>d.output.kind==="table");if(l.length>0&&l.length===a.length){i.push(go(r,l));continue}const u=a.map(d=>({label:d.label,curve:t(d.output),output:d.output})).filter(d=>d.curve!==null);if(u.length<2){(a.length>0&&u.length!==a.length||a.length>1)&&o.push(a[0].output.label);continue}i.push(bo(r,u))}return{outputs:i,perMapOnly:o}}function mo(n){return(n.kind==="curve"||n.kind==="matrix"||n.kind==="table")&&n.acrossMaps===!0}function po(n,t){const e=i=>i.kind==="curve"?i.series.length:i.kind==="matrix"?i.nrows:i.kind==="table"?i.rows.length:0;let s=t[0].output;for(const i of t)e(i.output)>e(s)&&(s=i.output);return{...s,id:`${n}__all`,label:`${s.label} — all maps`}}function go(n,t){const e=[],s=new Set;for(const a of t)for(const l of a.output.columns)s.has(l.key)||(s.add(l.key),e.push(l));let i=ho;for(;s.has(i);)i=`${i}_`;const o=[];for(const a of t)for(const l of a.output.rows)o.push({[i]:a.label,...l});const r=t[0].output;return{kind:"table",id:`${n}__all`,label:`${r.label} — all maps`,columns:[{key:i,label:"Map",kind:"text",hint:"The map this row was measured on, by the name the deck gives it."},...e],rows:o}}function bo(n,t){const e=t.every(c=>c.curve.series.length===1),s=[];for(const c of t)for(const u of c.curve.series)s.push({...u,name:e?c.label:`${c.label} · ${u.name}`,...u.colour===void 0?{}:{colour:u.colour},...u.stack===void 0?{}:{stack:`${c.label} · ${u.stack}`}});const i=t[0].curve,o=i.xTicks,r=o!==void 0&&t.every(c=>c.curve.xTicks?.join("\0")===o.join("\0")),a=i.xScaled,l=a!==void 0&&t.every(c=>JSON.stringify(c.curve.xScaled)===JSON.stringify(a))?a:void 0;return{kind:"curve",id:`${n}__all`,label:`${i.label} — all maps`,series:s,xLabel:i.xLabel,yLabel:i.yLabel,xScale:i.xScale,yScale:i.yScale,...r?{xTicks:[...o]}:{},...l!==void 0?{xScaled:{...l}}:{}}}function yo(n){return Ts(n)}function Ie(n){const t=Math.round(n);return t===0?"0":`${t<0?"-":"+"}${yo(Math.abs(t))}`}function On(n,t){if(!Number.isFinite(t))return"";const e=1e-9*Math.max(1,Math.abs(n.to-n.from));if(Math.abs(t-n.start)<=e)return"Start";if(Math.abs(t-n.end)<=e)return"End";if(t<n.start)return Ie((t-n.start)*n.flankStep);if(t>n.end)return Ie((t-n.end)*n.flankStep);const s=(t-n.start)/(n.end-n.start),i=s*100;return q.pct(s,Math.abs(i-Math.round(i))<1e-6?0:1)}const vo=[50,25,10,5,1],wo=[1,2,2.5,5],ko=1,xo=6;function So(n,t,e,s,i){const[o,r]=t;if(!(r>o)||!(e>0)||!(n.end>n.start))return[];const a=e/(r-o),l=1e-9*Math.max(1,n.to-n.from),c=p=>p>=o-l&&p<=r+l,u=new Map,d=p=>{let w=u.get(p);return w===void 0&&(w=s(On(n,p)),u.set(p,w)),w},m=(p,w)=>Math.abs(w-p)*a+1e-6>=Math.max(xo*i,(d(p)+d(w))/2+ko*i),f=[n.start,n.end].filter(c),h=p=>{const w=[...f,...p].sort((M,v)=>M-v);for(let M=1;M<w.length;M++)if(!(f.includes(w[M-1])&&f.includes(w[M]))&&!m(w[M-1],w[M]))return!1;return!0},y=p=>{let w=null;for(const M of p)M.ticks.length===0||!h(M.ticks)||(w===null||M.ticks.length>w.ticks.length||M.ticks.length===w.ticks.length&&(Number(M.whole)>Number(w.whole)||M.whole===w.whole&&M.step>w.step))&&(w=M);return w===null?[]:w.ticks},b=n.end-n.start;f.push(...y(vo.filter(p=>p/100*b>=1).map(p=>{const w=[];for(let M=1;M*p<100;M++){const v=n.start+M*p/100*b;c(v)&&w.push(v)}return{ticks:w,whole:!1,step:p}})));const k=[{edge:n.start,reach:(n.start-n.from)*n.flankStep,sign:-1},{edge:n.end,reach:(n.to-n.end)*n.flankStep,sign:1}];for(const p of k){if(!(p.reach>0)||!(n.flankStep>0))continue;const w=[];for(const M of Mo(n.flankStep,p.reach)){const v=[];for(let x=1;x*M<=p.reach*(1+1e-12);x++){const E=p.edge+p.sign*x*M/n.flankStep;c(E)&&v.push(E)}w.push({ticks:v,whole:$o(p.reach,M),step:M})}f.push(...y(w))}return f.sort((p,w)=>p-w)}function Mo(n,t){const e=new Set([t]);for(let s=Math.floor(Math.log10(n));10**s<=t;s++)for(const i of wo){const o=Number((i*10**s).toPrecision(12));o>=n*(1-1e-12)&&o<=t*(1+1e-12)&&e.add(o)}return[...e].sort((s,i)=>s-i)}function $o(n,t){const e=n/t;return Math.abs(e-Math.round(e))<1e-9*Math.max(1,e)}function wt(n){return n.filter(t=>Number.isFinite(t)).sort((t,e)=>t-e)}function it(n,t){if(n.length===0)return Number.NaN;if(n.length===1)return n[0];const e=(n.length-1)*Math.min(1,Math.max(0,t)),s=Math.floor(e),i=Math.ceil(e);return s===i?n[s]:n[s]+(e-s)*(n[i]-n[s])}function In(n){const t=wt(n);if(t.length===0)return{low:Number.NaN,q1:Number.NaN,median:Number.NaN,q3:Number.NaN,high:Number.NaN,outliers:[]};const e=it(t,.25),s=it(t,.5),i=it(t,.75),o=1.5*(i-e),r=e-o,a=i+o;let l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;const u=[];for(const d of t){if(d<r||d>a){u.push(d);continue}d<l&&(l=d),d>c&&(c=d)}return Number.isFinite(l)||(l=s),Number.isFinite(c)||(c=s),{low:l,q1:e,median:s,q3:i,high:c,outliers:u}}function Dt(n,t=0){const e=wt(n);if(e.length===0)return{edges:[],counts:[]};const s=e[0],i=e[e.length-1];if(s===i)return{edges:[s,s+1],counts:[e.length]};let o=Math.round(t);if(!(o>0)){const c=it(e,.75)-it(e,.25),u=c>0?2*c/Math.cbrt(e.length):0;o=u>0?Math.ceil((i-s)/u):Math.ceil(Math.sqrt(e.length))}o=Math.max(1,Math.min(400,o));const r=(i-s)/o,a=[];for(let c=0;c<=o;c++)a.push(s+c*r);const l=new Array(o).fill(0);for(const c of e){const u=Math.floor((c-s)/r);l[u>=o?o-1:u<0?0:u]+=1}return{edges:a,counts:l}}function Fe(n,t=64){const e=wt(n);if(e.length<2)return{at:[],y:[]};const s=e.length,i=e.reduce((b,k)=>b+k,0)/s,o=e.reduce((b,k)=>b+(k-i)**2,0)/(s-1),r=Math.sqrt(Math.max(0,o)),a=it(e,.75)-it(e,.25),l=Math.min(r||Number.POSITIVE_INFINITY,a>0?a/1.34:Number.POSITIVE_INFINITY),c=Number.isFinite(l)&&l>0?.9*l*Math.pow(s,-.2):0;if(!(c>0))return{at:[],y:[]};const u=e[0]-3*c,m=(e[s-1]+3*c-u)/Math.max(1,t-1),f=[],h=[],y=1/(s*c*Math.sqrt(2*Math.PI));for(let b=0;b<t;b++){const k=u+b*m;let p=0;for(const w of e){const M=(k-w)/c;p+=Math.exp(-.5*M*M)}f.push(k),h.push(p*y)}return{at:f,y:h}}const Eo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function ot(n){return n.replace(/[&<>"']/g,t=>Eo[t]??t)}function Gt(n){return`<div class="figure-tip-head">${ot(n)}</div>`}function To(n){return typeof n!="string"||n===""?"":`<svg class="figure-tip-swatch" viewBox="0 0 10 10" aria-hidden="true"><circle cx="5" cy="5" r="5" fill="${ot(n)}"/></svg>`}function xt(n,t,e){return`<div class="figure-tip-row">${To(n)}<span class="figure-tip-name">${ot(t)}</span><span class="figure-tip-value">${ot(e)}</span></div>`}function Fn(n,t,e){return n.measure?.(t,e)??t.length*e*.6}function Pn(n,t,e,s){const i=e.colours[n.id];return i!==void 0?i:n.colour!==void 0?n.colour:s.series[t%s.series.length]}function jt(n,t){return Cs(t.mark)?t.mark:n.mark??t.mark}function H(n,t){return!Number.isFinite(n)||t&&n<=0?null:n}function Co(n,t){const e=t.x.scale==="log",s=t.y.scale==="log",i=[];for(let o=0;o<n.y.length;o++){const r=H(n.x[o]??o,e),a=H(n.y[o],s);i.push(r===null||a===null?null:[r,a])}return i}function Bn(n){const t=n.xScaled;if(t!==void 0)return i=>On(t,i);const e=n.binsize;if(e!==void 0)return i=>q.bp(i*e);if(/\(bp\)/i.test(n.xLabel??""))return i=>q.bp(i);const s=n.xTicks;if(s!==void 0)return i=>Number.isInteger(i)?s[i]??"":""}function qn(n){if(/\(%\)/.test(n.yLabel??""))return t=>{const e=t*100;return q.pct(t,Math.abs(e-Math.round(e))<1e-9?0:1)}}const Ao=["high","upper quartile","median","lower quartile","low"];function gt(n){return typeof n=="number"&&Number.isFinite(n)}function No(n){const t=Array.isArray(n)?n[1]:n;return gt(t)?t:null}function Lo(n,t){const e=t.mark==="histogram",s=t.x.scale==="log"?"log":"linear",i=t.y.scale==="log"?"log":"linear",o=e?void 0:Bn(n),r=e?void 0:qn(n),a=c=>{const u=o?.(c)??"";return u!==""?u:st(c,s)},l=r??(c=>st(c,i));return c=>{if(Array.isArray(c)){const h=c[0];if(h===void 0)return"";const y=c.flatMap(b=>{const k=No(b.value);return k===null?[]:[xt(b.color,b.seriesName??"",l(k))]});return Gt(gt(h.axisValue)?a(h.axisValue):"")+y.join("")}if(c.seriesType==="boxplot"){const h=Array.isArray(c.value)?c.value.slice(-5):[],y=Gt(c.name??"");if(h.length!==5||!h.every(gt))return y;const b=[...h].reverse();return y+Ao.map((k,p)=>xt(null,k,st(b[p],i))).join("")}const u=Gt(c.seriesName??"");if(c.seriesType==="custom")return u;const d=Array.isArray(c.value)?c.value:[],[m,f]=d;return!gt(m)||!gt(f)?u:u+(e?xt(c.color,a(m),q.int(f)):xt(c.color,a(m),l(f)))}}function U(n,t,e){return{axisLine:{onZero:!1,lineStyle:{color:n.ink,width:te}},axisTick:{lineStyle:{color:n.ink,width:te}},axisLabel:{color:n.muted,fontSize:t.fontSize,fontFamily:n.fontFamily},nameTextStyle:{color:n.ink,fontSize:t.fontSize,fontFamily:n.fontFamily},splitLine:{show:e,showMinLine:!1,showMaxLine:!1,lineStyle:{color:n.grid,type:"solid",width:Oo}}}}const te=1,Oo=.5;function zn(n){return{show:!0,backgroundColor:"transparent",borderColor:n.ink,borderWidth:te,z:3}}const St=.05;function Mt(n,t,e){let s=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const r of n)!Number.isFinite(r)||t&&r<=0||(r<s&&(s=r),r>i&&(i=r));if(!(s<i))return null;if(!(e>0))return[s,i];if(t){const r=Math.log10(s),a=Math.log10(i),l=(a-r)*e;return[10**(r-l),10**(a+l)]}const o=(i-s)*e;return[s-o,i+o]}function ue(n,t,e){const s=n.series.filter(c=>!t.hidden.includes(c.id));if(t.mark==="histogram"){if(e==="y")return null;const c=s.flatMap(u=>Dt(u.y,t.bins).edges);return Mt(c,t.x.scale==="log",St)}if(Rt(t.mark))return e==="x"?null:Mt(Ho(s,t),t.y.scale==="log",St);const i=s.map(c=>jt(c,t));if(i.includes("bars")||e==="y"&&t.mark==="bars")return null;const o=t.x.scale==="log",r=t.y.scale==="log";if(e==="x"){const c=[];for(const m of s){const f=t.bands&&m.low!==void 0&&m.high!==void 0;for(let h=0;h<m.y.length;h++){const y=H(m.x[h]??h,o);if(y===null)continue;(H(m.y[h],r)!==null||f&&H(m.low[h],r)!==null&&H(m.high[h],r)!==null)&&c.push(y)}}const u=Mt(c,o,i.includes("points")?St:0),d=n.xScaled;return d===void 0||o?u:u===null?[d.from,d.to]:[Math.min(u[0],d.from),Math.max(u[1],d.to)]}const a=t.x.domain,l=[];for(const c of s){const u=jt(c,t)!=="points",d=[c.y];t.bands&&c.low!==void 0&&c.high!==void 0&&d.push(c.low,c.high);for(const m of d)Io(c,m,a,u,o,r,l)}return Mt(l,r,St)}function Io(n,t,e,s,i,o,r){const a=(c,u)=>u?Math.log10(c):c;let l=null;for(let c=0;c<t.length;c++){const u=H(n.x[c]??c,i),d=H(t[c],o);if(u===null||d===null){l=null;continue}if((e===null||u>=e[0]&&u<=e[1])&&r.push(d),e!==null&&s&&l!==null)for(const m of e){if((l.x-m)*(u-m)>=0)continue;const f=(a(m,i)-a(l.x,i))/(a(u,i)-a(l.x,i)),h=a(l.y,o)+f*(a(d,o)-a(l.y,o));r.push(o?10**h:h)}l={x:u,y:d}}}function Rn(n,t){if(!(n>0)||!(t>n))return null;const e=Math.log10(n),s=Math.log10(t);if(s-e>=10){const u=Math.ceil((s-e)/6),d=[];for(let m=Math.ceil(e/u)*u;m<=s+1e-9;m+=u)d.push(10**m);return d}if(Math.floor(s+1e-9)-Math.ceil(e-1e-9)+1>=3)return null;const i=u=>u>=n*(1-1e-9)&&u<=t*(1+1e-9);for(const u of[[1,2,5],[1,2,3,4,5,6,7,8,9]]){const d=[];for(let m=Math.floor(e);m<=Math.ceil(s);m++)for(const f of u){const h=+`${f}e${m}`;i(h)&&d.push(h)}if(d.length>=3)return d}const o=(t-n)/4,r=10**Math.floor(Math.log10(o)),a=o/r,l=(a<=1?1:a<=2?2:a<=5?5:10)*r,c=[];for(let u=Math.ceil(n/l);u*l<=t*(1+1e-12);u++)c.push(Number((u*l).toPrecision(12)));return c}const Dn=640;function _n(n,t,e,s){const i=!Rt(t.mark)&&t.legend==="right"?Wn(n.series.map(a=>a.name),t,e,s):null,o=8+(i===null?16:i.room),r=t.fontSize*6;return{width:Math.max(1,(s?.width??Dn)-o-r),measure:a=>Fn(e,a,t.fontSize)}}function Fo(n){return{width:Dn,measure:t=>t.length*n.fontSize*.6}}function Ot(n,t,e,s){const i=t.mark==="histogram";if(i&&e==="y")return{bounds:{},labels:{}};const o=t[e].scale==="log",a=n.series.filter(f=>!t.hidden.includes(f.id)).flatMap(f=>i?Dt(f.y,t.bins).edges:e==="x"?f.x:f.y),l=ee(t[e].domain,ue(n,t,e),a,o),c=n.xScaled;if(e==="x"&&c!==void 0&&!o&&!i&&!Rt(t.mark)){const[f,h]=t.x.domain??[l.bounds.min,l.bounds.max];if(typeof f!="number"||typeof h!="number")return l;const y=s??Fo(t),b=So(c,[f,h],y.width,y.measure,t.fontSize);return b.length===0?l:{...l,labels:{...l.labels,showMinLabel:!0,showMaxLabel:!0},ticks:b}}if(!o)return l;const[u,d]=t[e].domain??[l.bounds.min,l.bounds.max],m=typeof u=="number"&&typeof d=="number"?Rn(u,d):null;return m===null?l:{...l,labels:Vn(l.labels,m,u,d),ticks:m}}function Vn(n,t,e,s){const i=(r,a)=>r!==void 0&&typeof a=="number"&&Math.abs(r-a)<=1e-9*Math.max(Math.abs(r),Math.abs(a)),o={...n};return i(t[0],e)||delete o.showMinLabel,i(t[t.length-1],s)||delete o.showMaxLabel,o}function Pe(n){return n===null?{start:0,end:100}:{startValue:n[0],endValue:n[1]}}function Po(n){const t=n.legend;if(t===void 0||t.show===!1||!Array.isArray(t.data)||t.selected===void 0)return n;const e=t.selected;return{...n,legend:{...t,data:t.data.filter(s=>e[String(s)]!==!1)}}}const Be=28,nt={right:8,padding:5,icon:25,iconGap:5},Bo=.35,qo=72;function zo(n,t,e){if(e(n)<=t)return[n];const s=[];let i="";for(const l of n)i+=l,".-_:/, ".includes(l)&&(s.push(i),i="");i!==""&&s.push(i);const o=[];let r="";const a=()=>{const l=r.trimEnd();l!==""&&o.push(l),r=""};for(const l of s){if(r!==""&&e(r+l)>t&&a(),e(l)<=t){r+=l;continue}for(const c of l)r!==""&&e(r+c)>t&&a(),r+=c}return a(),o}function Wn(n,t,e,s){const i=u=>Fn(e,u,t.fontSize),o=nt.right+2*nt.padding+nt.icon+nt.iconGap,r=t.fontSize,a=s===void 0?Number.POSITIVE_INFINITY:Math.max(qo,s.width*Bo-o-r),l=new Map(n.map(u=>[u,zo(u,a,i)]));let c=0;for(const u of l.values())for(const d of u)c=Math.max(c,i(d));return{room:Math.ceil(o+c+r),formatter:u=>(l.get(u)??[u]).join(`
4
+ `)}}function Ro(n,t,e,s){const i=n.series.map((f,h)=>({series:f,index:h,colour:Pn(f,h,t,e),hidden:t.hidden.includes(f.id)})),o=i.map(f=>f.series.name),r=Object.fromEntries(i.map(f=>[f.series.name,!f.hidden])),a=Rt(t.mark),l=a?"none":t.legend,c=l==="right"?Wn(o,t,e,s):null,u=t.legend==="none"?{show:!1,data:o,selected:r}:{show:!0,type:"scroll",data:o,selected:r,textStyle:{color:e.ink,fontSize:t.fontSize,fontFamily:e.fontFamily},...t.legend==="right"?{orient:"vertical",right:nt.right,top:"middle",padding:nt.padding,itemWidth:nt.icon,...c===null?{}:{formatter:c.formatter}}:t.legend==="top"?{orient:"horizontal",top:4,left:"center"}:{orient:"horizontal",bottom:4,left:"center"}},d={...zn(e),left:8,right:c===null?16:c.room,top:l==="top"?Be+8:16,bottom:l==="bottom"?Be+8:8,outerBoundsMode:"same"},m=a?Go(n,t,e,i):Do(n,t,e,i,_n(n,t,e,s));return{backgroundColor:e.background,animation:!1,textStyle:{fontFamily:e.fontFamily,fontSize:t.fontSize,color:e.ink},...t.title===null||t.title===""?{}:{title:{text:t.title,left:"center",top:4,textStyle:{color:e.ink,fontSize:t.fontSize+4,fontFamily:e.fontFamily}}},grid:{...d,top:t.title===null||t.title===""?d.top:d.top+t.fontSize+12},legend:u,tooltip:t.tooltip?{trigger:a||t.mark==="points"||t.mark==="histogram"?"item":"axis",axisPointer:{type:"cross",lineStyle:{color:e.muted,type:"solid"},crossStyle:{color:e.muted,type:"solid"}},backgroundColor:e.background,borderColor:e.grid,textStyle:{color:e.ink,fontSize:t.fontSize},formatter:Lo(n,t)}:{show:!1},...m}}function ee(n,t,e,s){const i=c=>{const u=c[1]-c[0];return{...qe(c[0],u,s)?{}:{showMinLabel:!1},...qe(c[1],u,s)?{}:{showMaxLabel:!1}}};if(n===null)return t===null?{bounds:{},labels:{}}:{bounds:{min:t[0],max:t[1]},labels:i(t)};if(t!==null)return{bounds:{min:Math.min(t[0],n[0]),max:Math.max(t[1],n[1])},labels:i(n)};let o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const c of e)!Number.isFinite(c)||s&&c<=0||(c<o&&(o=c),c>r&&(r=c));const a=o>r||n[0]<o,l=o>r||n[1]>r;return{bounds:{...a?{min:n[0]}:{},...l?{max:n[1]}:{}},labels:i(n)}}function qe(n,t,e){if(e){if(!(n>0))return!1;const i=Math.log10(n);return Math.abs(i-Math.round(i))<1e-9}if(!Number.isFinite(n)||!(t>0))return!1;const s=n/10**(Math.floor(Math.log10(t))-1);return Math.abs(s-Math.round(s))<1e-6*Math.max(1,Math.abs(s))}function Do(n,t,e,s,i){const o=t.mark==="histogram",r=[],a=Math.max(1,s.filter(y=>!y.hidden).length),l=Math.max(.07,.35/Math.sqrt(a));for(const y of s){if(o){r.push(...Wo(y,t,Math.min(1,.9/Math.sqrt(a)+.1)));continue}t.bands&&y.series.low!==void 0&&y.series.high!==void 0&&r.push(...Vo(y,t)),r.push(_o(y,t,l))}const c=t.x.label??(o?n.yLabel:n.xLabel),u=t.y.label??(o?"count":n.yLabel),d=o?void 0:Bn(n),m=o?void 0:qn(n),f=Ot(n,t,"x",i),h=Ot(n,t,"y");return{xAxis:{type:t.x.scale==="log"?"log":"value",name:c,nameLocation:"middle",nameGap:t.fontSize*2.4,scale:!0,...n.xTicks!==void 0&&!o?{minInterval:1}:{},...o?{containShape:!1}:{},...f.bounds,...U(e,t,t.x.grid),...f.ticks===void 0?{}:{axisTick:{...U(e,t,t.x.grid).axisTick,customValues:f.ticks}},axisLabel:{...U(e,t,t.x.grid).axisLabel,...f.ticks===void 0?{}:{customValues:f.ticks},...o?{}:{hideOverlap:!0},...f.labels,formatter:d??(y=>st(y,t.x.scale==="log"?"log":"linear"))},axisPointer:{label:{formatter:ze(d,t.x.scale)}}},yAxis:{type:t.y.scale==="log"?"log":"value",name:u,nameLocation:"middle",nameGap:t.fontSize*4,scale:t.mark!=="histogram"&&t.mark!=="bars",...h.bounds,...U(e,t,t.y.grid),...h.ticks===void 0?{}:{axisTick:{...U(e,t,t.y.grid).axisTick,customValues:h.ticks}},axisLabel:{...U(e,t,t.y.grid).axisLabel,...h.ticks===void 0?{}:{customValues:h.ticks},...o?{}:{hideOverlap:!0},...h.labels,formatter:m??(y=>st(y,t.y.scale==="log"?"log":"linear"))},axisPointer:{label:{formatter:ze(m,t.y.scale)}}},dataZoom:[{id:de,type:"inside",xAxisIndex:0,zoomOnMouseWheel:!0,moveOnMouseMove:!0,filterMode:"none",...Pe(t.x.domain)},{id:he,type:"inside",yAxisIndex:0,zoomOnMouseWheel:"shift",moveOnMouseMove:!1,filterMode:"none",...Pe(t.y.domain)}],series:r}}const de="zoom-x",he="zoom-y";function ze(n,t){return({value:e})=>{if(typeof e!="number"||!Number.isFinite(e))return"";const s=n?.(e)??"";return s!==""?s:st(e,t==="log"?"log":"linear")}}function _o(n,t,e){const s=jt(n.series,t),i=Co(n.series,t),o={id:n.series.id,name:n.series.name,data:i,color:n.colour,emphasis:{focus:"series"}};if(s==="points")return{...o,type:"scatter",symbolSize:t.pointSize,itemStyle:{color:n.colour,opacity:.85}};if(s==="bars")return{...o,type:"bar",itemStyle:{color:n.colour},barMaxWidth:24,...n.series.stack===void 0?{}:{stack:n.series.stack}};const r=s==="area"||t.fillArea;return{...o,type:"line",step:s==="step"?"middle":!1,smooth:t.smooth,symbol:"none",lineStyle:{width:t.lineWidth,color:n.colour},...r?{areaStyle:{color:n.colour,opacity:e,origin:"auto"}}:{},connectNulls:!1,sampling:"lttb"}}function Vo(n,t){const e=n.series.low,s=n.series.high,i=t.y.scale==="log",o=t.x.scale==="log",r=[],a=[];for(let u=0;u<e.length;u++){const d=H(n.series.x[u]??u,o),m=H(e[u],i),f=H(s[u],i);if(d===null||m===null||f===null){r.push(null),a.push(null);continue}r.push([d,m]),a.push([d,f-m])}const l=`band-${n.series.id}`,c={type:"line",stack:l,stackStrategy:"all",symbol:"none",silent:!0,legendHoverLink:!1,lineStyle:{opacity:0},tooltip:{show:!1}};return[{...c,id:`${l}-low`,name:`${n.series.name} ${l}-low`,data:r},{...c,id:`${l}-high`,name:`${n.series.name} ${l}-high`,data:a,areaStyle:{color:n.colour,opacity:.18}}]}function Wo(n,t,e){const{edges:s,counts:i}=Dt(n.series.y,t.bins);if(i.length===0)return[];const o=i.map((r,a)=>[(s[a]+s[a+1])/2,r]);return[{id:n.series.id,name:n.series.name,type:"bar",data:o,color:n.colour,barGap:"-100%",barCategoryGap:"1%",itemStyle:{color:n.colour,opacity:e}}]}function Go(n,t,e,s){const i=s.filter(d=>!d.hidden),o=i.map(d=>d.series.name),r=t.y.label??n.yLabel,a=t.mark==="box"?Gn(i,t,e):Ko(i,t,e);t.jitter&&a.push({id:"points",name:"points",type:"scatter",symbolSize:Math.max(2,t.pointSize/2),itemStyle:{color:e.muted,opacity:.4},silent:!0,data:i.flatMap((d,m)=>wt(d.series.y).map(f=>[m,f]))});const l=t.y.scale==="log",c=t.y.domain??ue(n,t,"y"),u=l&&c!==null?Rn(c[0],c[1]):null;return{legend:{show:!1},xAxis:{type:"category",data:o,...U(e,t,!1),axisTick:{show:!1}},yAxis:{type:t.y.scale==="log"?"log":"value",name:r,nameLocation:"middle",nameGap:t.fontSize*4,scale:!0,...c===null?{}:{min:c[0],max:c[1]},...U(e,t,t.y.grid),...u===null?{}:{axisTick:{...U(e,t,t.y.grid).axisTick,customValues:u}},axisLabel:{...U(e,t,t.y.grid).axisLabel,...c===null?{}:u===null?ee(c,null,[],l).labels:Vn(ee(c,null,[],l).labels,u,c[0],c[1]),...u===null?{}:{customValues:u},formatter:d=>st(d,l?"log":"linear")}},series:a}}function Ho(n,t){const e=t.mark==="violin"?n.map(o=>Hn(o.y,t.y.scale==="log")):[],s=e.some(o=>o.y.some(r=>r>0)),i=[];return n.forEach((o,r)=>{if(s)for(const a of e[r].at)i.push(a);else{const a=In(o.y);i.push(a.low,a.high,...a.outliers)}if(t.jitter)for(const a of o.y)i.push(a)}),i}function Gn(n,t,e){const s=n.map(i=>In(i.series.y));return[{id:"box",name:"box",type:"boxplot",data:s.map((i,o)=>({value:[i.low,i.q1,i.median,i.q3,i.high],itemStyle:{color:n[o].colour,borderColor:e.ink,opacity:.55}})),boxWidth:[10,48]},{id:"outliers",name:"outliers",type:"scatter",symbolSize:Math.max(3,t.pointSize/1.5),itemStyle:{color:e.muted},silent:!0,data:s.flatMap((i,o)=>i.outliers.map(r=>[o,r]))}]}function Ko(n,t,e){const s=t.y.scale==="log",i=n.map(r=>Hn(r.series.y,s)),o=Math.max(0,...i.flatMap(r=>r.y));return o>0?n.map((r,a)=>({id:`violin-${r.series.id}`,name:r.series.name,type:"custom",color:r.colour,itemStyle:{color:r.colour},data:i[a].at.map(l=>[a,l]),clip:!0,renderItem:(l,c)=>{if(l.dataIndex!==0)return{type:"group",children:[]};const u=i[a];if(u.at.length===0)return{type:"group",children:[]};const d=c.size?.([1,0])??[24,0],m=Math.min(48,d[0]*.42),f=[];for(let h=0;h<u.at.length;h++){const[y,b]=c.coord([a,u.at[h]]);f.push([y-u.y[h]/o*m,b])}for(let h=u.at.length-1;h>=0;h--){const[y,b]=c.coord([a,u.at[h]]);f.push([y+u.y[h]/o*m,b])}return{type:"polygon",shape:{points:f},style:{fill:r.colour,opacity:.55,stroke:e.ink,lineWidth:t.lineWidth/2}}},encode:{x:0,y:1}})):Gn(n,t,e)}function Hn(n,t){if(!t)return Fe(n);const e=wt(n).filter(i=>i>0).map(i=>Math.log10(i)),s=Fe(e);return{at:s.at.map(i=>10**i),y:s.y}}const Yo=2e4;function It(n){const t=n.nrows*n.ncols;return t>0&&t<=Yo&&n.large!==!0&&n.aspect!=="fill"}const Re=32;function Uo(n){const t=Ls(n)?n:Ns,e=[];for(let s=0;s<Re;s++)e.push(As(t,s/(Re-1)));return e}function Zo(n,t){let e=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const o of n.values)Number.isFinite(o)&&(o<e&&(e=o),o>s&&(s=o));const i=t??{vmin:null,vmax:null};if(i.vmin!==null||i.vmax!==null){const o=i.vmin??(Number.isFinite(e)?e:0),r=i.vmax??(Number.isFinite(s)?s:1);if(o<r)return{vmin:o,vmax:r}}if(n.range!==void 0&&n.range[1]>n.range[0])return{vmin:n.range[0],vmax:n.range[1]};if(!(e<=s))return null;if(n.centre!==void 0){const o=n.centre,r=Math.max(Math.abs(s-o),Math.abs(e-o))||1;return{vmin:o-r,vmax:o+r}}return{vmin:e,vmax:s>e?s:e+1}}function Ft(n,t,e){const s=new Array(Math.max(0,t)).fill("");if(n.length===0||t<=0)return s;if(e!==void 0&&e.length===n.length)return n.forEach((i,o)=>{const r=Math.min(t-1,Math.max(0,Math.floor(e[o]*t)));s[r]===""&&(s[r]=i)}),s;if(n.length===t){for(let i=0;i<t;i++)s[i]=n[i]??"";return s}return n.length===1?(s[Math.floor((t-1)/2)]=n[0],s):(n.forEach((i,o)=>{const r=Math.round(o*(t-1)/(n.length-1));(s[r]===""||o===n.length-1)&&(s[r]=i)}),s)}function Xo(n){const t=[];for(let e=0;e<n.nrows;e++)for(let s=0;s<n.ncols;s++){const i=n.values[e*n.ncols+s];Number.isFinite(i)&&t.push([s,n.nrows-1-e,i])}return t}function Jo(n){const t=new Map;for(const e of[...n?.top??[],...n?.right??[]]){const s=t.get(e.name)??{lo:Number.POSITIVE_INFINITY,hi:Number.NEGATIVE_INFINITY};for(const i of e.values)Number.isFinite(i)&&(i<s.lo&&(s.lo=i),i>s.hi&&(s.hi=i));t.set(e.name,s)}return t}function De(n,t,e,s,i,o,r){return n.map((a,l)=>{const c=Math.max(0,o.indexOf(a.name)),u=t.series[c%t.series.length],d=r.get(a.name),m=d===void 0?0:d.hi-d.lo,f=[];for(const[h,y]of a.values.entries()){if(!Number.isFinite(y))continue;const b=m>0&&d!==void 0?(y-d.lo)/m:0,k=i?a.values.length-1-h:h;f.push(i?[b,k]:[k,b])}return{type:"line",name:a.name,id:`margin-${i?"right":"top"}-${l}`,xAxisIndex:s,yAxisIndex:s,data:f,showSymbol:!1,lineStyle:{color:u,width:Math.max(1,e.lineWidth*.8)},itemStyle:{color:u},areaStyle:{color:u,opacity:.18},silent:!0,tooltip:{show:!1},z:3}})}function _e(n,t,e){const s={type:"value",gridIndex:n,min:-.5,max:t-.5,show:!1},i={type:"value",gridIndex:n,min:0,max:1,show:!1};return e?[i,s]:[s,i]}function Qo(n,t,e,s){const i=Zo(n,t),o=t.fontSize,r=(n.margins?.top??[]).filter(T=>T.values.length>0),a=(n.margins?.right??[]).filter(T=>T.values.length>0),l=o*3.5,c=o*.8,u=[...new Set([...r,...a].map(T=>T.name))],d=Jo(n.margins),m=t.title!==null&&t.title!=="",f=u.length>0?o*1.8:0,h=(m?o+14:4)+f+(r.length>0?l+c:0),b=o*5.5+(a.length>0?l+c:0),k=n.stats??[],p=(n.xLabel===""?0:o*1.6)+(k.length>0?o*1.8:0),w={left:n.yLabel===""?o*3.5:o*5,right:b,top:h,bottom:o*2.6+p},M=Math.max(1,s.width-w.left-w.right),v=Math.max(1,s.height-w.top-w.bottom),x=Math.max(1,n.ncols),E=Math.max(1,n.nrows),S=n.aspect==="fill"?{width:M/x,height:v/E}:(()=>{const T=Math.min(M/x,v/E);return{width:T,height:T}})(),$={left:w.left+(M-S.width*x)/2,top:w.top+(v-S.height*E)/2,width:S.width*x,height:S.height*E,containLabel:!1,...zn(e)},C=[$],A=[],O=[],I=[],F=(T,B)=>({axisLine:{lineStyle:{color:e.ink}},axisTick:{lineStyle:{color:e.ink}},axisLabel:{color:e.muted,fontSize:o,fontFamily:e.fontFamily,...T.length>0&&T.length!==B?{interval:0}:{}},nameTextStyle:{color:e.ink,fontSize:o,fontFamily:e.fontFamily},splitLine:{show:!1},splitArea:{show:!1}});if(A.push({type:"category",gridIndex:0,data:Ft(n.xTicks,n.ncols,n.xTickAt),name:n.xLabel,nameLocation:"middle",nameGap:o*2.2,...F(n.xTicks,n.ncols)}),O.push({type:"category",gridIndex:0,data:[...Ft(n.yTicks,n.nrows)].reverse(),name:n.yLabel,nameLocation:"middle",nameGap:o*3.4,...F(n.yTicks,n.nrows)}),I.push({type:"heatmap",id:"matrix",name:n.label,data:Xo(n),xAxisIndex:0,yAxisIndex:0,itemStyle:{borderWidth:0},emphasis:{itemStyle:{borderColor:e.ink,borderWidth:1}},progressive:0}),r.length>0){C.push({left:$.left,width:$.width,top:$.top-l-c,height:l});const T=C.length-1,[B,at]=_e(T,n.ncols,!1);A.push(B),O.push(at),I.push(...De(r,e,t,T,!1,u,d))}if(a.length>0){C.push({left:$.left+$.width+c,width:l,top:$.top,height:$.height});const T=C.length-1,[B,at]=_e(T,n.nrows,!0);A.push(B),O.push(at),I.push(...De(a,e,t,T,!0,u,d))}const _=$.left+$.width+c+(a.length>0?l+c:0),V=Math.max(o*6,$.height-o*2),R=[0,...r.length>0?[1]:[]],D=[0,...a.length>0?[C.length-1]:[]],et=(T,B)=>T===null?{start:0,end:100}:{startValue:Math.max(0,Math.round(T[0])),endValue:Math.min(B-1,Math.round(T[1]))},K=k.map(T=>`${T.label} ${T.value.toFixed(T.digits??2)}`).join(" · ");return{backgroundColor:e.background,animation:!1,textStyle:{fontFamily:e.fontFamily,fontSize:o,color:e.ink},...m||K!==""?{title:[...m?[{text:t.title,left:"center",top:4,textStyle:{color:e.ink,fontSize:o+4,fontFamily:e.fontFamily}}]:[],...K===""?[]:[{text:K,left:"center",bottom:2,textStyle:{color:e.muted,fontSize:o,fontFamily:e.fontFamily}}]]}:{},grid:C,xAxis:A,yAxis:O,...u.length===0?{}:{legend:{data:u.map(T=>({name:T,icon:"roundRect"})),left:o*.5,top:m?o+10:2,selectedMode:!1,itemWidth:Math.round(o*.9),itemHeight:Math.max(2,Math.round(o*.22)),itemGap:Math.round(o),textStyle:{color:e.muted,fontSize:o,fontFamily:e.fontFamily},formatter:T=>{const B=d.get(T);return B===void 0||!(B.lo<=B.hi)?T:`${T} ${At(B.lo)}–${At(B.hi)}`}}},...i===null?{}:{visualMap:{type:"continuous",min:i.vmin,max:i.vmax,calculable:!0,realtime:!0,orient:"vertical",left:_,top:$.top+($.height-V)/2,itemWidth:Math.round(o*.9),itemHeight:Math.round(V),formatter:T=>At(T),inRange:{color:Uo(t.colormap??n.colormap)},textStyle:{color:e.muted,fontSize:o,fontFamily:e.fontFamily},seriesIndex:0}},dataZoom:[{id:de,type:"inside",xAxisIndex:R,zoomOnMouseWheel:!0,moveOnMouseMove:!0,filterMode:"none",...et(t.x.domain,n.ncols)},{id:he,type:"inside",yAxisIndex:D,zoomOnMouseWheel:"shift",moveOnMouseMove:!1,filterMode:"none",...et(t.y.domain,n.nrows)}],tooltip:t.tooltip?{trigger:"item",backgroundColor:e.background,borderColor:e.grid,textStyle:{color:e.ink,fontSize:o},formatter:jo(n)}:{show:!1},series:I}}function jo(n){const t=Ft(n.xTicks,n.ncols,n.xTickAt),e=Ft(n.yTicks,n.nrows);return s=>{const i=s.value;if(!Array.isArray(i)||i.length<3)return"";const[o,r,a]=i,l=n.nrows-1-r,c=t[o]!==""?t[o]:`column ${o+1}`,u=e[l]!==""?e[l]:`row ${l+1}`,d=Math.abs(a)>=.001&&Math.abs(a)<1e6?a.toFixed(3):a.toExponential(2);return`${ot(u)} · ${ot(c)}<br/><b>${ot(d)}</b>`}}const tr={fill:"#000000",fillGradient:null,stroke:null,strokeWidth:1,opacity:1,fillOpacity:1,strokeOpacity:1,lineCap:"butt",lineJoin:"miter",dash:[],fontSize:12,fontFamily:"sans-serif",fontWeight:"normal",fontStyle:"normal",anchor:"left",baseline:"alphabetic",strokeFirst:!1};function P(n,t,e){const s=t.get(e);if(s!==void 0&&s!=="")return s;const i=n.getAttribute(e);return i===null||i===""?null:i}function _t(n){const t=new Map,e=n.getAttribute("style");if(e===null)return t;for(const s of e.split(";")){const i=s.indexOf(":");i<0||t.set(s.slice(0,i).trim().toLowerCase(),s.slice(i+1).trim())}return t}function L(n,t){if(n===null)return t;const e=Number.parseFloat(n);return Number.isFinite(e)?e:t}function er(n,t){return n==="middle"?"center":n==="end"?"right":n==="start"?"left":t}function nr(n,t){switch(n){case"central":case"middle":return"middle";case"hanging":case"text-before-edge":return"top";case"text-after-edge":case"ideographic":return"bottom";case"alphabetic":case"auto":return"alphabetic";default:return t}}function sr(n){if(n===null||n==="none")return null;const t=n.split(/[\s,]+/).filter(e=>e!=="").map(e=>Number.parseFloat(e));return t.length===0||t.some(e=>!Number.isFinite(e)||e<0)?[]:t}function Kn(n,t,e){const s=_t(n),i={...t},o=P(n,s,"fill");o!==null&&(i.fill=Ve(o,t.fill,e),i.fillGradient=ir(o,t.fillGradient,e));const r=P(n,s,"stroke");r!==null&&(i.stroke=Ve(r,t.stroke,e));const a=P(n,s,"stroke-width");a!==null&&(i.strokeWidth=L(a,t.strokeWidth));const l=P(n,s,"opacity");l!==null&&(i.opacity=t.opacity*dt(L(l,1)));const c=P(n,s,"fill-opacity");c!==null&&(i.fillOpacity=dt(L(c,1)));const u=P(n,s,"stroke-opacity");u!==null&&(i.strokeOpacity=dt(L(u,1)));const d=P(n,s,"stroke-linecap");(d==="round"||d==="square"||d==="butt")&&(i.lineCap=d);const m=P(n,s,"stroke-linejoin");(m==="round"||m==="bevel"||m==="miter")&&(i.lineJoin=m);const f=sr(P(n,s,"stroke-dasharray"));f!==null&&(i.dash=f);const h=P(n,s,"font-size");h!==null&&(i.fontSize=L(h,t.fontSize));const y=P(n,s,"font-family");y!==null&&(i.fontFamily=y);const b=P(n,s,"font-weight");b!==null&&(i.fontWeight=b);const k=P(n,s,"font-style");k!==null&&(i.fontStyle=k),i.anchor=er(P(n,s,"text-anchor"),t.anchor),i.baseline=nr(P(n,s,"dominant-baseline")??P(n,s,"alignment-baseline"),t.baseline);const p=P(n,s,"paint-order");return p!==null&&(i.strokeFirst=p.trim().split(/\s+/)[0]==="stroke"),i}function dt(n){return n<0?0:n>1?1:n}function Yn(n){return/^url\(\s*['"]?#([^)'"]+)['"]?\s*\)$/.exec(n.trim())?.[1]??null}function Ve(n,t,e){const s=n.trim();if(s==="none"||s==="transparent")return null;if(s==="currentColor"||s==="inherit")return t;const i=Yn(s);return i!==null?e.get(i)?.flat??null:s}function ir(n,t,e){const s=n.trim();if(s==="inherit")return t;const i=Yn(s);return i===null?null:e.get(i)?.linear??null}function or(n){const t=new Map,e=n.querySelectorAll("linearGradient, radialGradient");for(const s of Array.from(e)){const i=s.getAttribute("id");if(i===null)continue;const o=Array.from(s.querySelectorAll("stop"));if(o.length===0)continue;const r=o[Math.floor((o.length-1)/2)],a=P(r,_t(r),"stop-color")??"#000000";t.set(i,{flat:a,linear:s.tagName.toLowerCase()==="lineargradient"?rr(s,o):null})}return t}function rr(n,t){const e=(i,o)=>{if(i===null||i.trim()==="")return o;const r=Number.parseFloat(i);return Number.isFinite(r)?i.trim().endsWith("%")?r/100:r:o};let s=0;return{units:n.getAttribute("gradientUnits")==="userSpaceOnUse"?"userSpaceOnUse":"objectBoundingBox",x1:e(n.getAttribute("x1"),0),y1:e(n.getAttribute("y1"),0),x2:e(n.getAttribute("x2"),1),y2:e(n.getAttribute("y2"),0),stops:t.map(i=>{const o=_t(i);return s=Math.max(s,dt(e(i.getAttribute("offset"),0))),{offset:s,rgb:Os(P(i,o,"stop-color")??"#000000"),opacity:dt(L(P(i,o,"stop-opacity"),1))}})}}function ar(n){let t=[1,0,0,1,0,0];const e=/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g;let s;for(;(s=e.exec(n))!==null;){const i=s[2].split(/[\s,]+/).filter(o=>o!=="").map(o=>Number.parseFloat(o)).map(o=>Number.isFinite(o)?o:0);t=ne(t,lr(s[1],i))}return t}function lr(n,t){switch(n){case"matrix":return[t[0]??1,t[1]??0,t[2]??0,t[3]??1,t[4]??0,t[5]??0];case"translate":return[1,0,0,1,t[0]??0,t[1]??0];case"scale":{const e=t[0]??1;return[e,0,0,t[1]??e,0,0]}case"rotate":{const e=(t[0]??0)*Math.PI/180,s=Math.cos(e),i=Math.sin(e),o=[s,i,-i,s,0,0];if(t.length<3)return o;const r=t[1],a=t[2];return ne(ne([1,0,0,1,r,a],o),[1,0,0,1,-r,-a])}case"skewX":return[1,0,Math.tan((t[0]??0)*Math.PI/180),1,0,0];case"skewY":return[1,Math.tan((t[0]??0)*Math.PI/180),0,1,0,0];default:return[1,0,0,1,0,0]}}function ne(n,t){return[n[0]*t[0]+n[2]*t[1],n[1]*t[0]+n[3]*t[1],n[0]*t[2]+n[2]*t[3],n[1]*t[2]+n[3]*t[3],n[0]*t[4]+n[2]*t[5]+n[4],n[1]*t[4]+n[3]*t[5]+n[5]]}const cr=[1,0,0,1,0,0];function se(n){return n[0]===1&&n[1]===0&&n[2]===0&&n[3]===1&&n[4]===0&&n[5]===0}function ur(n,t){let e=0;const s=()=>{for(;e<t.length&&(t[e]===" "||t[e]===","||t[e]===`
5
+ `||t[e]===" "||t[e]==="\r");)e+=1},i=()=>{s();const p=e;for((t[e]==="+"||t[e]==="-")&&(e+=1);e<t.length&&t[e]>="0"&&t[e]<="9";)e+=1;if(t[e]===".")for(e+=1;e<t.length&&t[e]>="0"&&t[e]<="9";)e+=1;if(t[e]==="e"||t[e]==="E")for(e+=1,(t[e]==="+"||t[e]==="-")&&(e+=1);e<t.length&&t[e]>="0"&&t[e]<="9";)e+=1;const w=Number.parseFloat(t.slice(p,e));return Number.isFinite(w)?w:Number.NaN},o=()=>{s();const p=t[e];return p==="0"||p==="1"?(e+=1,p==="1"?1:0):Number.NaN},r=()=>{s();const p=t[e];return p!==void 0&&(p==="+"||p==="-"||p==="."||p>="0"&&p<="9")};let a=0,l=0,c=0,u=0,d=null,m=null,f=!1;const h=(p,w)=>{n.moveTo(p,w),a=p,l=w,c=p,u=w,f=!0},y=(p,w)=>{f?(n.lineTo(p,w),a=p,l=w):h(p,w)},b=(p,w,M,v,x,E)=>{f||h(a,l),n.bezierCurveTo(p,w,M,v,x,E),a=x,l=E};let k="";for(s();e<t.length;){const p=t[e];if(/[MmLlHhVvCcSsQqTtAaZz]/.test(p))k=p,e+=1;else{if(k==="")return;k==="M"?k="L":k==="m"&&(k="l")}const w=k===k.toLowerCase(),M=w?a:0,v=w?l:0;switch(k.toUpperCase()){case"Z":{n.closePath(),a=c,l=u,d=null,m=null,k="",s();continue}case"M":{h(M+i(),v+i()),d=null,m=null;break}case"L":{y(M+i(),v+i()),d=null,m=null;break}case"H":{y(M+i(),l),d=null,m=null;break}case"V":{y(a,v+i()),d=null,m=null;break}case"C":{const x=M+i(),E=v+i(),S=M+i(),$=v+i(),C=M+i(),A=v+i();b(x,E,S,$,C,A),d={x:S,y:$},m=null;break}case"S":{const x=d===null?a:2*a-d.x,E=d===null?l:2*l-d.y,S=M+i(),$=v+i(),C=M+i(),A=v+i();b(x,E,S,$,C,A),d={x:S,y:$},m=null;break}case"Q":{const x=M+i(),E=v+i(),S=M+i(),$=v+i();f||h(a,l),n.quadraticCurveTo(x,E,S,$),a=S,l=$,m={x,y:E},d=null;break}case"T":{const x=m===null?a:2*a-m.x,E=m===null?l:2*l-m.y,S=M+i(),$=v+i();f||h(a,l),n.quadraticCurveTo(x,E,S,$),a=S,l=$,m={x,y:E},d=null;break}case"A":{const x=i(),E=i(),S=i(),$=o(),C=o(),A=M+i(),O=v+i();if(Number.isNaN($)||Number.isNaN(C)||Number.isNaN(A)||Number.isNaN(O))return;f||h(a,l);for(const I of ie(a,l,x,E,S,$===1,C===1,A,O))n.bezierCurveTo(I[0],I[1],I[2],I[3],I[4],I[5]);a=A,l=O,d=null,m=null;break}default:return}if(Number.isNaN(a)||Number.isNaN(l)||(s(),!r()&&e<t.length&&!/[MmLlHhVvCcSsQqTtAaZz]/.test(t[e])))return}}function ie(n,t,e,s,i,o,r,a,l){let c=Math.abs(e),u=Math.abs(s);if(c===0||u===0)return[[n,t,a,l,a,l]];const d=i*Math.PI/180,m=Math.cos(d),f=Math.sin(d),h=(n-a)/2,y=(t-l)/2,b=m*h+f*y,k=-f*h+m*y,p=b*b/(c*c)+k*k/(u*u);if(p>1){const T=Math.sqrt(p);c*=T,u*=T}const w=o===r?-1:1,M=c*c*u*u-c*c*k*k-u*u*b*b,v=c*c*k*k+u*u*b*b,x=v===0?0:w*Math.sqrt(Math.max(0,M/v)),E=x*c*k/u,S=-x*u*b/c,$=m*E-f*S+(n+a)/2,C=f*E+m*S+(t+l)/2,A=(T,B)=>Math.atan2(B,T),O=A((b-E)/c,(k-S)/u);let F=A((-b-E)/c,(-k-S)/u)-O;!r&&F>0&&(F-=2*Math.PI),r&&F<0&&(F+=2*Math.PI);const _=Math.max(1,Math.ceil(Math.abs(F)/(Math.PI/2))),V=F/_,R=4/3*Math.tan(V/4),D=[],et=T=>[$+c*Math.cos(T)*m-u*Math.sin(T)*f,C+c*Math.cos(T)*f+u*Math.sin(T)*m],K=T=>[-c*Math.sin(T)*m-u*Math.cos(T)*f,-c*Math.sin(T)*f+u*Math.cos(T)*m];for(let T=0;T<_;T++){const B=O+T*V,at=B+V,[hs,fs]=et(B),[me,pe]=et(at),[ms,ps]=K(B),[gs,bs]=K(at);D.push([hs+R*ms,fs+R*ps,me-R*gs,pe-R*bs,me,pe])}return D}function dr(n,t,e){const i=new DOMParser().parseFromString(n,"image/svg+xml").documentElement;i===null||i.nodeName==="parsererror"||hr(i,t,e)}function hr(n,t,e){const s=fr(n),i=or(n),o=mr(n);if(t.save(),e!==void 0&&s!==null&&s.width>0&&s.height>0){const r=e.width/s.width,a=e.height/s.height;(r!==1||a!==1)&&t.transform(r,0,0,a,0,0)}s!==null&&(s.x!==0||s.y!==0)&&t.transform(1,0,0,1,-s.x,-s.y),Un(n,t,tr,i,o),t.restore()}function fr(n){const t=n.getAttribute("viewBox");if(t!==null){const i=t.split(/[\s,]+/).filter(o=>o!=="").map(o=>Number.parseFloat(o));if(i.length===4&&i.every(o=>Number.isFinite(o)))return{x:i[0],y:i[1],width:i[2],height:i[3]}}const e=L(n.getAttribute("width"),Number.NaN),s=L(n.getAttribute("height"),Number.NaN);return!Number.isFinite(e)||!Number.isFinite(s)?null:{x:0,y:0,width:e,height:s}}function mr(n){const t=new Map;for(const e of Array.from(n.querySelectorAll("clipPath"))){const s=e.getAttribute("id");s!==null&&t.set(s,e)}return t}const pr=new Set(["defs","style","clippath","lineargradient","radialgradient","title","desc","metadata","filter","mask","pattern","marker","symbol"]);function Un(n,t,e,s,i){for(const o of Array.from(n.children)){const r=o.tagName.toLowerCase();if(pr.has(r))continue;const a=Kn(o,e,s),l=Zn(o),c=Xn(o,i),u=!se(l)||c!==null;u&&t.save(),se(l)||t.transform(...l),c!==null&&Jn(t,c,i),r==="g"||r==="a"||r==="svg"?Un(o,t,a,s,i):br(o,r,t,a),u&&t.restore()}}function Zn(n){const t=n.getAttribute("transform");return t===null||t===""?cr:ar(t)}function Xn(n,t){const e=n.getAttribute("clip-path")??_t(n).get("clip-path")??null;if(e===null)return null;const s=/^url\(\s*['"]?#([^)'"]+)['"]?\s*\)$/.exec(e.trim());return s===null?null:t.get(s[1])??null}function Jn(n,t,e){n.beginPath();let s=!1;for(const o of Array.from(t.children)){const r=Zn(o);se(r)&&vt(o,o.tagName.toLowerCase(),n)&&(s=!0)}const i=Xn(t,e);i!==null&&Jn(n,i,e),s&&n.clip()}function vt(n,t,e){switch(t){case"path":{const s=n.getAttribute("d");return s===null||s===""?!1:(ur(e,s),!0)}case"rect":{const s=L(n.getAttribute("x"),0),i=L(n.getAttribute("y"),0),o=L(n.getAttribute("width"),0),r=L(n.getAttribute("height"),0);if(!(o>0)||!(r>0))return!1;const a=Math.min(L(n.getAttribute("rx"),0),o/2),l=Math.min(L(n.getAttribute("ry"),a),r/2);return a>0&&l>0?gr(e,s,i,o,r,a,l):e.rect(s,i,o,r),!0}case"circle":{const s=L(n.getAttribute("r"),0);return s>0?(e.moveTo(L(n.getAttribute("cx"),0)+s,L(n.getAttribute("cy"),0)),e.arc(L(n.getAttribute("cx"),0),L(n.getAttribute("cy"),0),s,0,Math.PI*2),!0):!1}case"ellipse":{const s=L(n.getAttribute("rx"),0),i=L(n.getAttribute("ry"),0);if(!(s>0)||!(i>0))return!1;const o=L(n.getAttribute("cx"),0),r=L(n.getAttribute("cy"),0);e.moveTo(o+s,r);for(const a of ie(o+s,r,s,i,0,!0,!0,o-s,r))e.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5]);for(const a of ie(o-s,r,s,i,0,!0,!0,o+s,r))e.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5]);return e.closePath(),!0}case"line":return e.moveTo(L(n.getAttribute("x1"),0),L(n.getAttribute("y1"),0)),e.lineTo(L(n.getAttribute("x2"),0),L(n.getAttribute("y2"),0)),!0;case"polyline":case"polygon":{const s=(n.getAttribute("points")??"").split(/[\s,]+/).filter(i=>i!=="").map(i=>Number.parseFloat(i));if(s.length<4)return!1;e.moveTo(s[0],s[1]);for(let i=2;i+1<s.length;i+=2)e.lineTo(s[i],s[i+1]);return t==="polygon"&&e.closePath(),!0}default:return!1}}function gr(n,t,e,s,i,o,r){n.moveTo(t+o,e),n.lineTo(t+s-o,e),n.quadraticCurveTo(t+s,e,t+s,e+r),n.lineTo(t+s,e+i-r),n.quadraticCurveTo(t+s,e+i,t+s-o,e+i),n.lineTo(t+o,e+i),n.quadraticCurveTo(t,e+i,t,e+i-r),n.lineTo(t,e+r),n.quadraticCurveTo(t,e,t+o,e),n.closePath()}function br(n,t,e,s){if(t==="text"||t==="tspan"){Qn(n,e,s);return}if(t==="image"||t==="use"||t==="foreignobject"||(e.beginPath(),!vt(n,t,e)))return;const i=s.fill===null?null:s.fillGradient;if(i===null){We(e,s);return}const o=()=>vr(n,t,e,s,i),r=()=>{e.beginPath(),vt(n,t,e),We(e,{...s,fill:null})};s.strokeFirst?(r(),o()):(o(),r())}const yr=100;function vr(n,t,e,s,i){const o=wr(n,t);if(o===null||i.stops.length===0)return;const r=i.units==="objectBoundingBox",a=(k,p)=>r?[o.x+k*o.width,o.y+p*o.height]:[k,p],l=r?[[0,0],[1,0],[1,1],[0,1]]:[[o.x,o.y],[o.x+o.width,o.y],[o.x+o.width,o.y+o.height],[o.x,o.y+o.height]],c=i.x2-i.x1,u=i.y2-i.y1,d=c*c+u*u,m=i.stops,f=m[0],h=m[m.length-1],y=s.opacity*s.fillOpacity,b=(k,p,w,M)=>{const v=F=>[i.x1+c*F,i.y1+u*F],x=-u/Math.sqrt(d),E=c/Math.sqrt(d);let S=0;for(const[F,_]of l)S=Math.max(S,Math.abs((F-i.x1)*x+(_-i.y1)*E));S+=1;const[$,C]=v(k),[A,O]=v(p),I=[a($+x*S,C+E*S),a(A+x*S,O+E*S),a(A-x*S,O-E*S),a($-x*S,C-E*S)];e.globalAlpha=y*M,e.fillStyle=`rgb(${w.map(F=>Math.round(dt(F)*255)).join(", ")})`,e.beginPath(),e.moveTo(I[0][0],I[0][1]);for(const[F,_]of I.slice(1))e.lineTo(F,_);e.closePath(),e.fill()};if(e.save(),e.beginPath(),vt(n,t,e),e.clip(),!(d>0))b(-1,1,h.rgb,h.opacity);else{let k=0,p=1;for(const[v,x]of l){const E=((v-i.x1)*c+(x-i.y1)*u)/d;k=Math.min(k,E),p=Math.max(p,E)}const w=[],M=v=>{const x=w[w.length-1];x!==void 0&&x.opacity===v.opacity&&x.rgb.every((S,$)=>S===v.rgb[$])?x.to=v.to:w.push(v)};k<f.offset&&M({from:k-.01,to:f.offset,rgb:f.rgb,opacity:f.opacity});for(let v=0;v+1<m.length;v++){const x=m[v],E=m[v+1],S=E.offset-x.offset;if(!(S>0))continue;const C=x.opacity===E.opacity&&x.rgb.every((A,O)=>A===E.rgb[O])?1:Math.max(1,Math.round(S*yr));for(let A=0;A<C;A++){const O=(A+.5)/C;M({from:x.offset+S*A/C,to:x.offset+S*(A+1)/C,rgb:[0,1,2].map(I=>x.rgb[I]+(E.rgb[I]-x.rgb[I])*O),opacity:x.opacity+(E.opacity-x.opacity)*O})}}p>h.offset&&M({from:h.offset,to:p+.01,rgb:h.rgb,opacity:h.opacity}),w.forEach((v,x)=>{const E=y*v.opacity>=1&&x+1<w.length;b(v.from,E?v.to+(v.to-v.from)/2:v.to,v.rgb,v.opacity)})}e.restore(),e.globalAlpha=1}function wr(n,t){let e=1/0,s=1/0,i=-1/0,o=-1/0;const r=(c,u)=>{e=Math.min(e,c),s=Math.min(s,u),i=Math.max(i,c),o=Math.max(o,u)},a=()=>{};return!vt(n,t,{beginPath:a,closePath:a,moveTo:r,lineTo:r,rect:(c,u,d,m)=>{r(c,u),r(c+d,u+m)},arc:(c,u,d)=>{r(c-d,u-d),r(c+d,u+d)},bezierCurveTo:(c,u,d,m,f,h)=>{r(c,u),r(d,m),r(f,h)},quadraticCurveTo:(c,u,d,m)=>{r(c,u),r(d,m)}})||!(i>e)||!(o>s)?null:{x:e,y:s,width:i-e,height:o-s}}function We(n,t,e){const s=t.stroke!==null&&t.strokeWidth>0,i=()=>{t.fill!==null&&(n.globalAlpha=t.opacity*t.fillOpacity,n.fillStyle=t.fill,n.fill())},o=()=>{s&&(n.globalAlpha=t.opacity*t.strokeOpacity,n.strokeStyle=t.stroke,n.lineWidth=t.strokeWidth,n.lineJoin=t.lineJoin,n.lineCap=t.lineCap,n.setLineDash(t.dash),n.stroke())};t.strokeFirst?(o(),i()):(i(),o()),n.globalAlpha=1,n.setLineDash([])}function Qn(n,t,e){const s=Array.from(n.children).filter(o=>o.tagName.toLowerCase()==="tspan"),i=s.length>0?"":n.textContent??"";if(i.trim()!==""){const o=L(n.getAttribute("x"),0)+L(n.getAttribute("dx"),0),r=L(n.getAttribute("y"),0)+L(n.getAttribute("dy"),0);t.font=kr(e),t.textAlign=e.anchor,t.textBaseline=e.baseline;const a=e.stroke!==null&&e.strokeWidth>0,l=()=>{e.fill!==null&&(t.globalAlpha=e.opacity*e.fillOpacity,t.fillStyle=e.fill,t.fillText(i,o,r))},c=()=>{a&&(t.globalAlpha=e.opacity*e.strokeOpacity,t.strokeStyle=e.stroke,t.lineWidth=e.strokeWidth,t.lineJoin=e.lineJoin,t.setLineDash([]),t.strokeText(i,o,r))};e.strokeFirst?(c(),l()):(l(),c()),t.globalAlpha=1}for(const o of s)Qn(o,t,Kn(o,e,new Map))}function kr(n){const t=n.fontStyle!=="normal"?`${n.fontStyle} `:"",e=n.fontWeight!=="normal"?`${n.fontWeight} `:"";return`${t}${e}${n.fontSize}px ${n.fontFamily}`}const Ge=1/12;function xr(n,t){return{x:n.right-n.left>=Math.max(1,t.width)*Ge,y:n.bottom-n.top>=Math.max(1,t.height)*Ge}}function Sr(n){return n.metaKey||n.ctrlKey}function Mr(n){const{host:t}=n;if(typeof window>"u")return{destroy:()=>{}};const e=g("div",{class:"figure-marquee hidden"});t.appendChild(e);let s=null,i=null;const o=h=>{const y=t.getBoundingClientRect();return{x:h.clientX-y.left,y:h.clientY-y.top}},r=h=>({left:Math.min(s?.x??h.x,h.x),right:Math.max(s?.x??h.x,h.x),top:Math.min(s?.y??h.y,h.y),bottom:Math.max(s?.y??h.y,h.y)}),a=h=>{e.classList.remove("hidden"),e.style.left=`${h.left}px`,e.style.top=`${h.top}px`,e.style.width=`${Math.max(0,h.right-h.left)}px`,e.style.height=`${Math.max(0,h.bottom-h.top)}px`},l=()=>{e.classList.add("hidden"),s=null,i=null},c=h=>{!Sr(h)||h.button!==0||n.chart()!==null&&(h.preventDefault(),h.stopPropagation(),s=o(h),i=h.pointerId,t.setPointerCapture?.(h.pointerId))},u=h=>{s===null||h.pointerId!==i||(h.preventDefault(),h.stopPropagation(),a(r(o(h))))},d=h=>{if(s===null||h.pointerId!==i)return;h.preventDefault(),h.stopPropagation();const y=r(o(h));l(),t.hasPointerCapture?.(h.pointerId)===!0&&t.releasePointerCapture?.(h.pointerId);const b=xr(y,{width:t.clientWidth,height:t.clientHeight});!b.x&&!b.y||n.onZoom(y,b)},m=h=>{h.pointerId===i&&l()},f=()=>n.onReset();return t.addEventListener("pointerdown",c,!0),t.addEventListener("pointermove",u,!0),t.addEventListener("pointerup",d,!0),t.addEventListener("pointercancel",m,!0),t.addEventListener("dblclick",f),{destroy(){t.removeEventListener("pointerdown",c,!0),t.removeEventListener("pointermove",u,!0),t.removeEventListener("pointerup",d,!0),t.removeEventListener("pointercancel",m,!0),t.removeEventListener("dblclick",f),e.remove()}}}function He(n,t,e,s,i){const o=u=>{const d=i?[n.getWidth()/2,u]:[u,n.getHeight()/2],m=n.convertFromPixel({gridIndex:0},d),f=Array.isArray(m)?m[i?1:0]:null;if(typeof f=="number"&&Number.isFinite(f))return f;const h=n.convertFromPixel(t,u),y=Array.isArray(h)?h[i?1:0]:h;return typeof y=="number"&&Number.isFinite(y)?y:null},r=o(e),a=o(s);if(r===null||a===null)return null;const[l,c]=r<=a?[r,a]:[a,r];return l<c?[l,c]:null}let ut=null,Ke=null;async function $r(){ut===null&&(Ke??=Fs(()=>import("./echartsBundle-Dqa1ruUg.js"),[],import.meta.url).then(n=>{ut=n.echarts}),await Ke)}function Nt(n){const t=Ps(n),e=/\d+(?:\.\d+)?px\s+(.*)$/.exec(t.font)?.[1]??"system-ui, sans-serif";return{ink:t.ink,muted:t.muted,grid:t.grid,background:t.background,series:t.series,fontFamily:e,measure:(s,i)=>{const o=Tr();return o===null?s.length*i*.6:(o.font=`${i}px ${e}`,o.measureText(s).width)}}}function Er(n){const t=n??{},e=[t,...t.batch??[]].map(s=>s.dataZoomId).filter(s=>typeof s=="string");return e.length===0?null:new Set(e)}let Ht;function Tr(){return Ht===void 0&&(Ht=document.createElement("canvas").getContext("2d")),Ht}function Cr(n){return Math.max(260,Math.min(520,Math.round(n*.78)))}function Kt(n){const t=g("div",{class:n.fill===!0?"figure-chart figure-chart-fill":"figure-chart"});let e=n.style,s=null,i=n.fill===!0,o=0,r=0,a=!1,l=!1,c=null,u={x:n.style.x.domain,y:n.style.y.domain};const d=(S,$=t)=>n.spec.kind==="matrix"?Qo(n.spec.output,e,Nt($),S):Ro(n.spec,e,Nt($),S),m=()=>i?t.clientHeight:Cr(o),f=()=>{s!==null||o<=0||ut===null||(r=m(),!(r<=0)&&(s=ut.init(t,null,{renderer:"svg",width:o,height:r}),s.on("legendselectchanged",S=>{const $=n.spec;if($.kind==="matrix")return;const C=S.selected;if(C===void 0)return;const A=$.series.filter(O=>C[O.name]===!1).map(O=>O.id);e={...e,hidden:A},n.onStyle?.(e)}),s.on("dataZoom",S=>{if(l||s===null)return;const $=s.getOption().dataZoom;if($===void 0)return;const C=V=>{if(V===void 0)return null;const R=V.startValue,D=V.endValue;return typeof R!="number"||typeof D!="number"||!Number.isFinite(R)||!Number.isFinite(D)||R>=D?null:[R,D]},A=Er(S),O=A===null||A.has(de),I=A===null||A.has(he),F=e.x.domain;e={...e,x:O?{...e.x,domain:C($[0])??e.x.domain}:e.x,y:I?{...e.y,domain:C($[1])??e.y.domain}:e.y};const _=n.spec;if(_.kind!=="matrix"){const V=K=>({showMinLabel:K.labels.showMinLabel??null,showMaxLabel:K.labels.showMaxLabel??null,customValues:K.ticks??null}),R=Ot(_,e,"x",_n(_,e,Nt(t),{width:o})),D=Ot(_,e,"y"),et=e.y.domain===null&&e.x.domain!==F;l=!0,s.setOption({xAxis:{axisLabel:V(R),axisTick:{customValues:R.ticks??null}},yAxis:{...et?{min:D.bounds.min??null,max:D.bounds.max??null}:{},axisLabel:V(D),axisTick:{customValues:D.ticks??null}}}),l=!1}n.onStyle?.(e)}),b()))},h=(S,$)=>{if(s===null)return;const C={...e};if($.x){const A=He(s,{xAxisIndex:0},S.left,S.right,!1);A!==null&&(C.x={...C.x,domain:A})}if($.y){const A=He(s,{yAxisIndex:0},S.top,S.bottom,!0);A!==null&&(C.y={...C.y,domain:A})}C.x.domain===e.x.domain&&C.y.domain===e.y.domain||(e=C,b(),n.onStyle?.(e))},y=()=>{e.x.domain===u.x&&e.y.domain===u.y||(e={...e,x:{...e.x,domain:u.x},y:{...e.y,domain:u.y}},b(),n.onStyle?.(e))},b=()=>{s!==null&&(l=!0,s.setOption(d({width:o,height:r}),!0),l=!1)},k=()=>{if(o<=0)return;if(s===null){f();return}const S=m();if(S<=0)return;r=S,s.resize({width:o,height:r});const $=n.spec;($.kind==="matrix"||e.legend==="right"||$.xScaled!==void 0)&&b()},p=typeof ResizeObserver>"u"?null:new ResizeObserver(S=>{const $=S[0]?.contentRect,C=$?.width??0;Math.abs(C-o)<.5&&(!i||Math.abs(($?.height??0)-r)<.5)&&s!==null||(o=C,k())});p?.observe(t);const w=window.matchMedia?.("(prefers-color-scheme: dark)"),M=()=>b(),v=typeof MutationObserver>"u"?null:new MutationObserver(M);v?.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),w?.addEventListener?.("change",M);const x=Is(()=>b()),E=$r().then(()=>{a||typeof document>"u"||(o>0&&f(),c??=Mr({host:t,chart:()=>s,onZoom:h,onReset:y}))},()=>{a||typeof document>"u"||t.replaceChildren(g("p",{class:"hint",text:"The chart library did not load. Check the connection and reopen this result."}))});return{el:t,ready:E,draw(S,$){if(ut===null)throw new Error("the chart library has not arrived yet");const C=document.createElement("div");C.style.cssText=`position:absolute;left:-10000px;top:0;width:${$.width}px;height:${$.height}px`,t.appendChild(C);const A=ut.init(C,null,{renderer:"svg",width:$.width,height:$.height});try{A.setOption(Po(d($,Bs())),!0),dr(A.renderToSVGString(),S,$)}finally{A.dispose(),C.remove()}},update(S){e=S,u={x:S.x.domain,y:S.y.domain},b()},setFill(S){i!==S&&(i=S,t.classList.toggle("figure-chart-fill",S),k())},current(){return e},destroy(){a=!0,c?.destroy(),c=null,p?.disconnect(),v?.disconnect(),w?.removeEventListener?.("change",M),x(),s?.dispose(),s=null}}}const Ye=24;function Ar(n){const t=g("div",{class:"controls-card figure-settings"}),e=i=>{n.onChange({...n.style(),...i})},s=()=>{const i=n.style(),o=n.spec.kind==="xy"?[Or(n.spec,i,e),ts(n.spec,i,e),Pr(n.spec,i,e,n.theme()),$t(i,e)]:n.spec.kind==="matrix"?n.spec.output.streaks!==void 0?[$t(i,e,It(n.spec.output))]:[qr(i,e),$t(i,e,It(n.spec.output))]:[zr(n.spec,i,e),...Fr(n.spec,i,e),$t(i,e)];t.replaceChildren(mn("Figure","chart-line","controls-title"),g("div",{class:"panel-controls"},...o,g("div",{class:"figure-actions"},N("reset",()=>n.onReset(),{class:"btn btn-quiet",title:"Back to the figure the task returned, and forget what was set here"}),...n.exports??[])))};return s(),{el:t,refresh:s}}function ht(n,...t){return g("div",{class:"figure-group"},g("h4",{class:"figure-group-head",text:n}),...t.filter(e=>e!==!1))}function j(n,t,e,s){const i=g("select",{class:"select"});for(const o of n){const r=g("option",{value:o,text:o}),a=s?.[o];a!==void 0&&(r.title=a),i.appendChild(r)}return i.value=t,i.addEventListener("change",()=>e(i.value)),i}function tt(n,t,e,s){const i=`figure-toggle-${Lr+=1}`,o=N(t?"on":"off",()=>e(!t),{class:"btn btn-toggle",title:s});return o.setAttribute("aria-pressed",String(t)),o.setAttribute("aria-labelledby",i),g("div",{class:"field ann-field figure-check"},g("span",{class:"field-label",text:n,id:i,title:s}),o)}function Nr(n,t,e,s){const i=N(n,()=>e(!t),{class:"btn btn-toggle",title:s});return i.setAttribute("aria-pressed",String(t)),i}let Lr=0;function rt(n,t,e,s){const i=g("input",{class:"input input-num",type:"number",title:e,placeholder:"auto"});i.value=n===null?"":At(n,6),s!==void 0&&(i.step=String(s));const o=()=>{const r=i.value.trim();if(r===""){t(null);return}const a=Number(r);t(Number.isFinite(a)?a:null)};return i.addEventListener("change",o),i}function fe(n,t,e,s){const i=g("input",{class:"input",type:"text",title:e,placeholder:s});return i.value=n,i.addEventListener("change",()=>t(i.value)),i}const jn={line:"Joined samples — a claim that something is between them",area:"A line with the space under it filled",step:"Held between samples, for a quantity that changes at them",points:"One mark per sample and nothing between, for an x that is not an ordering",bars:"One bar per sample",histogram:"The y values counted into bins; x is ignored",box:"Quartiles and Tukey whiskers per series; x is ignored",violin:"A kernel density per series, every violin to one scale; x is ignored"};function Or(n,t,e){const s=[...gn,...pn],i=n.series.some(r=>r.low!==void 0),o=t.mark==="line"||t.mark==="area"||t.mark==="step";return ht("chart",z("mark",j(s,t.mark,r=>e({mark:r}),jn)),o&&z("line width",rt(t.lineWidth,r=>e({lineWidth:r??1.8}),"In CSS pixels",.25)),(t.mark==="points"||t.jitter||t.mark==="box")&&z("point size",rt(t.pointSize,r=>e({pointSize:r??6}),"In CSS pixels",1)),o&&tt("smooth",t.smooth,r=>e({smooth:r}),"A curve through the samples rather than straight segments — a claim about what is between them"),o&&tt("fill under",t.fillArea,r=>e({fillArea:r}),"Shade the space between the line and the axis"),i&&tt("band",t.bands,r=>e({bands:r}),"The spread the task computed, drawn around each line"),t.mark==="histogram"&&z("bins",rt(t.bins===0?null:t.bins,r=>e({bins:r===null?0:Math.round(r)}),"Empty chooses the width from the data (Freedman–Diaconis)",1)),(t.mark==="box"||t.mark==="violin")&&tt("points",t.jitter,r=>e({jitter:r}),"Every observation beside the summary, so a summary of six points does not read like one of six thousand"))}function Ir(n,t,e,s){const i=ue(n,t,e);if(i!==null)return i[s];const o=t[e].scale==="log",r=t.mark==="histogram";let a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const c of n.series){if(t.hidden.includes(c.id))continue;const u=r?Dt(c.y,t.bins):null,d=u!==null?e==="x"?u.edges:[0,...u.counts]:e==="x"?c.y.map((m,f)=>c.x[f]??f):c.y;for(const m of d)!Number.isFinite(m)||o&&m<=0||(m<a&&(a=m),m>l&&(l=m))}return a>l?null:s===0?a:l}function Ue(n,t,e,s){const i=e[n],o=l=>s({[n]:{...i,...l}}),r=i.domain,a=l=>rt(r===null?null:r[l],c=>{if(c===null){o({domain:null});return}const u=r===null?Ir(t,e,n,l===0?1:0):r[l===0?1:0];if(u===null)return;const d=l===0?[c,u]:[u,c];o({domain:d[0]<d[1]?d:null})},l===0?"The low end of the window; empty fits the data":"The high end of the window; empty fits the data");return[z(`${n} scale`,j(["linear","log"],i.scale,l=>o({scale:l}),{log:"A log axis has no place for a zero: values at or below it become gaps"})),z(`${n} name`,fe(i.label??"",l=>o({label:l===""?null:l}),"What the axis is called; empty is the task’s own name",n==="x"?t.xLabel:t.yLabel)),g("div",{class:"field ann-field figure-range"},g("span",{class:"field-label",text:`${n} from`}),a(0),g("span",{class:"field-label",text:"to"}),a(1)),tt(`${n} grid`,i.grid,l=>o({grid:l}),"Rules across the plot at the ticks")]}function Fr(n,t,e){const s=t.plot;return s===null||s.x===null?[]:[ts(bn(n,s.x,s.y,s.mark,s.fit,t.x.domain),t,e)]}function ts(n,t,e){return ht("axes",...Ue("x",n,t,e),...Ue("y",n,t,e),g("div",{class:"figure-actions"},N("fit",()=>e({x:{...t.x,domain:null},y:{...t.y,domain:null}}),{class:"btn btn-quiet",title:"Both axes back to the whole of the data"})))}function Pr(n,t,e,s){const i=n.series.slice(0,Ye).map((r,a)=>{const l=t.hidden.includes(r.id),c=J(l?"eye-off":"eye",l?`Show ${r.name}`:`Hide ${r.name}`,()=>e({hidden:l?t.hidden.filter(d=>d!==r.id):[...t.hidden,r.id]}),{class:"btn btn-icon btn-toggle ann-eye",size:13});c.setAttribute("aria-pressed",String(!l));const u=g("input",{class:"figure-swatch",type:"color"});return u.value=Rr(Pn(r,a,t,s)),u.title=`The colour of ${r.name}`,u.addEventListener("change",()=>e({colours:{...t.colours,[r.id]:u.value}})),g("div",{class:"figure-series-row"},c,u,g("span",{class:"figure-series-name",text:r.name,title:r.name}),r.n===void 0||!Number.isFinite(r.n)?g("span"):g("span",{class:"figure-series-n",text:`n = ${r.n}`}))}),o=n.series.length-i.length;return ht("series",g("div",{class:"figure-series"},...i),o>0&&g("p",{class:"hint",text:`…and ${o} more, all of them drawn. Only the first ${Ye} are listed.`}),g("div",{class:"figure-actions"},N("show all",()=>e({hidden:[]}),{class:"btn btn-quiet",title:"Every series back on the picture"}),N("reset colours",()=>e({colours:{}}),{class:"btn btn-quiet",title:"Back to the task’s own colours and the palette"})))}const Br=["right","top","bottom","none"];function $t(n,t,e=!0){return ht("text",z("title",fe(n.title??"",s=>t({title:s===""?null:s}),"Printed on the figure itself, so it survives the export; empty is no title","none")),z("type size",rt(n.fontSize,s=>t({fontSize:s??11}),"In CSS pixels, for every word on the figure",1)),z("legend",j(Br,n.legend,s=>t({legend:s}))),...e?[tt("tooltip",n.tooltip,s=>t({tooltip:s}),"The readout that follows the pointer")]:[])}function qr(n,t){const e=["auto",...qs];return ht("colour",z("colormap",j(e,n.colormap??"auto",s=>t({colormap:s==="auto"?null:s}))),g("div",{class:"field ann-field figure-range"},g("span",{class:"field-label",text:"scale"}),rt(n.vmin,s=>t({vmin:s}),"The value the lowest colour means; empty fits the data"),g("span",{class:"field-label",text:"to"}),rt(n.vmax,s=>t({vmax:s}),"The value the highest colour means; empty fits the data")))}function zr(n,t,e){const s=zs(n),i=[...s,...Rs(n)],o=t.plot,r=n.columns.map(l=>l.key),a=t.columns??r;return ht("rows",z("filter",fe(t.filter,l=>e({filter:l}),"Rows whose text contains this, anywhere","every row")),z("sort by",j(["—",...r],t.sortKey??"—",l=>e({sortKey:l==="—"?null:l}))),t.sortKey!==null&&tt("descending",t.sortDown,l=>e({sortDown:l}),"Largest or last first"),g("div",{class:"figure-columns"},...n.columns.map(l=>{const c=a.includes(l.key);return Nr(l.label,c,u=>e({columns:u?r.filter(d=>a.includes(d)||d===l.key):a.filter(d=>d!==l.key)}),l.hint??`Show the ${l.label} column`)})),s.length>0&&z("plot",j(["table",...s.map(l=>l.key)],o===null?"table":o.y,l=>e({plot:l==="table"?null:{x:o?.x??null,y:l,mark:o?.mark??"histogram",fit:o?.fit??!1}})),"A column drawn instead of the rows: its distribution on its own, or against another column"),o!==null&&z("against",j(["—",...i.map(l=>l.key)],o.x??"—",l=>e({plot:{...o,x:l==="—"?null:l,mark:l==="—"?"histogram":"points"}})),"The abscissa; on its own the column is drawn as a distribution. A column of names is read at the first number in each, and a row whose name has none is left out"),o!==null&&o.x!==null&&tt("least squares",o.fit,l=>e({plot:{...o,fit:l}}),"The straight line fitted through the points, its equation, r² and n in the legend"),o!==null&&z("as",j(o.x===null?pn:gn,o.mark,l=>e({plot:{...o,mark:l}}),jn)))}function Rr(n){const t=n.trim();if(/^#[0-9a-f]{6}$/i.test(t))return t;const e=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(t);if(e!==null)return`#${e[1]}${e[1]}${e[2]}${e[2]}${e[3]}${e[3]}`;const s=/^#([0-9a-f]{6})[0-9a-f]{2}$/i.exec(t);if(s!==null)return`#${s[1]}`;const i=/^rgba?\(([^)]+)\)$/i.exec(t);if(i!==null){const o=i[1].split(/[,/\s]+/).filter(a=>a!==""),r=a=>{const l=Math.round(Number.parseFloat(o[a]??"0"));return(Number.isFinite(l)?Math.max(0,Math.min(255,l)):0).toString(16).padStart(2,"0")};return`#${r(0)}${r(1)}${r(2)}`}return"#000000"}const Dr="figure:side";function Ze(n){const t=Ds(n.output);if(t===null)throw new Error("this output is not a figure");return _r(t,n)}function _r(n,t){let e=_s(t.uri,t.task,n),s=null,i=null,o=d(n,e);const r=g("div",{class:"figure-body"},o.el),a=g("div",{class:"figure-strip"}),l=g("div",{class:"analysis-figure-head"}),c=g("div",{class:"analysis-figure figure-block"},l,a,r),u=()=>"update"in o?o:null;function d(v,x){const E=s!==null;if(v.kind==="matrix"&&v.output.streaks!==void 0){const S=Vs(v.output.streaks);return S.setFill?.(E),S}if(v.kind==="matrix"){const S=It(v.output)?v.output:Gr(v,x);return It(S)?Kt({spec:{...v,output:S},style:Je(v,x),onStyle:$=>m($),fill:E}):Ws(S)}if(v.kind==="table"){const S=es(v,x);return S===null?Pi(v,x,($,C)=>f({sortKey:$,sortDown:C})):Kt({spec:S.spec,style:S.style,onStyle:$=>m($),fill:E})}return Kt({spec:v,style:x,onStyle:S=>m(S),fill:E})}function m(v){const x=e;e=v,ye(t.uri,t.task,n.id,e),i?.refresh(),b(),ns(n,x,e)&&setTimeout(()=>{h(),k()},0)}function f(v){const x=e;e={...e,...v},ye(t.uri,t.task,n.id,e);const E=u();E!==null&&Vr(n,x,e)?E.update(Je(n,e)):n.kind==="matrix"&&n.output.streaks!==void 0||h(),i?.refresh(),b(),k()}function h(){const v=d(n,e);(o.el.parentElement??r).replaceChild(v.el,o.el),o.destroy(),o=v}function y(){Ks(t.uri,t.task,n.id),e=Ys(n),h(),i?.refresh(),b(),k()}function b(){const v=[];if(n.kind==="xy"){const x=g("select",{class:"select select-tight"});for(const E of["line","area","step","points","bars","histogram","box","violin"])x.appendChild(g("option",{value:E,text:E}));x.value=e.mark,x.title="How the series are drawn",x.addEventListener("change",()=>f({mark:x.value})),v.push(x),v.push(Qe("x",e,f),Qe("y",e,f),Wr("list",e.legend!=="none","legend",()=>f({legend:e.legend==="none"?"right":"none"})),N("fit",()=>f({x:{...e.x,domain:null},y:{...e.y,domain:null}}),{class:"btn btn-quiet",title:"Both axes back to the whole of the data — the wheel zooms, this undoes it"}))}else if(!(n.kind==="matrix"&&n.output.streaks!==void 0))if(n.kind==="matrix"){const x=g("select",{class:"select select-tight"});x.appendChild(g("option",{value:"",text:"auto"}));const E=Yt.includes(e.colormap??"")?Yt:[...e.colormap===null?[]:[e.colormap],...Yt];for(const S of E)x.appendChild(g("option",{value:S,text:S}));x.value=e.colormap??"",x.title="The colours the values are drawn in",x.addEventListener("change",()=>f({colormap:x.value===""?null:x.value})),v.push(x)}else{const x=g("input",{class:"input input-tight",type:"search",placeholder:"filter rows",value:e.filter});x.title="Rows whose text contains this, anywhere",x.addEventListener("change",()=>f({filter:x.value})),v.push(x)}a.replaceChildren(...v)}function k(){const v=Xe(o);l.replaceChildren(g("span",{class:"analysis-figure-title",text:e.title??t.output.label}),...t.extras??[],...v===null||t.onPng===void 0?[]:[N("PNG",()=>t.onPng?.(v),{class:"btn",title:"The figure as a raster, redrawn at 300 dpi"})],...v===null||t.onPdf===void 0?[]:[N("PDF",()=>t.onPdf?.(v),{class:"btn",title:"The figure as a true vector page — restylable, recolourable, scalable"})],...v===null||t.onCopy===void 0?[]:[N("Copy",()=>t.onCopy?.(v),{class:"btn",title:"The figure as a raster at 300 dpi, onto the clipboard — the PNG, to paste"})],J("sliders-horizontal","Customise this figure",()=>p(),{class:"btn btn-icon figure-enlarge",size:14}))}function p(){if(s!==null)return;const v=M();s=Hs({title:e.title??t.output.label,stage:o.el,side:v.el,memoryKey:()=>t.uri,scope:Dr,onResize:()=>w(!0),onClose:()=>{s=null,w(!1),r.replaceChildren(o.el),k()}}),w(!0)}function w(v){u()?.setFill(v),o.setFill?.(v)}function M(){return i===null&&(i=Ar({spec:n,style:()=>e,onChange:v=>f(v),onReset:()=>y(),theme:()=>Nt(c)})),i.refresh(),i}return b(),k(),{el:c,drawable:()=>Xe(o),ready:()=>"ready"in o?o.ready:Promise.resolve(),destroy(){s?.close(),o.destroy()}}}function Xe(n){return"draw"in n?n:null}function Vr(n,t,e){return n.kind==="matrix"?!0:n.kind==="table"?t.plot===null||e.plot===null?t.plot===e.plot:t.plot.x===e.plot.x&&t.plot.y===e.plot.y&&t.plot.fit===e.plot.fit&&!ns(n,t,e):!0}function es(n,t){const e=t.plot;if(e===null)return null;const s=e.x===null?Gs(n,e.y,e.mark):bn(n,e.x,e.y,e.mark,e.fit,t.x.domain);return{spec:s,style:{...t,mark:e.mark,legend:s.series.length>1?t.legend==="none"?"none":"top":"none"}}}function Je(n,t){return n.kind==="table"?es(n,t)?.style??t:n.kind==="matrix"?{...t,legend:"none"}:t}function ns(n,t,e){if(n.kind!=="table"||e.plot===null||!e.plot.fit||e.plot.x===null)return!1;const s=t.x.domain,i=e.x.domain;return s===null||i===null?s!==i:s[0]!==i[0]||s[1]!==i[1]}const Yt=["fall","viridis","magma","seismic","coolwarm","bwr"];function Qe(n,t,e){const s=t[n],i=s.scale==="log",o=N(`log ${n}`,()=>e({[n]:{...s,scale:i?"linear":"log"}}),{class:"btn btn-toggle",title:i?`A linear ${n} axis`:`A log ${n} axis — values at or below zero become gaps`});return o.setAttribute("aria-pressed",String(i)),o}function Wr(n,t,e,s){const i=J(n,t?`Hide the ${e}`:`Show the ${e}`,s,{class:"btn btn-icon btn-toggle",size:13});return i.setAttribute("aria-pressed",String(t)),i}function Gr(n,t){const e={...n.output};if(t.colormap!==null&&(e.colormap=t.colormap),t.vmin===null&&t.vmax===null)return e;let s=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const a of n.output.values)Number.isFinite(a)&&(a<s&&(s=a),a>i&&(i=a));const o=t.vmin??(Number.isFinite(s)?s:0),r=t.vmax??(Number.isFinite(i)?i:1);return o<r&&(e.range=[o,r]),e}const je="10.1093/bioinformatics/btae088",Et="10.1371/journal.pcbi.1012067",tn="10.1093/nar/gkw257",Hr={coverage:{method:"Coverage as cooltools computes it (Open2C 2024).",doi:Et,agreement:"identical",section:9},cistrans:{method:"Cis and trans sums as cooltools’ expected_cis and expected_trans make them (Open2C 2024).",doi:Et,agreement:"identical",section:20},cellqc:{method:"The near and mitotic contact shares of Nagano et al. 2017.",doi:"10.1038/nature23001",agreement:"untested"},expected:{method:"The expected contact by separation, as cooltools’ expected_cis computes it (Open2C 2024).",doi:Et,agreement:"identical",section:4},pairsqc:{method:"The pairs’ statistics and fragments, as pairtools’ stats and restrict count them (Open2C 2024).",doi:"10.1371/journal.pcbi.1012164",agreement:"identical",section:27},mapreport:{method:"The map resolution of Rao et al. 2014, its counts at every bin size.",doi:"10.1016/j.cell.2014.11.021",agreement:"identical",section:29},scalogram:{method:"The scalogram of Lioy et al. 2018.",doi:"10.1016/j.cell.2017.12.027",agreement:"untested"},fourc:{method:"Virtual 4C as cooltools’ virtual4c computes it (Open2C 2024).",doi:Et,agreement:"identical",section:10},insulation:{method:"Diamond insulation (Crane et al. 2015), as cooltools computes it.",doi:"10.1038/nature14450",agreement:"identical",section:1},di:{method:"The directionality index of Dixon et al. 2012, as domaincaller computes it.",doi:"10.1038/nature11082",agreement:"identical",section:2},hicscore:{method:"The HiC score of Bignaud et al. 2024, after their R script.",doi:"10.1038/s41594-023-01178-2",agreement:"untested"},arrowhead:{method:"Contact domains by Arrowhead (Rao et al. 2014), as juicer_tools arrowhead calls them.",doi:"10.1016/j.cell.2014.11.021",agreement:"identical",section:28},compartments:{method:"The first eigenvector (Lieberman-Aiden et al. 2009), as cooltools’ eigs_cis takes it.",doi:"10.1126/science.1181369",agreement:"equivalent",section:3},loops:{method:"HiCCUPS (Rao et al. 2014), as cooltools.dots computes it.",doi:"10.1016/j.cell.2014.11.021",agreement:"identical",section:19},chromosight:{method:"Chromosight’s template matching (Matthey-Doret et al. 2020).",doi:"10.1038/s41467-020-19562-7",agreement:"identical",section:6},hicrep:{method:"HiCRep’s stratum-adjusted correlation (Yang et al. 2017).",doi:"10.1101/gr.220640.117",agreement:"identical",section:7},apa:{method:"Coolpup.py’s pile-ups (Flyamer et al. 2020), and chromosight’s score.",doi:"10.1093/bioinformatics/btaa073",agreement:"identical",section:11},reconstruct3d:{method:"pastis-NB, a negative binomial fit (Varoquaux et al. 2023).",doi:"10.1093/bioinformatics/btac838",agreement:"equivalent",section:8},motif:{method:"A motif scan as seqkit locate makes it (Shen et al. 2016).",doi:"10.1371/journal.pone.0163962",agreement:"identical",section:17},restriction:{method:"Restriction sites as bioframe’s digest finds them, each 2 bp earlier (Open2C 2024).",doi:je,agreement:"identical",section:26},peaks:{method:"yapc’s concave regions (Jänes et al. 2018), with IDR across replicates.",doi:"10.7554/eLife.37344",agreement:"identical",section:5},composition:{method:"GC content and skews, as bioframe and Biopython compute them (Open2C 2024).",doi:je,agreement:"identical",section:16},metaplot:{method:"deepTools’ computeMatrix and plotProfile (Ramírez et al. 2016).",doi:tn,agreement:"identical",section:14},trackcorr:{method:"deepTools’ multiBigwigSummary and plotCorrelation (Ramírez et al. 2016), on exact window means.",doi:tn,agreement:"equivalent",section:18},frip:{method:"FRiP, as the ENCODE guidelines define it (Landt et al. 2012).",doi:"10.1101/gr.136184.111",agreement:"identical",section:22},groupsignal:{method:"Mann–Whitney and Kruskal–Wallis tests as SciPy computes them (Virtanen et al. 2020).",doi:"10.1038/s41592-019-0686-2",agreement:"identical",section:23},overlap:{method:"bedtools’ intersect and jaccard, with a shuffle null (Quinlan and Hall 2010).",doi:"10.1093/bioinformatics/btq033",agreement:"identical",section:15}};function Kr(n){return Hr[n]??null}function Yr(n){return n.agreement!=="untested"}const ss={identical:"Identical in the validation",equivalent:"Equivalent in the validation",untested:"Not validated yet"};function Ur(n,t){n.replaceChildren(g("p",{class:"question-tip-text",text:t.method}),g("p",{class:"question-tip-note"},`${ss[t.agreement]} · `,g("a",{text:`doi:${t.doi}`,attrs:{href:`https://doi.org/${t.doi}`,target:"_blank",rel:"noopener noreferrer"}})))}function Zr(n){return Us({class:`task-ref${Yr(n)?" is-validated":""}`,label:`${n.method} ${ss[n.agreement]}.`,fill:t=>Ur(t,n)})}const Xr={"2d":"grid-2x2","3d":"box","1d":"chart-line",metagenome:"library"};function Jr(n){switch(n.status){case"idle":return{text:"never run",tone:"",spinner:!1,detail:"",batch:""};case"queued":return{text:"queued",tone:"is-running",spinner:!1,detail:"",batch:""};case"running":return{text:n.total>0?q.pct(Math.min(1,n.done/n.total),0):"running",tone:"is-running",spinner:!0,batch:n.batch===void 0?"":`${n.batch.at+1} of ${n.batch.of}`,detail:n.batch===void 0?n.note:`${n.batch.label}${n.note===""?"":` — ${n.note}`}`};case"done":return{text:`done in ${kn(n.ms)}`,tone:"is-done",spinner:!1,detail:"",batch:""};case"failed":return{text:"failed",tone:"is-failed",spinner:!1,detail:n.message,batch:""};case"cancelled":return{text:"cancelled",tone:"",spinner:!1,detail:"",batch:""}}}function Qr(n){return n.status==="running"||n.status==="queued"}function is(n){return n==="annotations"?"It stops at its next read; a pass with no read in it runs on, and its answer is discarded.":"The worker checks between chunks, so it stops at the next one."}class jr{constructor(t){this.options=t,this.el=g("div",{class:"analysis-tasks"},this.blockedEl,this.filterEl,this.noMatchEl,this.cardsEl),this.filterEl.addEventListener("input",()=>this.applyFilter()),this.filterEl.addEventListener("keydown",e=>{if(e.key==="Escape"&&this.filterEl.value!=="")e.preventDefault(),e.stopPropagation(),this.filterEl.value="",this.applyFilter();else if(e.key==="Enter"){e.preventDefault();const s=this.rows.find(i=>!i.el.classList.contains("is-filtered-out")&&!i.el.classList.contains("is-waiting"));s!==void 0&&this.options.onOpen(s.task)}}),this.unsubscribe=t.runner.subscribe(()=>this.refresh()),this.refresh()}el;unsubscribe;blockedEl=g("p",{class:"inline-error analysis-blocked hidden",attrs:{role:"status"}});cardsEl=g("div",{class:"analysis-cards"});filterEl=g("input",{class:"input input-tiny analysis-filter",type:"search",attrs:{"aria-label":"filter the tasks",spellcheck:"false",autocomplete:"off"}});noMatchEl=g("p",{class:"analysis-empty analysis-no-match hidden",attrs:{role:"status"}});rows=[];groupNotes=[];cards=[];built=null;refresh(){const t=this.options.context(),e=t===null?[]:yn(t),s=e.map(i=>i.id).join(`
6
+ `);s!==this.built&&(this.built=s,this.rebuild(e)),this.paint()}destroy(){this.unsubscribe(),this.rows.length=0,this.el.remove()}groups(t){const e=[];for(const s of t)e.includes(s.group)||e.push(s.group);return e}rebuild(t){if(this.rows.length=0,this.groupNotes.length=0,this.cards.length=0,this.filterEl.placeholder=`filter ${q.int(t.length)} task${t.length===1?"":"s"}…`,this.filterEl.classList.toggle("hidden",t.length===0),t.length===0){this.noMatchEl.classList.add("hidden"),this.cardsEl.replaceChildren(g("p",{class:"analysis-empty",text:"This file offers no analyses. A task that could never mean anything here is absent "+(vn("metacool")?"rather than greyed — a metagenome task on a plain cooler, say. ":"rather than greyed. ")+"Everything that is one file away is listed, waiting, with a line saying what to load."}));return}const e=[];for(const s of this.groups(t)){const i=[],o=g("p",{class:"analysis-group-needs hidden"});this.groupNotes.push({group:s,needs:o}),i.push(o);for(const a of t.filter(l=>l.group===s)){const l=this.row(a);this.rows.push(l),i.push(l.el,l.needs)}const r=g("section",{class:"card analysis-card"},mn(wn[s],Xr[s]),...i);this.cards.push({group:s,el:r}),e.push(r)}this.cardsEl.replaceChildren(...e),this.applyFilter()}applyFilter(){const t=this.filterEl.value.toLowerCase().split(/\s+/).filter(i=>i!=="");let e=0;for(const i of this.rows){const o=ta(i.task),r=t.every(a=>o.includes(a));i.el.classList.toggle("is-filtered-out",!r),i.needs.classList.toggle("is-filtered-out",!r),r&&e++}for(const i of this.cards){const o=this.rows.some(r=>r.group===i.group&&!r.el.classList.contains("is-filtered-out"));i.el.classList.toggle("is-filtered-out",!o)}const s=t.length>0&&e===0&&this.rows.length>0;this.noMatchEl.textContent=s?`No task matches “${this.filterEl.value.trim()}”.`:"",this.noMatchEl.classList.toggle("hidden",!s)}row(t){const e=g("span",{class:"analysis-chip"}),s=g("span",{class:"analysis-chip analysis-batch hidden"}),i=J("circle-stop",`Stop ${t.title}. ${is(t.venue)}`,()=>this.options.runner.cancel(t.id),{class:"btn btn-icon",size:14});i.addEventListener("click",m=>m.stopPropagation());const o=Kr(t.id),r=o===null?g("span",{class:"task-ref-blank",attrs:{"aria-hidden":"true"}}):Zr(o),a=g("div",{class:"plot-icon-row"},e,s,r),l=g("span",{class:"analysis-row-blurb",text:t.blurb}),c=g("p",{class:"analysis-row-needs hidden"}),u=g("div",{class:"analysis-row",attrs:{role:"button",tabindex:"0"}},g("span",{class:"analysis-row-title",text:t.title}),a,l),d=()=>{u.classList.contains("is-waiting")||this.options.onOpen(t)};return u.addEventListener("click",d),u.addEventListener("keydown",m=>{m.key!=="Enter"&&m.key!==" "||(m.preventDefault(),d())}),{task:t,el:u,chip:e,blurb:l,needs:c,stop:i,batch:s,cell:a,mark:r,group:t.group}}sharedNeeds(t){return t.length<2?"":t.every(e=>e===t[0])?t[0]:""}paint(){const t=this.options.active(),e=this.options.context(),s=this.options.blocked?.()??null;this.blockedEl.textContent=s??"",this.blockedEl.classList.toggle("hidden",s===null);const i=this.rows.map(l=>s!==null&&Q(l.task)),o=this.rows.map((l,c)=>s!==null&&i[c]?{state:"waiting",needs:s}:e===null?{state:"waiting",needs:"Open a file."}:l.task.availability(e)),r=new Map;this.rows.forEach((l,c)=>{const u=o[c];if(u.state!=="waiting"||i[c])return;const d=r.get(l.group)??[];d.push(u.needs),r.set(l.group,d)});const a=new Map;for(const[l,c]of r)a.set(l,this.sharedNeeds(c));for(const l of this.groupNotes){const c=a.get(l.group)??"";l.needs.textContent=c,l.needs.classList.toggle("hidden",c==="")}for(const[l,c]of this.rows.entries()){const u=o[l],d=u.state==="waiting";c.el.classList.toggle("is-waiting",d),d?c.el.setAttribute("aria-disabled","true"):c.el.removeAttribute("aria-disabled"),c.el.tabIndex=d?-1:0;const m=d&&!i[l]&&u.needs!==a.get(c.group)?u.needs:"";c.needs.textContent=m,c.needs.classList.toggle("hidden",m==="");const f=this.options.runner.stateOf(c.task.id),h=Jr(f);c.chip.className=h.tone===""?"analysis-chip":`analysis-chip ${h.tone}`,c.chip.replaceChildren(...h.spinner?[g("span",{class:"analysis-spinner",attrs:{"aria-hidden":"true"}})]:[],h.text),c.batch.textContent=h.batch,c.batch.classList.toggle("hidden",h.batch===""),c.blurb.textContent=h.detail===""?c.task.blurb:h.detail,c.el.title=d?u.needs:h.detail;const y=Qr(f);y&&c.stop.parentNode===null?c.cell.insertBefore(c.stop,c.mark):!y&&c.stop.parentNode!==null&&c.stop.remove();const b=t===c.task.id;c.el.classList.toggle("is-active",b),b?c.el.setAttribute("aria-current","true"):c.el.removeAttribute("aria-current")}}}function ta(n){return[n.title,n.blurb,...n.keywords??[],wn[n.group],n.id].join(`
7
+ `).toLowerCase()}function ea(n){let t=(Number.isFinite(n)?Math.trunc(n):0)>>>0;return function(){t=t+1831565813>>>0;let s=t;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function os(n,t){return n.options.filter(e=>e.needsGenomes===!0&&!t.hasGenomes?!1:e.needsKinds===void 0?!0:t.entries.some(s=>s.status!=="error"&&e.needsKinds.includes(s.kind)))}function na(n,t,e){const s={...e};for(const i of n){if(i.kind!=="choice")continue;const o=os(i,t);if(o.length===0)continue;const r=Y(s[i.key],i.default);o.some(a=>a.value===r)||(s[i.key]=o[0].value)}return s}function sa(n,t){return t.hasGenomes?n.label:n.coolLabel??n.label}const ia=400,oa="score";let ra=0;function aa(){const n=new Map;return{get:t=>n.get(t),set:(t,e)=>{e===null?n.delete(t):n.set(t,e)}}}function en(n,t){const e=t.toLowerCase();return n.accept.some(s=>e.endsWith(s))}const la=oi.filter(ri);function ca(n){switch(n.kind){case"featureSet":return la;case"pairSet":return["pairs"];case"track":return["track"];case"sequence":return["sequence"]}}function Pt(n,t){const e=ca(n);return t.entries.filter(s=>e.includes(s.kind)&&s.status!=="error")}function Bt(n){return(n.find(e=>e.primary===!0)??n[0])?.id??null}function ua(n){return n.kind==="featureSet"||n.kind==="pairSet"||n.kind==="track"||n.kind==="sequence"}function da(n,t,e){const s=Pt(n,t),i=typeof e=="string"&&e!=="";return i&&s.some(o=>o.id===e)?e:n.optional===!0?i||e===""?"":Bt(rs(s))??"":Bt(s)}function rs(n){return n.filter(t=>t.source.kind!=="computed"&&t.source.kind!=="derived")}function ha(n,t,e){const s=Pt(n,t),i=new Set(s.map(a=>a.id)),o=Array.isArray(e)?e.filter(a=>typeof a=="string"&&i.has(a)):[];if(n.optional===!0){if(Array.isArray(e))return o;const a=Bt(rs(s));return a===null?null:[a]}if(o.length>0)return o;const r=Bt(s);return r===null?[]:[r]}function fa(n){const e=/^\s*(.*?)\s*[=:]\s*(\S+)\s*$/.exec(n)??/^\s*(.*\S)\s+(\S+)\s*$/.exec(n);if(e===null)return null;const s=e[1];return s===""||!Number.isFinite(Number(e[2]))?null:s}function as(n){const t=[oa],e=n?.payload;if(e===void 0)return t;const s=e.data.detail,i=new Set(t),o=Math.min(s.length,ia);for(let r=0;r<o;r++)for(const a of s[r].split(ii)){const l=fa(a);l===null||i.has(l)||(i.add(l),t.push(l))}return t}function ls(n,t,e){const s=e[n.from],i=typeof s=="string"?s:Array.isArray(s)?s[0]??"":"";return i===""?void 0:t.entries.find(o=>o.id===i)}function ma(n,t,e){return as(ls(n,t,e))}function pa(n,t){const e=n.contigs.map(i=>i.name);if(!Array.isArray(t))return e;const s=new Set(e);return t.filter(i=>typeof i=="string"&&s.has(i))}function cs(n,t,e){const s=ma(n,t,e),i=e[n.key],o=typeof i=="string"&&i!=="";return o&&s.includes(i)?i:n.optional===!0?o||i===""?"":s[0]??"":s[0]??null}function Ut(n,t,e){const s=new Set(n.map(o=>o.key)),i={};for(const[o,r]of Object.entries(e))s.has(o)&&(i[o]=r);for(const o of n)ua(o)&&(i[o.key]=o.multiple===!0?ha(o,t,i[o.key]):da(o,t,i[o.key]));for(const o of n)o.kind==="column"&&(i[o.key]=cs(o,t,i));for(const o of n)o.kind==="sequences"&&(i[o.key]=pa(t,i[o.key]));for(const o of n)o.kind==="toggle"&&o.derive!==void 0&&(i[o.key]=o.derive(t));for(const o of n)o.settled!==void 0&&(ni(o,t)||(i[o.key]=o.settled));return na(n,t,i)}function nn(n,t){return typeof n=="number"&&Number.isFinite(n)?n:t}function Y(n,t){return typeof n=="string"?n:t}function sn(n,t=!1){const e=n.framing;if(e===null||e.level==="genome")return"";const[s,i]=e.rows,o=c=>n.contigs.filter(u=>u.startBin<c[1]&&u.startBin+u.bins>c[0]);if(t){const c=[...new Set([...o(e.rows),...o(e.cols)])];if(c.length===0||c.length===n.contigs.length)return"";if(c.length>1)return n.contigs.filter(u=>c.includes(u)).map(u=>u.name).join(", ")}const r=n.contigs.find(c=>s>=c.startBin&&s<c.startBin+c.bins);if(r===void 0)return"";if(i>r.startBin+r.bins)return r.name;const a=(s-r.startBin)*e.binsize,l=Math.min(r.length,(i-r.startBin)*e.binsize);return ce({contig:r.name,start:Math.max(0,Math.round(a)),end:Math.round(l)})}function ga(n){const t=Math.floor(ea(n)()*4294967296);return t===n?n+1>>>0:t}function oe(n,t){return Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&n.every((e,s)=>e===t[s]):n===t}function ba(n,t){for(const e of new Set([...Object.keys(n),...Object.keys(t)]))if(!oe(n[e],t[e]))return!1;return!0}class ya{constructor(t){this.options=t,this.specs=t.specs,this.context=t.context,this.shelf=t.files??aa(),this.params={...Ut(t.specs,t.context,t.value)},this.fillRegions(),this.forgetUnheld(),this.el=g("div",{class:"param-form"});for(const e of this.sections())this.el.appendChild(this.group(e));for(const e of this.specs){if(Lt(e)||e.retired===!0)continue;const s=this.build(e);this.controls.push(s),this.groups.get(e.section??"")?.appendChild(s.wrapper),s.shown=!0}this.syncVisibility()}el;context;params;specs;controls=[];groups=new Map;teardown=[];id=`pf${ra++}`;shelf;get value(){return{...this.params}}setContext(t){this.context=t;const e={...this.params};this.params={...Ut(this.specs,t,this.params)},this.fillRegions();for(const s of this.controls)s.refill?.(),s.sync();this.syncVisibility(),ba(e,this.params)||this.options.onChange(this.value)}setValue(t){this.params={...Ut(this.specs,this.context,t)},this.fillRegions(),this.forgetUnheld();for(const e of this.controls)e.refill?.(),e.sync();this.syncVisibility()}destroy(){for(const t of this.teardown)t();this.teardown.length=0,this.el.remove(),this.controls.length=0,this.groups.clear()}sections(){const t=this.specs.filter(s=>!Lt(s)&&s.retired!==!0),e=[""];for(const s of t){const i=s.section??"";e.includes(i)||e.push(i)}return e.filter(s=>t.some(i=>(i.section??"")===s))}group(t){const e=g("div",{class:"panel-controls"});return this.groups.set(t,e),g("div",{class:"controls-card param-group"},t===""?null:g("h3",{class:"controls-title",text:t}),e)}wrap(t,e,s){return g("div",{class:"param-row"},e,s,t.hint===void 0?null:g("div",{class:"hint",text:t.hint}))}labelled(t,e,s){return g("label",{class:"field param-field",attrs:{for:s}},g("span",{class:"field-label",text:t.label}),e)}named(t,e,s){return g("div",{class:"field param-field"},g("span",{class:"field-label",text:t.label,id:s}),e)}blocked(t,e,s){return e.setAttribute("role","group"),e.setAttribute("aria-labelledby",s),g("div",{class:"field field-block param-field"},g("span",{class:"field-label",text:t.label,id:s}),e)}commit(t,e){if(!oe(this.params[t],e)){this.params[t]=e;for(const s of this.controls)s.spec.kind==="column"&&s.refill?.(),s.sync();this.syncVisibility(),this.options.onChange(this.value)}}syncVisibility(){const t=new Map;for(let e=this.controls.length-1;e>=0;e--){const s=this.controls[e],i=s.spec.section??"",o=this.groups.get(i);if(o===void 0)continue;const r=Zs(s.spec,this.params,this.context),a=t.get(i)??null;r&&!s.shown?o.insertBefore(s.wrapper,a):!r&&s.shown&&s.wrapper.remove(),s.shown=r,r&&t.set(i,s.wrapper)}for(const[e,s]of this.groups)s.parentElement?.classList.toggle("hidden",!t.has(e))}fillRegions(){for(const t of this.specs){if(t.kind!=="region"||Y(this.params[t.key],"")!=="")continue;const e=t.default??sn(this.context,t.many===!0);e!==""&&(this.params[t.key]=e)}}forgetUnheld(){for(const t of this.specs){if(t.kind!=="file")continue;const e=Y(this.params[t.key],"").trim();e===""||kt(e)||this.shelf.get(t.key)?.value!==e&&(this.params[t.key]="")}}build(t){switch(t.kind){case"number":return this.numberControl(t);case"choice":return this.choiceControl(t);case"toggle":return this.toggleControl(t);case"featureSet":case"pairSet":case"track":case"sequence":return t.multiple===!0?this.entryList(t):this.entrySelect(t);case"column":return this.columnControl(t);case"sequences":return this.sequenceList(t);case"region":return this.locusControl(t);case"text":return this.textControl(t);case"file":return this.fileControl(t);case"seed":return this.seedControl(t)}}numberControl(t){const e=`${this.id}-${t.key}`,s=t.min!==void 0&&t.max!==void 0,i=t.slider===!0&&s,o=t.step??(t.integer===!0?1:void 0),r=g("input",{class:i?"input input-num input-step":"input input-num",type:"number",attrs:{id:e,size:"1",step:o===void 0?"any":String(o)}});t.min!==void 0&&(r.min=String(t.min)),t.max!==void 0&&(r.max=String(t.max));const a=i?g("input",{class:"ann-range",type:"range"}):null;a!==null&&t.min!==void 0&&t.max!==void 0&&(a.min=String(t.min),a.max=String(t.max),a.step=String(o??(t.max-t.min)/100),a.setAttribute("aria-labelledby",`${e}-label`));const l=b=>{let k=t.integer===!0?Math.round(b):b;return t.min!==void 0&&(k=Math.max(t.min,k)),t.max!==void 0&&(k=Math.min(t.max,k)),k},c=()=>nn(this.params[t.key],t.seed?.(this.context)??t.default),u=b=>{r.value=Number.isFinite(b)?String(b):"",a!==null&&Number.isFinite(b)&&(a.value=String(b))},d=()=>{const b=r.value.trim(),k=b===""?Number.NaN:Number(b);if(!Number.isFinite(k)){u(c());return}const p=l(k);u(p),this.commit(t.key,p)};r.addEventListener("change",d),r.addEventListener("keydown",b=>{b.key==="Enter"&&d()}),a!==null&&(a.addEventListener("input",()=>{r.value=String(l(Number(a.value)))}),a.addEventListener("change",()=>this.commit(t.key,l(Number(a.value)))));const m=t.unit===void 0||t.unit===""?null:g("span",{class:"field-label",text:t.unit}),f=g("div",{class:"plot-icon-row"},r,m,a);i&&r.setAttribute("aria-labelledby",`${e}-label`);const h=i?this.blocked(t,f,`${e}-label`):this.labelled(t,f,e),y=()=>{document.activeElement!==r&&u(c())};return y(),{spec:t,wrapper:this.wrap(t,h),shown:!1,sync:y}}choiceControl(t){const e=`${this.id}-${t.key}`,s=()=>Y(this.params[t.key],t.default),i=g("select",{class:"select",attrs:{id:e}}),o=()=>{const a=os(t,this.context);i.replaceChildren();for(const c of a)i.appendChild(g("option",{value:c.value,text:sa(c,this.context),...c.hint===void 0?{}:{title:c.hint}}));const l=s();a.some(c=>c.value===l)||i.appendChild(g("option",{value:l,text:`${l} — not available on this file`,attrs:{disabled:""}}))};i.addEventListener("change",()=>this.commit(t.key,i.value));const r=()=>{i.value=s()};return o(),r(),{spec:t,wrapper:this.wrap(t,this.labelled(t,i,e)),shown:!1,sync:r,refill:o}}toggleControl(t){const e=`${this.id}-${t.key}-label`,s=g("button",{class:"btn btn-toggle",type:"button",text:"on",title:t.hint??t.label});s.setAttribute("aria-labelledby",e),s.addEventListener("click",()=>{const o=this.params[t.key];this.commit(t.key,!(typeof o=="boolean"?o:t.default))});const i=()=>{const o=typeof this.params[t.key]=="boolean"?this.params[t.key]:t.default;s.setAttribute("aria-pressed",String(o)),s.textContent=o===!0?"on":"off"};return i(),{spec:t,wrapper:this.wrap(t,this.named(t,g("div",{class:"plot-icon-row"},s),e)),shown:!1,sync:i}}entrySelect(t){const e=`${this.id}-${t.key}`,s=g("select",{class:"select",attrs:{id:e}}),i=()=>{const r=Pt(t,this.context);s.replaceChildren(),t.optional===!0&&s.appendChild(g("option",{value:"",text:t.noneLabel??"none"}));for(const a of r)s.appendChild(g("option",{value:a.id,text:a.label}));r.length===0&&t.optional!==!0&&s.appendChild(g("option",{value:"",text:"nothing loaded"})),s.disabled=r.length===0};s.addEventListener("change",()=>this.commit(t.key,s.value===""?t.optional===!0?"":null:s.value));const o=()=>{s.value=Y(this.params[t.key],"")};return i(),o(),{spec:t,wrapper:this.wrap(t,this.labelled(t,s,e)),shown:!1,sync:o,refill:i}}entryList(t){const e=`${this.id}-${t.key}-label`,s=g("div",{class:"ann-list param-checks"});let i=[];const o=()=>{const l=this.params[t.key];return Array.isArray(l)?l.filter(c=>typeof c=="string"):[]},r=()=>{const l=Pt(t,this.context);s.replaceChildren(),i=l.map(c=>{const u=g("input",{class:"checkbox",type:"checkbox"});return u.addEventListener("change",()=>this.commit(t.key,i.filter(d=>d.input.checked).map(d=>d.id))),s.appendChild(g("label",{class:"ann-head param-check"},u,g("span",{text:c.label}))),{id:c.id,input:u}}),l.length===0&&s.appendChild(g("div",{class:"hint",text:"nothing loaded"}))},a=()=>{const l=new Set(o());for(const c of i)c.input.checked=l.has(c.id)};return r(),a(),{spec:t,wrapper:this.wrap(t,this.blocked(t,s,e)),shown:!1,sync:a,refill:r}}sequenceList(t){const e=`${this.id}-${t.key}-label`,s=g("div",{class:"ann-list param-checks param-sequences"}),i=g("span",{class:"hint param-check-count"});let o=[];const r=()=>{const d=this.params[t.key];return Array.isArray(d)?d.filter(m=>typeof m=="string"):[]},a=()=>{this.commit(t.key,o.filter(d=>d.input.checked).map(d=>d.name))},l=()=>{s.replaceChildren(),o=this.context.contigs.map(d=>{const m=g("input",{class:"checkbox",type:"checkbox"});return m.addEventListener("change",a),s.appendChild(g("label",{class:"ann-head param-check"},m,g("span",{text:d.name}),g("span",{class:"hint param-check-note",text:q.bp(d.length)}))),{name:d.name,input:m}}),o.length===0&&s.appendChild(g("div",{class:"hint",text:"this file has no sequences"}))},c=()=>{const d=new Set(r());for(const m of o)m.input.checked=d.has(m.name);i.textContent=o.length===0?"":`${q.int(d.size)} of ${q.int(o.length)} ticked`},u=g("div",{class:"param-check-actions"},N("all",()=>this.commit(t.key,this.context.contigs.map(d=>d.name)),{class:"btn btn-quiet",title:"Tick every sequence"}),N("none",()=>this.commit(t.key,[]),{class:"btn btn-quiet",title:"Untick every sequence"}),i);return l(),c(),{spec:t,wrapper:this.wrap(t,this.blocked(t,g("div",{},u,s),e)),shown:!1,sync:c,refill:()=>{l(),c()}}}columnControl(t){const e=`${this.id}-${t.key}`,s=g("select",{class:"select",attrs:{id:e}});let i=null;const o=()=>{const a=ls(t,this.context,this.params),l=`${a?.id??""}:${a?.payload?.data.length??0}`;if(l===i)return;i=l;const c=as(a);s.replaceChildren(),t.optional===!0&&s.appendChild(g("option",{value:"",text:t.noneLabel??"none"}));for(const u of c)s.appendChild(g("option",{value:u,text:u}));this.params[t.key]=cs(t,this.context,this.params),s.value=Y(this.params[t.key],"")};s.addEventListener("change",()=>this.commit(t.key,s.value===""?t.optional===!0?"":null:s.value));const r=()=>{s.value=Y(this.params[t.key],"")};return o(),r(),{spec:t,wrapper:this.wrap(t,this.labelled(t,s,e)),shown:!1,sync:r,refill:o}}locusControl(t){const e=`${this.id}-${t.key}`,s=`${e}-sequences`,i=g("datalist",{attrs:{id:s}}),o=g("input",{class:"input input-region param-region",type:"text",attrs:{id:e,list:s},placeholder:sn(this.context),title:vn("metacool")?"A contig, or a contig and a span. Coordinates are 1-based and inclusive, as IGV and samtools write them. On a metagenome a genome name is one too, and means the whole of it.":"A sequence, or a sequence and a span. Coordinates are 1-based and inclusive, as IGV and samtools write them."}),r=g("p",{class:"hint param-map-note hidden"}),a=t.pickable===!0&&this.context.hasMap,l=a?N("pick on map",()=>we()?si():Xs(),{class:"btn btn-toggle param-pick",title:"Then Shift-drag along either axis of the map. That gesture normally zooms; while this is lit it names this locus instead, once."}):null,c=()=>{i.replaceChildren(...(this.context.genomes??[]).map(m=>g("option",{value:m.name})),...this.context.contigs.map(m=>g("option",{value:m.name})))},u=()=>this.commit(t.key,o.value.trim());o.addEventListener("change",u),o.addEventListener("keydown",m=>{m.key==="Enter"&&u()});const d=()=>{if(l!==null){const m=we();l.setAttribute("aria-pressed",String(m)),l.textContent=m?"pointing…":"pick on map",r.classList.toggle("hidden",!m),r.textContent=m?"Shift-drag along either axis of the map. Escape to stop.":""}document.activeElement!==o&&(o.value=Y(this.params[t.key],""))};if(a){let m=ke();this.teardown.push(Js(()=>{const f=ke();f!==null&&f!==m&&(m=f,this.commit(t.key,f.whole===!0?f.contig:ce(f))),d()}))}return c(),d(),{spec:t,wrapper:this.wrap(t,this.labelled(t,g("div",{class:"param-locus"},o,i,...l===null?[]:[l]),e),r),shown:!1,sync:d,refill:()=>{c(),d()}}}fileControl(t){const e=`${this.id}-${t.key}-label`,s=`${this.id}-${t.key}`,i=g("span",{class:"ann-drop-label"}),o=g("span",{class:"ann-drop-hint"}),r=g("div",{class:"ann-drop param-drop",attrs:{tabindex:"0",role:"button","aria-labelledby":e}},i,o),a=J("x","Forget this file",()=>this.chooseFile(t,null),{class:"btn btn-icon param-drop-forget"}),l=g("input",{class:"input param-address",type:"text",attrs:{id:s,"aria-label":`${t.label}: address`},...t.placeholder===void 0?{}:{placeholder:t.placeholder}}),c=g("p",{class:"hint param-file-note hidden"}),u=b=>{c.textContent=b,c.classList.toggle("hidden",b==="")},d=b=>{if(!en(t,b.name)){u(`${b.name} is not a ${t.accept.join(" or ")} file.`);return}u(""),this.chooseFile(t,{value:b.name,source:{kind:"local",file:b},size:b.size})},m=()=>{ei({multiple:!1}).then(b=>{b.length>0&&d(b[0])})};r.addEventListener("click",m),r.addEventListener("keydown",b=>{b.key!=="Enter"&&b.key!==" "||(b.preventDefault(),m())}),r.addEventListener("dragover",b=>{!Qs(b)&&!ve(b)||(b.preventDefault(),r.classList.add("over"))}),r.addEventListener("dragleave",b=>{b.relatedTarget instanceof Node&&r.contains(b.relatedTarget)||r.classList.remove("over")}),r.addEventListener("drop",b=>{if(b.preventDefault(),b.stopPropagation(),r.classList.remove("over"),ve(b)){js(b).then(p=>{if(p===null)return;const w=p.name??p.uri.split(/[\\/]/).pop()??p.uri;if(!en(t,w)){u(`${w} is not a ${t.accept.join(" or ")} file.`);return}u(""),this.chooseFile(t,{value:p.source.kind==="local"?p.source.file.name:p.uri,source:p.source,name:w,...p.source.kind==="local"?{size:p.source.file.size}:{}})});return}const k=ti(b.dataTransfer);k.length>0&&d(k[0])});const f=()=>{const b=l.value.trim();if(b!==""&&!kt(b)){u("An address starts with https:// or s3:// — a file on this computer is dropped above.");return}u(""),this.shelf.set(t.key,null),this.commit(t.key,b)};l.addEventListener("change",f),l.addEventListener("keydown",b=>{b.key==="Enter"&&(b.preventDefault(),f())});const h=()=>{const b=Y(this.params[t.key],"").trim(),k=this.shelf.get(t.key),p=k!==void 0&&k.value===b&&b!==""&&!kt(b),w=k!==void 0&&k.value===b&&kt(b);r.classList.toggle("is-held",p||w),p||w?(i.textContent=k.name??(p?b:b.split(/[\\/]/).pop()??b),o.textContent=k.size===void 0?"drop or click to choose another":`${q.bytes(k.size)} · drop or click to choose another`):(i.textContent=t.prompt,o.textContent=t.accept.join(" or ")),a.classList.toggle("hidden",!(p||w)),document.activeElement!==l&&(l.value=p||w?"":b)};h();const y=g("div",{class:"param-file"},g("div",{class:"param-file-row"},r,a),l);return{spec:t,wrapper:this.wrap(t,this.named(t,y,e),c),shown:!1,sync:h}}chooseFile(t,e){this.shelf.set(t.key,e);const s=e?.value??"";if(oe(this.params[t.key],s)){for(const i of this.controls)i.sync();this.options.onChange(this.value);return}this.commit(t.key,s)}textControl(t){const e=`${this.id}-${t.key}`,s=g("input",{class:"input",type:"text",attrs:{id:e},...t.placeholder===void 0?{}:{placeholder:t.placeholder},style:{width:"100%"}}),i=()=>this.commit(t.key,s.value.trim());s.addEventListener("change",i),s.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),i())});const o=()=>{document.activeElement!==s&&(s.value=Y(this.params[t.key],""))};return o(),{spec:t,wrapper:this.wrap(t,this.labelled(t,s,e)),shown:!1,sync:o}}seedControl(t){const e=`${this.id}-${t.key}`,s=g("input",{class:"input input-num input-step",type:"number",attrs:{id:e,size:"1",step:"1",min:"0"}}),i=()=>nn(this.params[t.key],t.default),o=()=>{const l=Number(s.value);if(!Number.isFinite(l)){s.value=String(i());return}const c=Math.max(0,Math.trunc(l));s.value=String(c),this.commit(t.key,c)};s.addEventListener("change",o),s.addEventListener("keydown",l=>{l.key==="Enter"&&o()});const r=J("rotate-cw","Roll a new seed — the same seed gives the same numbers, a new one resamples",()=>{const l=ga(i());s.value=String(l),this.commit(t.key,l)},{class:"btn btn-icon",size:14}),a=()=>{document.activeElement!==s&&(s.value=String(i()))};return a(),{spec:t,wrapper:this.wrap(t,this.labelled(t,g("div",{class:"plot-icon-row"},s,r),e)),shown:!1,sync:a}}}const mt="\0all-maps",re="chromosomix:analysis-drawer:width",va=380,wa=.75,ka=.95,xa=300;let Sa=0;function Ma(){try{const n=window.localStorage.getItem(re);if(n===null)return null;const t=Number(n);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function on(n){try{n===null?window.localStorage.removeItem(re):window.localStorage.setItem(re,String(Math.round(n)))}catch{}}function $a(n){if(n===null)return!0;const t=typeof n;return t==="number"||t==="string"||t==="boolean"?!0:Array.isArray(n)&&n.every(e=>typeof e=="string")}function pt(n){return n===null?"":n.memoryKey??n.uri}function Ea(n,t){const e={...qt(n.params)},s=Sn(t,n.id);if(s===null)return e;for(const i of n.params){const o=s[i.key];$a(o)&&(e[i.key]=o)}return e}function Ta(n){const t=[n.note.replace(/\.\s*$/,"")];return n.requests!==null&&n.requests>0&&t.push(`${q.int(n.requests)} request${n.requests===1?"":"s"}`),n.bytes!==null&&n.bytes>0&&t.push(q.bytes(n.bytes)),t.join(" · ")}function Ca(n,t){return Ln(n,{params:n.params,framing:t})}function Aa(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?!0:n instanceof HTMLInputElement?!["button","checkbox","radio","range","submit","reset"].includes(n.type):n.isContentEditable}function ae(n){return pi(n.provenance.createdAt)}function Na(n,t,e){if(n===t)return"The run on screen";const s=[];for(const o of e.params){const r=n.provenance.params[o.key],a=t.provenance.params[o.key];Tt(r)!==Tt(a)&&s.push(`${o.label}: ${Tt(r)} (latest: ${Tt(a)})`)}const i=`Finished ${ae(n)}.`;return s.length===0?`${i} The same parameters as the latest run.`:`${i} ${s.join(" · ")}`}function Tt(n){return n==null||n===""?"—":Array.isArray(n)?n.length===0?"—":n.join(", "):String(n)}function rn(n){return n.mapless===!0?"the sequences chosen":"the loaded tracks"}function La(n){switch(n.status){case"running":return[g("span",{class:"analysis-spinner",attrs:{"aria-hidden":"true"}}),n.note===""?"working":n.note];case"queued":return["waiting for the job in front of it"];case"failed":return[g("span",{class:"inline-error",text:n.message})];default:return[]}}function le(n){const t=n.getBoundingClientRect();return{width:Math.max(1,Math.round(t.width)),height:Math.max(1,Math.round(t.height))}}function Zt(n){const t=le(n.el),e=bi(xa),s=document.createElement("canvas");s.width=Math.max(1,Math.round(t.width*e)),s.height=Math.max(1,Math.round(t.height*e));const i=s.getContext("2d");if(i===null)throw new Error("The browser would not give this page a canvas.");return i.setTransform(e,0,0,e,0,0),n.draw(i,t),s}function Oa(n){const t=n.split("::")[0];return(t.split(/[\\/]/).pop()??t).split("?")[0].split("#")[0].replace(/\..*$/,"")||"map"}function an(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"figure"}function Ct(n,t,e,s){return yt(t.task,n,e).replace(/\.tsv$/,`.${s}`)}class Ia{constructor(t){this.options=t;const e=`analysis-drawer-${Sa++}`;this.titleEl.id=`${e}-title`,this.recomputeButton=N("recompute here",()=>this.run(),{class:"btn btn-quiet",title:"Take a new snapshot of the framing and run again. The result on screen is a record of the view it was computed from, so it is left as it is until this finishes."}),this.runButton=N("run",()=>this.run(),{class:"btn"}),this.runAllButton=N("run on all maps",()=>this.runAll(),{class:"btn hidden",title:"Run this task once per map on screen, one after another. Each result is filed against the map it was measured from, so a batch leaves a row per panel."}),this.cancelButton=N("cancel",()=>this.cancel(),{class:"btn"}),this.cliButton=N("copy CLI command",()=>this.copyCliCommand(),{class:"btn"}),this.progressEl=g("div",{class:"analysis-progress"},this.progressFill),this.recordEl=g("div",{class:"plot-icon-row hidden"},this.recordNote,N("copy provenance",()=>this.copyProvenance(),{class:"btn",title:"The task, its version, every parameter, the framing, the file and the build — the same lines every export carries at its head."}),this.cliButton,this.documentsEl),this.el=g("div",{class:"analysis-drawer collapsed",attrs:{role:"region","aria-labelledby":this.titleEl.id}},g("div",{class:"analysis-drawer-head"},this.titleEl,this.framingEl,this.recomputeButton,J("x","Close the drawer. Anything running keeps running — the panel row says so.",()=>this.close(),{class:"btn-close",size:14})),g("div",{class:"analysis-drawer-body"},this.formSlot,g("div",{class:"analysis-run"},this.runButton,this.runAllButton,this.cancelButton,this.costEl,this.progressEl),this.noteEl,this.recordEl,this.notesEl,this.mapsEl,this.runsEl,this.outputsEl,this.statusEl),this.handle()),this.unsubscribe=t.runner.subscribe(()=>this.refresh()),window.addEventListener("keydown",this.onKeyDown)}el;titleEl=g("h2",{class:"analysis-drawer-title"});framingEl=g("span",{class:"analysis-framing"});recomputeButton;formSlot=g("div",{class:"analysis-form"});runButton;runAllButton;cancelButton;costEl=g("span",{class:"analysis-cost"});progressFill=g("div",{class:"analysis-progress-fill"});progressEl;noteEl=g("div",{class:"analysis-note hidden"});recordEl;recordNote=g("span",{class:"analysis-note"});documentsEl=g("span",{class:"analysis-documents"});notesEl=g("ul",{class:"analysis-notes hidden"});outputsEl=g("div",{style:{display:"flex",flexDirection:"column",gap:"0.8rem"}});mapsEl=g("div",{class:"analysis-maps hidden"});runsEl=g("div",{class:"analysis-runs hidden"});statusEl=g("div",{class:"analysis-note hidden"});unsubscribe;current=null;form=null;params={};figures=[];surfaceSlots=[];drawn=null;cliButton;chosenMap=new Map;chosenRun=new Map;combined=!1;across=null;width=Ma();show(t){if(t!==null&&this.current!==null&&t.id===this.current.id){this.refresh();return}if(this.teardown(),this.current=t,t===null){this.el.classList.add("collapsed");return}this.params=qt(t.params),this.el.classList.remove("collapsed"),this.paintWidth(),this.refresh()}get task(){return this.current}get isOpen(){return this.current!==null}context(){return this.options.context(this.current??void 0)}paintRun(t,e){if(!Q(t)){this.runButton.replaceChildren("run"),this.runButton.title=`Run ${t.title} on ${rn(t)}`+(e<2?".":" — it reads no map, so it runs once, whichever map is starred.");return}const s=e<2?null:this.options.runner.target();if(s===null){this.runButton.replaceChildren("run"),this.runButton.title=`Run ${t.title} on the open map.`;return}this.runButton.replaceChildren("run on ",xe("star",{size:12,class:"run-star"})),this.runButton.title=`Run ${t.title} on ${s.label} — the starred map, which is the one every task measures. Move the star in a panel’s heading to measure another, or run on all of them.`}refresh(){const t=this.current;if(t===null)return;const e=this.context();this.titleEl.textContent=t.title,this.syncForm(t,e);const s=this.options.runner.resultsFor(t.id);this.syncMaps(t,s);const i=this.chosenMap.get(t.id),o=i===mt&&s.length>1,r=i===void 0||i===mt?void 0:i,a=r===void 0?[]:this.options.runner.runsOf(t.id,r),l=o?[]:a.length>0?a:this.options.runner.runsOf(t.id),c=Math.min(Math.max(0,this.chosenRun.get(t.id)??0),Math.max(0,l.length-1)),u=o?null:l[c]??null;this.syncRuns(t,l,c),o?this.syncCombined(s):this.syncOutputs(u),this.syncFraming(u??s[0]?.result??null),this.syncRun(t,e)}relayout(){this.current!==null&&this.paintWidth()}destroy(){this.unsubscribe(),window.removeEventListener("keydown",this.onKeyDown),this.teardown(),this.el.remove()}onKeyDown=t=>{if(t.key!=="Escape"||t.defaultPrevented||this.current===null)return;const e=document.activeElement;e instanceof HTMLElement&&this.el.contains(e)&&Aa(e)||(t.preventDefault(),this.close())};close(){this.show(null),this.options.onClose()}teardown(){this.form?.destroy(),this.form=null,this.clearFigures(),this.outputsEl.replaceChildren(),this.notesEl.replaceChildren(),this.notesEl.classList.add("hidden"),this.recordEl.classList.add("hidden"),this.formSlot.replaceChildren(),this.setStatus(""),this.drawn=null,this.params={}}setStatus(t){this.statusEl.textContent=t,this.statusEl.classList.toggle("hidden",t==="")}clearFigures(){for(const t of this.figures)t.destroy();this.figures=[]}handle(){return ai({side:"right",what:"Analysis drawer",width:()=>this.widthNow(),resize:t=>{this.width=t,this.paintWidth()},commit:()=>on(this.widthNow()),reset:()=>{this.width=null,on(null),this.paintWidth()}})}bodyWidth(){const e=(this.el.closest(".app-body")??this.el.parentElement)?.getBoundingClientRect().width??0;return e>0?e:window.innerWidth}widthNow(){const t=this.bodyWidth(),e=Math.round(t*ka),s=Math.min(va,e);return Math.max(s,Math.min(e,this.width??Math.round(t*wa)))}paintWidth(){this.el.style.width=`${this.widthNow()}px`}syncForm(t,e){if(e===null)return;if(this.form!==null){this.form.setContext(e);return}this.params=Ea(t,pt(e));const s=this.options.runner,i=new ya({specs:t.params,context:e,value:this.params,onChange:o=>this.onParams(o),files:{get:o=>s.heldFile(t.id,o),set:(o,r)=>s.holdFile(t.id,o,r)}});this.form=i,this.params=i.value,this.formSlot.replaceChildren(i.el)}onParams(t){this.params=t;const e=this.current,s=this.context();e===null||s===null||(Xt(pt(s),e.id,t),this.syncRun(e,s))}blockedFor(t){return Q(t)?this.options.blocked?.()??null:null}run(){const t=this.current;t!==null&&this.blockedFor(t)===null&&(this.setStatus(""),this.chosenRun.delete(t.id),this.options.runner.run(t,this.seeded(t)),this.refresh())}seeded(t){const e=this.context();return e===null?this.params:(Xt(pt(e),t.id,this.params),li(t.params,e,this.params))}runAll(){const t=this.current;t!==null&&this.blockedFor(t)===null&&(this.setStatus(""),this.chosenRun.delete(t.id),this.runAllButton.disabled=!0,this.options.runner.readyTargets().then(e=>{this.current===t&&this.options.runner.runAll(t,this.seeded(t),e)}).finally(()=>this.refresh()))}cancel(){this.current!==null&&this.options.runner.cancel(this.current.id)}syncRun(t,e){const s=this.options.runner.stateOf(t.id),i=s.status==="running"||s.status==="queued",o=e===null?null:t.estimate(e,this.params),r=this.blockedFor(t),a=r!==null?r:e===null?"This view has no contact map to run against.":o!==null&&o.refusal!==void 0&&o.refusal!==""?o.refusal:null;this.runButton.disabled=i||a!==null;const l=this.options.runner.targetCount();this.paintRun(t,l),this.runAllButton.classList.toggle("hidden",l<2||!Q(t)),this.runAllButton.disabled=i||a!==null,this.runAllButton.textContent=`run on all ${l} maps`,a!==null?(this.costEl.className="analysis-refusal",this.costEl.textContent=a):(this.costEl.className=o!==null&&o.class==="scan"?"analysis-cost is-scan":"analysis-cost",this.costEl.textContent=o===null?"":Ta(o)),this.cancelButton.classList.toggle("hidden",!i),this.cancelButton.title=`Stop this job. ${is(t.venue)}`;const c=s.status==="running"&&s.total>0;this.progressEl.classList.toggle("hidden",!c),c&&s.status==="running"&&(this.progressFill.style.width=`${Math.min(100,s.done/s.total*100).toFixed(1)}%`);const u=La(s);this.noteEl.replaceChildren(...u),this.noteEl.classList.toggle("hidden",u.length===0)}syncMaps(t,e){if(e.length<2){this.mapsEl.classList.add("hidden"),this.mapsEl.replaceChildren(),this.chosenMap.delete(t.id);return}const s=[...e.map(a=>a.target.map),mt],i=this.chosenMap.get(t.id)??s[0],o=a=>{this.chosenMap.set(t.id,a),this.chosenRun.delete(t.id),this.drawn=null,this.refresh()},r=a=>{const l=s.indexOf(i);o(s[(l+a+s.length)%s.length])};this.mapsEl.classList.remove("hidden"),this.mapsEl.replaceChildren(J("chevron-left","The previous map",()=>r(-1),{class:"btn-quiet"}),...e.map(a=>N(a.target.label,()=>o(a.target.map),{class:`btn btn-quiet analysis-map${a.target.map===i?" is-on":""}`,title:`The result measured on ${a.target.label}`})),N("all maps",()=>o(mt),{class:`btn btn-quiet analysis-map${i===mt?" is-on":""}`,title:"Every map’s curves on one axis and every map’s tables as one — the comparison the deck was opened for"}),J("chevron-right","The next map",()=>r(1),{class:"btn-quiet"}))}syncRuns(t,e,s){if(e.length<2){this.runsEl.classList.add("hidden"),this.runsEl.replaceChildren();return}const i=l=>{this.chosenRun.set(t.id,Math.max(0,Math.min(e.length-1,l))),this.drawn=null,this.refresh()},o=N("older",()=>i(s+1),{class:"btn btn-quiet",title:"The run before this one, with the figures it produced"});o.disabled=s>=e.length-1;const r=N("newer",()=>i(s-1),{class:"btn btn-quiet",title:"Back towards the most recent run"});r.disabled=s<=0;const a=N("latest",()=>i(0),{class:"btn btn-quiet",title:"The most recent run of this task"});a.disabled=s===0,this.runsEl.classList.remove("hidden"),this.runsEl.replaceChildren(xe("rotate-cw",{size:13,class:"analysis-runs-mark"}),o,g("span",{class:"analysis-run-at",text:s===0?`latest of ${e.length} runs`:`run ${e.length-s} of ${e.length} · ${ae(e[s])}`,title:Na(e[s],e[0],t)}),r,a)}syncCombined(t){this.drawn=null,this.combined=!0,this.clearFigures(),this.setStatus(""),this.notesEl.classList.add("hidden"),this.recordEl.classList.remove("hidden"),this.recordNote.textContent=`${t.length} maps, together`;const{outputs:e,perMapOnly:s}=fo(t.map(a=>({label:a.target.label,result:a.result})),a=>a.kind==="curve"?a:a.kind==="profile"?gi(a):null),i=t.map(a=>({label:a.target.label,provenance:a.target.uri===""||a.target.uri===a.result.provenance.framing.uri?a.result.provenance:{...a.result.provenance,framing:{...a.result.provenance.framing,uri:a.target.uri}}}));this.across=i;const o=i[0];o!==void 0&&this.paintCli(o.provenance);const r=e.map(a=>this.combinedBlock(a,i));s.length>0&&r.push(g("p",{class:"analysis-elsewhere",text:`${s.join(", ")} ${s.length===1?"is":"are"} one picture per map rather than one across them — a pileup averaged over four libraries would be a fifth thing nobody asked for. They are on the tabs above.`})),r.length===0&&r.push(g("p",{class:"analysis-elsewhere",text:"Nothing this task produces can be drawn across maps. Its tabs are above."})),this.outputsEl.replaceChildren(...r),this.paintWidth()}combinedBlock(t,e){const s=Ze({output:t,task:`${this.current?.id??"task"}:combined`,uri:pt(this.context()),extras:[N("TSV",()=>this.saveCombinedTsv(t,e),{class:"btn",title:"The numbers of every map as one table, with each map’s provenance above them — the file, the framing and the settings every row was measured with."})],onPng:i=>void this.savePngPlain(i,t.label),onPdf:i=>void this.savePdfPlain(i,t.label),onCopy:i=>this.copyPng(i,t.label)});return this.figures.push(s),s.el}saveCombinedTsv(t,e){const s=W(new Date),i=new Blob([...ci(t,e)],{type:"text/tab-separated-values"});X(i,yt(this.current?.id??"task",t,s))}syncFraming(t){const e=this.options.framing();if(this.current!==null&&!Q(this.current)){const s=rn(this.current);this.framingEl.className="analysis-framing",this.framingEl.textContent=t===null?`reads ${s}, not the map`:`from ${s}, not the map`,this.framingEl.title="",this.recomputeButton.classList.add("hidden");return}if(t!==null){const s=t.provenance,i=e!==null&&!Ca(s,e);this.framingEl.className=i?"analysis-framing is-stale":"analysis-framing",this.framingEl.textContent=i?`from ${s.framing.label} — the view has moved since`:`from ${s.framing.label}`,this.framingEl.title=s.framing.label,this.recomputeButton.classList.toggle("hidden",!i);return}this.framingEl.className="analysis-framing",this.framingEl.textContent=e===null?"no contact map in this view":`will run on ${e.label}`,this.framingEl.title=e?.label??"",this.recomputeButton.classList.add("hidden")}syncOutputs(t){if(t===this.drawn&&!this.combined)return;if(this.combined=!1,this.across=null,this.drawn=t,this.clearFigures(),this.setStatus(""),t===null){this.outputsEl.replaceChildren(),this.notesEl.replaceChildren(),this.notesEl.classList.add("hidden"),this.recordEl.classList.add("hidden");return}const e=t.provenance;this.recordEl.classList.remove("hidden"),this.recordNote.textContent=`computed in ${kn(t.ms)} at ${ae(t)}`,this.recordNote.title=e.createdAt,this.paintCli(e),this.paintDocuments(t),this.notesEl.replaceChildren(...t.notes.map(s=>g("li",{text:s}))),this.notesEl.classList.toggle("hidden",t.notes.length===0),this.outputsEl.replaceChildren(...t.outputs.length===0?[g("p",{class:"analysis-elsewhere",text:t.notes.length===0?"This run produced no output, and said nothing about why. That is a bug — please report it.":"No output was produced. The reason is above."})]:this.outputBlocks(t.outputs,e))}outputBlocks(t,e){const s=[];let i=null;const o=()=>{i!==null&&(s.push(this.elsewhere(i.where,i.items,e)),i=null)};for(const r of t){const a=this.elsewhereOf(r);a===null?(o(),s.push(this.block(r,e))):i!==null&&i.where===a?i.items.push(r):(o(),i={where:a,items:[r]})}return o(),s}elsewhereOf(t){return t.kind==="intervals"?t.entryKind==="structure"?"structure":this.options.hasLanes()?"overlay":"loose":t.kind==="profile"&&this.options.hasLanes()?"lane":null}block(t,e){const s=Ze({output:t,task:this.current?.id??"task",uri:pt(this.context()),extras:[...t.kind==="profile"?this.profileButtons(t,e):[],this.tsvButton(t,e)],onPng:i=>void this.savePng(i,t,e),onPdf:i=>void this.savePdf(i,t,e),onCopy:i=>this.copyPng(i,t.label)});return this.figures.push(s),s.el}profileButtons(t,e){const s=i=>{this.options.writeProfile(t,e,i).catch(o=>{this.setStatus(o instanceof Error?o.message:String(o))})};return[N("bigWig",()=>s("bigwig"),{class:"btn",title:"Written here, byte for byte — no bedGraphToBigWig step. What IGV, deepTools and pyBigWig open."}),N("bedGraph",()=>s("bedgraph"),{class:"btn",title:"One line per bin that has a value; bins with none are omitted, never written as 0."})]}elsewhere(t,e,s){const i=e.length>1,o=t==="lane"?i?`${q.int(e.length)} tracks added to the Tracks card in the Annotations panel, marked *.`:"Added to the Tracks card in the Annotations panel, marked *.":t==="structure"?"Added to the Structures card in the Annotations panel, and shown in a structure cell of its own, beside what the deck already shows.":t==="overlay"&&this.context()?.hasMap===!1?i?`${q.int(e.length)} sets added to the Tracks card in the Annotations panel as 1D tracks, marked *.`:"Added to the Tracks card in the Annotations panel as a 1D track, marked *.":t==="overlay"?i?`${q.int(e.length)} sets added to the Tracks card in the Annotations panel, marked *.`:"Added to the Tracks card in the Annotations panel, marked *.":"This file carries no annotation layer, so there is no overlay to draw these on. Take them as a BED, which this app reads back on any file that has one.";return g("div",{class:"analysis-elsewhere"},g("span",{text:o}),...e.map(r=>g("div",{class:"plot-icon-row"},g("span",{class:"analysis-elsewhere-name",text:r.label,title:r.label}),...r.kind==="intervals"?[this.bedButton(r,s)]:[],...r.kind==="intervals"&&r.entryKind==="structure"?[this.pdbButton(r,s)]:[],this.tsvButton(r,s))).flatMap((r,a)=>{const l=e[a];if(l.kind!=="intervals"||l.entryKind==="structure")return[r];const c=g("div",{class:"analysis-surfaces"});return this.surfaceSlots.push({slot:c,output:l}),this.fillSurface(c,l),[r,c]}))}fillSurfaces(){this.surfaceSlots=this.surfaceSlots.filter(({slot:t})=>t.isConnected);for(const{slot:t,output:e}of this.surfaceSlots)t.contains(document.activeElement)||this.fillSurface(t,e)}fillSurface(t,e){const s=this.options.surfaces?.(e)??null;t.replaceChildren(...s===null?[]:[s])}bedButton(t,e){const s=t.entryKind==="structure",i=s?"bed3d":t.payload.kind==="pairs"?"BEDPE":"BED";return N(i,()=>this.saveIntervals(t,e),{class:"btn",title:s?"The model as a bed3d — chrom, start, end, x, y, z — which this app and g3dtools read back":`The called intervals as a ${i} — what bedtools reads, and what this app reads back`})}saveIntervals(t,e){const s=W(new Date),i={label:t.label,file:e.framing.label,created:e.createdAt},o=t.payload,r=t.entryKind==="structure"&&o.kind==="features",a=r&&o.kind==="features"?xn(o.data,i):Jt(o,i),l=r?"bed3d":o.kind==="pairs"?"bedpe":"bed";X(new Blob([a],{type:"text/plain"}),Ct(t,e,s,l))}pdbButton(t,e){const s=t.payload,i=s.kind==="features"?ui(s.data):"This output holds no model.",o=N("PDB",()=>this.savePdb(t,e),{class:"btn",title:i??"The model as a PDB — an atom per bead, a chain per sequence, bonds along the fibre — which PyMOL and ChimeraX open and this app reads back"});return o.disabled=i!==null,o}savePdb(t,e){const s=t.payload;if(s.kind!=="features")return;const i=di(s.data,{label:t.label,file:e.framing.label,created:e.createdAt});X(new Blob([i],{type:"text/plain"}),Ct(t,e,W(new Date),"pdb"))}tsvButton(t,e){return N("TSV",()=>this.saveTsv(t,e),{class:"btn",title:"The numbers as a table, with the provenance above them — what makes a figure checkable by the person reading it."})}saveTsv(t,e){const s=W(new Date),i=new Blob([...Qt(t,e)],{type:"text/tab-separated-values"});X(i,yt(e.task,t,s))}copyPng(t,e){let s;try{s=Zt(t)}catch(i){this.setStatus(i instanceof Error?i.message:String(i));return}hi(Vt(s)).then(()=>{this.setStatus(""),fi(`Copied ${e} · ${s.width} × ${s.height} px`)},i=>this.setStatus(`${e} could not be copied: ${i instanceof Error?i.message:String(i)}`))}async savePngPlain(t,e){const s=await ct(`${an(e)}-${W(new Date)}.png`,"image/png");if(s!==null)try{await s.write(await Vt(Zt(t))),this.setStatus("")}catch(i){this.setStatus(i instanceof Error?i.message:String(i))}}async savePdfPlain(t,e){const s=new Date,i=await ct(`${an(e)}-${W(s)}.pdf`,"application/pdf");if(i!==null)try{const o=le(t.el),r=new Se(o.width,o.height);t.draw(r.ctx,o);const a=await r.toBlob({title:e,created:s});await i.write(a),this.setStatus("")}catch(o){this.setStatus(o instanceof Error?o.message:String(o))}}async savePng(t,e,s){const i=await ct(Ct(e,s,W(new Date),"png"),"image/png");if(i!==null)try{await i.write(await Vt(Zt(t))),this.setStatus("")}catch(o){this.setStatus(o instanceof Error?o.message:String(o))}}async savePdf(t,e,s){const i=new Date,o=await ct(Ct(e,s,W(i),"pdf"),"application/pdf");if(o!==null)try{const r=le(t.el),a=new Se(r.width,r.height);t.draw(a.ctx,r);const l=await a.toBlob({title:e.label,created:i});await o.write(l),this.setStatus("")}catch(r){this.setStatus(r instanceof Error?r.message:String(r))}}paintDocuments(t){const s=(bt(t.provenance.task)?.documents??[]).filter(i=>i.shellOnly!==!0);this.documentsEl.replaceChildren(...s.map(i=>N(i.label,()=>{const o=Oa(t.provenance.framing.uri),r=new Blob([i.write(t,o)],{type:i.type});X(r,`${o}.${t.provenance.task}.${i.id}-${W(new Date)}.${i.extension}`)},{class:"btn",title:"Every figure and table of this run on one page, with its notes and provenance, in a file that needs nothing beside it."})))}paintCli(t){const e=bt(t.task)===void 0;this.cliButton.disabled=e,this.cliButton.title=e?`This build does not have the task ${t.task}, so it cannot write its flags.`:"The same run as a chromosomix command line — the file, the window, the balancing and every parameter — for the other two hundred files."}shownProvenances(){return this.drawn!==null?[{label:null,provenance:this.drawn.provenance}]:(this.across??[]).map(t=>({label:t.label,provenance:t.provenance}))}copyCliCommand(){const t=this.shownProvenances(),e=t[0];if(e===void 0)return;const s=bt(e.provenance.task);if(s===void 0)return;const o=t.map(({label:a,provenance:l})=>{const c=Tn({task:s,provenance:l,context:this.options.context(s)}).text;return a===null?c:`# ${a}
8
+ ${c}`}).join(`
9
+
10
+ `),r=t.length>1?0:o.split(`
11
+ `).filter(a=>a.startsWith("#")).length;Me(o).then(()=>{this.setStatus(t.length>1?`${t.length} CLI commands copied, one per map.`:r===0?"CLI command copied.":`CLI command copied, with ${r} note${r===1?"":"s"} on what a shell cannot be told.`)},a=>{this.setStatus(a instanceof Error?a.message:String(a))})}copyProvenance(){const t=this.shownProvenances();if(t.length===0)return;const e=(this.drawn===null?mi(t.map(({label:s,provenance:i})=>({label:s??"",provenance:i}))):zt(t[0].provenance)).join(`
12
+ `);Me(e).then(()=>{this.setStatus("Provenance copied.")},s=>{this.setStatus(s instanceof Error?s.message:String(s))})}}function us(n){return Number.isInteger(n)?String(n):String(Number(n.toPrecision(7)))}function ds(n){return n!==void 0&&Number.isFinite(n)}function*Fa(n,t,e){yield*Mn(zt(e));const{values:s,extent:i,binsize:o}=n,r=new yi;for(const l of t)for(let c=0;c<l.bins;c++){const u=l.startBin+c;if(u<i[0]||u>=i[1])continue;const d=s[u-i[0]];if(!ds(d))continue;const m=c*o,f=Math.min(l.length,m+o);if(!(f>m))continue;const h=r.push(`${l.name} ${m} ${f} ${us(d)}`);h!==void 0&&(yield h)}const a=r.flush();a!==void 0&&(yield a)}function Pa(n,t,e){const s=zt(e),i=new Map;for(const o of n){const r=i.get(o.contig);r===void 0?i.set(o.contig,[o]):r.push(o)}for(const o of t){const r=i.get(o.name);if(r===void 0)continue;const a=[];for(const l of r)for(let c=0;c<l.starts.length;c+=1){const u=l.values[c];if(!ds(u))continue;const d=Math.max(0,l.starts[c]),m=Math.min(o.length,l.ends[c]);m>d&&a.push([d,m,u])}a.sort((l,c)=>l[0]-c[0]);for(const[l,c,u]of a)s.push(`${o.name} ${l} ${c} ${us(u)}`)}return Mn(s)}class Ra{constructor(t){this.host=t;const e={context:a=>this.host.context(a),source:a=>this.host.source(a),block:()=>this.host.block(),payload:a=>this.host.store()?.byId(a)?.payload,label:a=>this.host.store()?.byId(a)?.label,vector:a=>this.binVector(a),annotations:()=>this.host.annotations(),contigLengths:a=>{const l={};for(const c of this.host.contigs(a))l[c.name]=c.length;return l},...this.host.targetMap===void 0?{}:{targetMap:()=>this.host.targetMap?.()??Z},allTargets:()=>this.host.allTargets?.()??[],...this.host.allTargetsReady===void 0?{}:{allTargetsReady:()=>this.host.allTargetsReady?.()??Promise.resolve([])},...this.host.targetCount===void 0?{}:{targetCount:()=>this.host.targetCount?.()??0},finished:(a,l,c)=>this.adopt(a,l,c)};this.runner=new ao(e),this.panel=new jr({runner:this.runner,context:()=>this.host.context(),blocked:()=>this.host.blocked?.()??null,onOpen:a=>this.show(a),active:()=>this.open?.id??null}),this.panelEl=this.panel.el,this.drawer=new Ia({runner:this.runner,context:a=>this.host.context(a),blocked:()=>this.host.blocked?.()??null,framing:()=>this.host.framing(),onClose:()=>this.show(null),hasLanes:()=>this.laneable(),surfaces:a=>{const l=this.host.store();if(l===null)return null;for(const[c,u]of this.intervals){if(u.output!==a)continue;const d=l.byId(c);if(d!==void 0){const m=$e.find(f=>f.id===u.task);return vi(l,d,{map:this.host.context(m)?.hasMap??!0})}}return null},writeProfile:(a,l,c)=>this.writeProfile(a,l,c,this.gridFor(a.binsize))}),this.drawerEl=this.drawer.el;const s=t.store(),i=this.runner.subscribe(()=>{this.panel.refresh(),this.drawer.refresh()});let o=s===null?"":un(s);const r=s===null?()=>{}:s.subscribe(()=>{const a=un(s);a!==o&&(o=a,this.drawer.fillSurfaces());const l=cn(s);l!==this.entries&&(this.entries=l,this.refresh())});s!==null&&(this.entries=cn(s)),this.unsubscribe=()=>{i(),r()},this.adoptCarried(t.carried?.()??[])}panelEl;drawerEl;runner;panel;drawer;profiles=new Map;intervals=new Map;open=null;entries="";unsubscribe;get hasTasks(){const t=this.host.context();return t!==null&&yn(t).length>0}get isDrawerOpen(){return this.drawer.isOpen}get openTask(){return this.drawer.task?.id??null}runsOf(t){return this.runner.runsOf(t)}isRunning(t){const e=this.runner.stateOf(t).status;return e==="running"||e==="queued"}show(t){this.open=t,this.drawer.show(t),this.panel.refresh(),this.host.changed()}refresh(){this.panel.refresh(),this.drawer.refresh()}relayout(){this.drawer.relayout()}destroy(){this.unsubscribe(),this.panel.destroy(),this.drawer.destroy(),this.runner.destroy(),this.profiles.clear()}adopt(t,e,s){const i=s.map,o=e.provenance.framing.uri,r=this.host.context(t),a=this.host.memoryKey?.(o)??o;if(Xt(a,t.id,wi(t,e.provenance.params,Sn(a,t.id),r?.uri===o?r:null)),t.id==="cellqc"){const h=e.outputs.find(y=>y.kind==="table"&&y.id==="cellqc");h!==void 0&&this.host.cellMeasurements?.(e.provenance.framing.uri,h)}if(t.id==="oriter"){const h=ki(e.outputs);Object.keys(h).length>0&&this.host.originsFound?.(e.provenance.framing.uri,h)}const l=this.host.store(),c=e.outputs.filter(h=>h.kind==="profile"),u=e.outputs.filter(h=>h.kind==="intervals");if(c.length===0&&u.length===0)return;if(l!==null&&!this.laneable()){for(const h of u)this.adoptIntervals(t,e,h,l,s,null,!1);for(const h of c)this.profiles.set(ft(h.id),{output:h,provenance:e.provenance,task:t.id,grid:this.gridFor(h.binsize,t)});this.drawer.refresh(),this.host.changed();return}if(l===null){for(const h of u)this.intervals.set(`analysis:${t.id}:${h.id}`,{output:h,provenance:e.provenance,task:t.id});for(const h of c)this.profiles.set(ft(h.id),{output:h,provenance:e.provenance,task:t.id,grid:this.gridFor(h.binsize,t)});this.drawer.refresh();return}const m=[...c.map(h=>ft(h.id,i)),...u.map(h=>dn(t.id,h.id,i))].map(h=>l.byId(h)?.style.colour).find(h=>h!==void 0)??l.nextColour();for(const h of c){const y={kind:"computed",name:h.label,task:t.id,recipe:{taskVersion:e.provenance.taskVersion,params:e.provenance.params,framing:e.provenance.framing},framing:e.provenance.framing.label},b=xi(h,y,h.colour??m,s),k=l.byId(b.id)?.revision??0;if(h.group!==void 0&&h.groupMode!==void 0){const w=this.host.groups?.()??null,M=Si(h.group,s);w!==null&&!w.knowsMode(M)&&w.setMode(M,h.groupMode)}l.begin({card:"synthetic",kind:"track",id:b.id,label:b.label,source:y,placement:b.placement,style:b.style}),this.placeOnTarget(l,b.id,b.placement,i);const p=this.gridFor(h.binsize,t);this.profiles.set(b.id,{output:h,provenance:e.provenance,task:t.id,grid:p}),this.register(b.id,h,p),l.update(b.id,{status:"ready",...b.fileExtent===void 0?{}:{fileExtent:b.fileExtent},revision:k+1})}let f=c.length===0?null:ft(c[c.length-1].id,i);for(const h of u){const y=h.lane?.under,b=this.adoptIntervals(t,e,h,l,s,y===void 0?f:"output"in y?ft(y.output,i):y.entry,!0,m);y===void 0&&b!==null&&(f=b)}u.length>0&&this.drawer.fillSurfaces(),this.host.changed()}adoptIntervals(t,e,s,i,o,r,a=!0,l){const c=o.map,u={kind:"computed",name:s.label,task:t.id,recipe:{taskVersion:e.provenance.taskVersion,params:e.provenance.params,framing:e.provenance.framing},framing:e.provenance.framing.label},d=s.entryKind==="structure",m=dn(t.id,s.id,c),f=c===Z?s.label:`${s.label} · ${o.label}`,h={output:s,provenance:e.provenance,task:t.id};if(!d){const p=Mi(i,{id:m,label:f,source:u,payload:s.payload,summary:ln(s),colour:i.byId(m)?.style.colour??l??i.nextColour(),map:c,display:a?s.display??(s.payload.kind==="pairs"?"overlay":"lane"):"overlay",look:s.look??"corner",overlay:this.host.context(t)?.hasMap??!0,under:r});return this.intervals.set(p,h),p}const y=Ba(i,m),b=y===m?1:Number(y.slice(m.length+1)),k=i.nextColour();return i.begin({card:"structure",kind:"structure",id:y,label:b>1?`${f} (${b})`:f,source:u,placement:Ei(),style:$i("structure",k)}),i.update(y,{status:"ready",payload:s.payload,summary:s.payload.kind==="features"?Ti(s.payload.data):ln(s)}),this.intervals.set(y,h),null}carry(){const t=this.host.store();if(t===null)return[];const e=[];for(const s of t.entries){if(s.source.kind!=="computed")continue;const i=this.profiles.get(s.id),o=this.intervals.get(s.id);e.push({entry:s,...i===void 0?{}:{profile:i},...o===void 0?{}:{intervals:o}})}return e}placeOnTarget(t,e,s,i){i!==Z&&(t.placeOn(e,i,s),t.unplaceFrom(e,Z))}adoptCarried(t){const e=this.host.store();if(!(e===null||t.length===0)){for(const{entry:s,profile:i,intervals:o}of t){const r=s.source;r.kind==="computed"&&(e.begin({card:s.card,kind:s.kind,id:s.id,label:s.label,source:r,placement:s.placement,style:s.style,visible:s.visible,...s.partner===void 0?{}:{partner:s.partner}}),i!==void 0&&(this.profiles.set(s.id,i),this.register(s.id,i.output,i.grid)),o!==void 0&&this.intervals.set(s.id,o),e.update(s.id,{status:s.status,...s.summary===void 0?{}:{summary:s.summary},...s.payload===void 0?{}:{payload:s.payload},...s.fileExtent===void 0?{}:{fileExtent:s.fileExtent}}))}this.host.changed()}}grid(t){return this.host.contigs(t).map(e=>({name:e.name,startBin:e.startBin,bins:e.bins,length:e.length}))}gridFor(t,e){return this.host.context(e)?.binsize===t?this.grid(e):Ci(this.host.contigs(e),t)}gridBins(){let t=0;for(const e of this.host.contigs())t=Math.max(t,e.startBin+e.bins);return t}async binVector(t){const e=this.host.annotations(),s=this.host.context();if(e===null||s===null)return;const i=this.host.contigs();if(i.length===0)return;const o=s.binsize,r=this.gridBins();if(!(o>0)||r===0)return;const a=i.filter(f=>f.length>0).map(f=>({contig:f.name,start:0,end:f.length}));let l;try{l=await e.request({kind:"sample",entry:t,regions:a,basesPerPixel:o})}catch{return}const c=new Map(i.map(f=>[f.name,f.startBin])),u=new Float32Array(r).fill(Number.NaN),d=new Float64Array(r),m=new Float64Array(r);for(const f of l.regions){const h=c.get(f.contig);if(h!==void 0)for(let y=0;y<f.values.length;y++){const b=f.values[y];if(!Number.isFinite(b))continue;const k=f.starts[y],p=f.ends[y];if(!(p>k))continue;const w=Math.floor(k/o),M=Math.floor((p-1)/o);for(let v=w;v<=M;v++){const x=h+v;if(x<0||x>=u.length)continue;const E=Math.min(p,(v+1)*o)-Math.max(k,v*o);E>0&&(m[x]+=b*E,d[x]+=E)}}}for(let f=0;f<u.length;f++)d[f]>0&&(u[f]=m[f]/d[f]);return u}laneable(){return this.host.store()!==null&&this.host.annotations()!==null}register(t,e,s){const i=this.host.annotations();if(i===null)return;const o={binsize:e.binsize,firstBin:e.extent[0],values:e.values.slice(),contigs:s};i.request({kind:"register",entry:t,vector:o}).catch(()=>{})}recompute(t){const e=t.source;if(e.kind!=="computed")return;const s=$e.find(i=>i.id===e.task);s!==void 0&&this.show(s)}createdAt(t){return this.intervals.get(t)?.provenance.createdAt}async exportEntry(t,e){const s=W(new Date),i=Ee(t.label);if(e==="anchors"){const a=Te(t);if(a?.kind!=="pairs")return;const l=this.intervals.get(t.id),c=Jt({kind:"features",data:Ai(a.data)},{label:`${t.label} anchors`,...l===void 0?{}:{file:l.provenance.framing.label,created:l.provenance.createdAt}});X(new Blob([c],{type:"text/plain"}),`${i}-anchors-${s}.bed`);return}if(e==="bed"){const a=Te(t);if(a===void 0)return;const l=this.intervals.get(t.id),c={label:t.label,...l===void 0?{}:{file:l.provenance.framing.label,created:l.provenance.createdAt}},u=t.kind==="structure"&&a.kind==="features",d=u?xn(a.data,c):Jt(a,c),m=u?"bed3d":a.kind==="pairs"?"bedpe":"bed";X(new Blob([d],{type:"text/plain"}),`${i}-${s}.${m}`);return}const o=this.intervals.get(t.id);if(o!==void 0&&e==="tsv"){X(new Blob([...Qt(o.output,o.provenance)],{type:"text/tab-separated-values"}),yt(i,o.output,s));return}if(t.source.kind==="derived"){await this.exportDerived(t,e,i,s);return}const r=this.profiles.get(t.id);if(r!==void 0){if(e==="tsv"){X(new Blob([...Qt(r.output,r.provenance)],{type:"text/tab-separated-values"}),yt(i,r.output,s));return}await this.writeProfile(r.output,r.provenance,e,r.grid,i)}}async exportDerived(t,e,s,i){const o=t.derivedFrom,r=this.host.context();if(o===void 0||r===null||e==="bed")return;const a=await ct(`${s}-${i}.${e==="tsv"?"tsv":e==="bedgraph"?"bedGraph":"bw"}`,e==="tsv"?"text/tab-separated-values":e==="bedgraph"?"text/plain":"application/octet-stream");if(a===null)return;const[l,c]=await Promise.all([this.exactSamples(o.a),this.exactSamples(o.b)]),u=Ni(l,c,o.op,"drop");if(u===null)return;const d=u.regions.map(y=>({contig:y.contig,starts:y.starts,ends:y.ends,values:y.values})),m=qa(t,o.op,r),f=this.host.contigs();if(e==="tsv"){await a.write(new Blob([...Li(t.label,$n[o.op],d,f,m)],{type:"text/tab-separated-values"}));return}if(e==="bedgraph"){await a.write(new Blob([...Pa(d,f,m)],{type:"text/plain"}));return}const h=await Ce({contigs:f.map(y=>({name:y.name,length:y.length})),spans:d});await a.write(h)}async exactSamples(t){const e=this.host.annotations();if(e===null)return null;const s=this.host.contigs().filter(i=>i.length>0);if(s.length===0)return null;try{return await e.request({kind:"sample",entry:t,regions:s.map(i=>({contig:i.name,start:0,end:i.length})),basesPerPixel:1,exact:!0})}catch{return null}}async writeProfile(t,e,s,i,o=Ee(t.label)){const r=W(new Date),a=await ct(`${o}-${r}.${s==="bedgraph"?"bedGraph":"bw"}`,s==="bedgraph"?"text/plain":"application/octet-stream");if(a===null)return;if(s==="bedgraph"){await a.write(new Blob([...Fa(t,i,e)],{type:"text/plain"}));return}const l=await Ce({contigs:i.map(c=>({name:c.name,length:c.length})),values:t.values,firstBin:t.extent[0],binsize:t.binsize});await a.write(l)}}function Ba(n,t){if(n.byId(t)===void 0)return t;for(let e=2;e<1e3;e++){const s=`${t}#${e}`;if(n.byId(s)===void 0)return s}return`${t}#${Date.now()}`}function ln(n){const t=n.payload,e=t.data.length,s=n.noun??(t.kind==="pairs"?{one:"pair",many:"pairs"}:{one:"interval",many:"intervals"});return`${q.int(e)} ${e===1?s.one:s.many}`}function qa(n,t,e){const s=`${e.binsize.toLocaleString()} bp bins`;return{task:`track ${$n[t]}`,taskVersion:1,params:{operation:t,of:n.label},framing:{uri:e.uri,label:e.hasMap?`two loaded tracks, read onto this file’s ${s}`:`two loaded tracks, read onto the assembly’s ${s}`,binsize:e.binsize,binsPerCell:1,rows:[0,e.nBins],cols:[0,e.nBins],balance:!1,value:"",normalise:null,level:"bin"},app:hn,createdAt:new Date().toISOString()}}function cn(n){return n.entries.map(t=>`${t.id}:${t.kind}:${t.status}:${t.label}`).join("|")}function un(n){return n.entries.filter(Oi).map(t=>`${t.id}:${t.card}:${t.style.shape}`).join("|")}function dn(n,t,e){return e===Z?`analysis:${n}:${t}`:`analysis:${e}:${n}:${t}`}export{Ra as AnalysisWorkspace,cn as entrySignature,Ba as freshId};