Download static/circular/circular-view.js from pswap/phlam: direct link, hf CLI and curl.
- Browser
- Download file 26 kB
-
https://huggingface.co/spaces/pswap/phlam/resolve/main/static/circular/circular-view.js
- Command line
-
hf download hf://spaces/pswap/phlam/static/circular/circular-view.js
-
curl -L -o circular-view.js https://huggingface.co/spaces/pswap/phlam/resolve/main/static/circular/circular-view.js
26 kB
| // Shared with static/genome-viewer.js's PHLAM_PALETTE/phlamHashColor -- same | |
| // palette + same djb2 hash-of-the-annotation-string means a given annotation | |
| // (e.g. "endolysin") gets the identical color in both the circular view and | |
| // the synteny view, since neither view's local set of categories affects it | |
| // (unlike an ordinal scale keyed to sort- or appearance-order, which would | |
| // reassign colors whenever the surrounding category set changes). | |
| const PHLAM_PALETTE = [ | |
| 'oklch(0.62 0.11 195)', 'oklch(0.62 0.11 25)', 'oklch(0.55 0.09 260)', | |
| 'oklch(0.62 0.11 140)', 'oklch(0.65 0.13 60)', 'oklch(0.55 0.10 320)', | |
| 'oklch(0.62 0.11 90)', 'oklch(0.58 0.12 350)', 'oklch(0.6 0.08 220)', | |
| 'oklch(0.65 0.12 10)', 'oklch(0.6 0.1 170)', 'oklch(0.55 0.11 290)', | |
| 'oklch(0.68 0.1 40)', 'oklch(0.58 0.09 240)', 'oklch(0.6 0.12 110)', | |
| 'oklch(0.5 0.08 200)', | |
| ]; | |
| const PHLAM_UNANNOTATED_COLOR = '#C9C4BB'; | |
| function phlamHashColor(str, palette = PHLAM_PALETTE) { | |
| if (!str || str === 'unannotated' || str === 'no annotation') return PHLAM_UNANNOTATED_COLOR; | |
| let h = 5381; | |
| for (let i = 0; i < str.length; i++) h = ((h << 5) + h + str.charCodeAt(i)) | 0; | |
| return palette[Math.abs(h) % palette.length]; | |
| } | |
| // A homology hit's id, linked out to its source database when hit.url is | |
| // set (caller-supplied -- this module has no knowledge of any specific | |
| // source's URL scheme). | |
| function hitIdLabel(hit) { | |
| if (!hit.id) return ''; | |
| return hit.url ? `<a href="${hit.url}" target="_blank" rel="noopener">${hit.id}</a>` : hit.id; | |
| } | |
| class CircularGenomeViewer { | |
| // container: a DOM element to render into (not an id) -- this builds its | |
| // own .phlam-gv-outer/.phlam-gv-wrap/svg/tooltip structure inside it, so | |
| // the caller only needs an empty host element, same calling convention as | |
| // synteny-view.js's createSyntenyView(element, options). | |
| constructor(container, options = {}) { | |
| this.W = options.width || 700; | |
| this.H = options.height || 700; | |
| this.R = options.radius || 260; | |
| this.rH = options.trackWidth || 16; | |
| this.HEAD_RAD = 0.075; | |
| this.globalAttentionData = null; | |
| // Interaction state | |
| this._pinnedGeneIdx = null; | |
| this._clickTimer = null; | |
| this._lastClickedIdx = null; | |
| this._geneNodes = []; | |
| container.innerHTML = ''; | |
| const outer = document.createElement('div'); | |
| outer.className = 'phlam-gv-outer'; | |
| const wrap = document.createElement('div'); | |
| wrap.className = 'phlam-gv-wrap'; | |
| outer.appendChild(wrap); | |
| container.appendChild(outer); | |
| this.container = outer; | |
| this.svg = d3.select(wrap).append('svg').attr('width', this.W).attr('height', this.H); | |
| this.g = this.svg.append('g').attr('transform', `translate(${this.W / 2},${this.H / 2})`); | |
| const defs = this.svg.append('defs'); | |
| defs.append('marker') | |
| .attr('id', 'arrowhead') | |
| .attr('markerWidth', 10) | |
| .attr('markerHeight', 10) | |
| .attr('refX', 8) | |
| .attr('refY', 3) | |
| .attr('orient', 'auto') | |
| .append('polygon') | |
| .attr('points', '0 0, 10 3, 0 6') | |
| .attr('fill', 'var(--phlam-accent)'); | |
| this.chordG = this.g.append('g').attr('class', 'chord-layer'); | |
| this.axisG = this.g.append('g').attr('class', 'axis-layer'); | |
| this.geneG = this.g.append('g').attr('class', 'gene-layer'); | |
| this.labelG = this.g.append('g').attr('class', 'label-layer'); | |
| this.legendG = this.g.append('g').attr('class', 'legend-layer'); | |
| this._initTooltip(); | |
| // Click on SVG background unpins | |
| const self = this; | |
| this.svg.on('click', () => { | |
| if (self._pinnedGeneIdx !== null) { | |
| const node = self._geneNodes[self._pinnedGeneIdx]; | |
| if (node) d3.select(node).attr('fill-opacity', 0.85); | |
| self._pinnedGeneIdx = null; | |
| self._hideTooltip(); | |
| self._restoreChords(); | |
| } | |
| }); | |
| this.genomeData = null; | |
| } | |
| // ββ Tooltip ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // A permanent in-flow side panel (not position:fixed) at a fixed spot next | |
| // to the chart -- never follows the mouse, and never needs viewport-size | |
| // math (which broke once this chart started living inside a tightly-sized | |
| // iframe with no guaranteed empty space around it). | |
| _initTooltip() { | |
| const el = document.createElement('div'); | |
| el.className = 'gv-tooltip'; | |
| this.container.appendChild(el); | |
| this.tipEl = el; | |
| this._placeholderHtml = '<div class="gv-tt-placeholder">Hover a protein for details.<br>Double-click any protein to copy the full gene table.</div>'; | |
| this._hideTooltip(); | |
| } | |
| _showTooltip(html, pinned = false) { | |
| this.tipEl.innerHTML = html; | |
| this.tipEl.classList.toggle('gv-tooltip--pinned', pinned); | |
| } | |
| _hideTooltip() { | |
| this.tipEl.innerHTML = this._placeholderHtml; | |
| this.tipEl.classList.remove('gv-tooltip--pinned'); | |
| } | |
| // ββ Chord helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _dimChordsExcept(i) { | |
| // Hover: fade non-connected chords to hint | |
| this.svg.selectAll('.chord').attr('stroke-opacity', 0.03); | |
| this.svg.selectAll(`.chord-i-${i}`).attr('stroke-opacity', function () { | |
| return +d3.select(this).attr('data-base-opacity'); | |
| }); | |
| } | |
| _isolateChordsFor(i) { | |
| // Pin: show only ego-network edges (direct ins + outs), hide everything else | |
| this.svg.selectAll('.chord').attr('stroke-opacity', 0); | |
| this.svg.selectAll(`.chord-i-${i}`).attr('stroke-opacity', function () { | |
| return +d3.select(this).attr('data-base-opacity'); | |
| }); | |
| } | |
| _restoreChords() { | |
| this.svg.selectAll('.chord').attr('stroke-opacity', function () { | |
| return +d3.select(this).attr('data-base-opacity'); | |
| }); | |
| } | |
| // ββ Clipboard βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _copyGeneFasta(gn) { | |
| let header = `>${gn.id} # ${gn.start} # ${gn.end} # ${gn.strand}`; | |
| // PHLAM's only annotation signal is the flat ESM-homology block (gn.homology, | |
| // built by viewer.py) -- there is no gn.annotation here (that hierarchical | |
| // category/leaf shape belongs to the sibling genome_view project this | |
| // viewer was adapted from, and PHLAM never populates it), so the FASTA | |
| // header must be built from the same fields the hover tooltip already | |
| // reads at gn.homology.{topHit,otherTopHit,majorityVote}. | |
| const h = gn.homology; | |
| if (h) { | |
| const hit = (key, label) => { | |
| const entry = h[key]; | |
| if (!entry) return; | |
| const pct = entry.score != null ? (entry.score * 100).toFixed(0) : ''; | |
| header += ` # ${label}=${entry.text}` + (entry.source ? ` # ${label}_source=${entry.source}` : '') | |
| + (entry.id ? ` # ${label}_id=${entry.id}` : '') | |
| + (pct ? ` # ${label}_match=${pct}%` : ''); | |
| }; | |
| hit('topHit', 'top_hit'); | |
| hit('otherTopHit', 'other_top_hit'); | |
| if (h.majorityVote) { | |
| const frac = h.majorityVote.voteFrac != null ? (h.majorityVote.voteFrac * 100).toFixed(0) : ''; | |
| header += ` # majority_vote=${h.majorityVote.text}` + (h.majorityVote.id ? ` # majority_vote_id=${h.majorityVote.id}` : '') | |
| + (frac ? ` # majority_vote_agree=${frac}%` : ''); | |
| } | |
| } | |
| const text = `${header}\n${gn.sequence || ''}`; | |
| const flash = (html) => { | |
| const prev = this.tipEl.innerHTML; | |
| this.tipEl.innerHTML = html; | |
| setTimeout(() => { this.tipEl.innerHTML = prev; }, 1400); | |
| }; | |
| const onCopied = () => flash('<div class="gv-tt-title" style="color:var(--phlam-pass)">β Protein FASTA copied</div>'); | |
| const onFailed = () => flash('<div class="gv-tt-title" style="color:var(--phlam-rev)">Copy failed β clipboard unavailable</div>'); | |
| if (navigator.clipboard && navigator.clipboard.writeText) { | |
| navigator.clipboard.writeText(text).then(onCopied, () => this._legacyCopy(text) ? onCopied() : onFailed()); | |
| } else { | |
| this._legacyCopy(text) ? onCopied() : onFailed(); | |
| } | |
| } | |
| // Fallback for contexts where the async Clipboard API is unavailable or | |
| // denied (e.g. some sandboxed/cross-origin iframe embeddings) -- a | |
| // synchronous execCommand('copy') off a throwaway textarea still works | |
| // there since it runs inside the same user-gesture (dblclick) call stack. | |
| _legacyCopy(text) { | |
| try { | |
| const ta = document.createElement('textarea'); | |
| ta.value = text; | |
| ta.style.position = 'fixed'; | |
| ta.style.opacity = '0'; | |
| document.body.appendChild(ta); | |
| ta.focus(); | |
| ta.select(); | |
| const ok = document.execCommand('copy'); | |
| document.body.removeChild(ta); | |
| return ok; | |
| } catch (e) { | |
| return false; | |
| } | |
| } | |
| // ββ Legend βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _renderLegend(label, lo, hi, colorScale) { | |
| const w = 150, h = 11, y = this.H / 2 - 36, x = -w / 2; | |
| const gradId = 'phlam-legend-gradient'; | |
| const defs = this.svg.select('defs'); | |
| defs.select(`#${gradId}`).remove(); | |
| const grad = defs.append('linearGradient').attr('id', gradId).attr('x1', '0%').attr('x2', '100%'); | |
| d3.range(0, 1.0001, 0.1).forEach(t => { | |
| grad.append('stop').attr('offset', `${t * 100}%`).attr('stop-color', colorScale(lo + t * (hi - lo))); | |
| }); | |
| const legend = this.legendG.append('g').attr('transform', `translate(0, ${y})`); | |
| legend.append('text').attr('x', 0).attr('y', -7).attr('text-anchor', 'middle') | |
| .attr('fill', 'var(--phlam-muted)').attr('font-size', '11') | |
| .attr('font-family', "'Azeret Mono', monospace").text(label); | |
| legend.append('rect').attr('x', x).attr('y', 0).attr('width', w).attr('height', h) | |
| .attr('fill', `url(#${gradId})`).attr('stroke', 'var(--phlam-border)').attr('stroke-width', 0.75); | |
| legend.append('text').attr('x', x).attr('y', h + 14).attr('text-anchor', 'start') | |
| .attr('fill', 'var(--phlam-muted)').attr('font-size', '10.5') | |
| .attr('font-family', "'Azeret Mono', monospace").text(lo.toFixed(2)); | |
| legend.append('text').attr('x', x + w).attr('y', h + 14).attr('text-anchor', 'end') | |
| .attr('fill', 'var(--phlam-muted)').attr('font-size', '10.5') | |
| .attr('font-family', "'Azeret Mono', monospace").text(hi.toFixed(2)); | |
| } | |
| // ββ Render ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| renderGenome(genomeData, colorMetric = null) { | |
| this.genomeData = genomeData; | |
| const { genomeSize, genes } = genomeData; | |
| // Reset interaction state on each render | |
| this._pinnedGeneIdx = null; | |
| this._geneNodes = []; | |
| if (this._clickTimer) { clearTimeout(this._clickTimer); this._clickTimer = null; } | |
| this._hideTooltip(); | |
| this.axisG.selectAll('*').remove(); | |
| this.geneG.selectAll('*').remove(); | |
| this.labelG.selectAll('*').remove(); | |
| this.legendG.selectAll('*').remove(); | |
| this.chordG.selectAll('.global-attn-arrow').remove(); | |
| if (!genomeSize || !genes) return; | |
| const R = this.R, rH = this.rH, HEAD_RAD = this.HEAD_RAD; | |
| const ang = pos => (pos / genomeSize) * Math.PI * 2 - Math.PI / 2; | |
| const pt = (r, a) => [Math.cos(a) * r, Math.sin(a) * r]; | |
| // Strand ('strand' mode, the default) keeps the categorical fwd/rev | |
| // colors below; any other mode drives fill color from a per-gene metric | |
| // instead (continuous: sequential scale + gradient legend; categorical, | |
| // e.g. annotation category/subcategory: ordinal scale + swatch legend) | |
| // -- gene shape/arrow direction still encodes strand regardless, so no | |
| // information is lost by repurposing color. | |
| let colorScale = null; | |
| if (colorMetric && colorMetric.values && colorMetric.values.length === genes.length) { | |
| if (colorMetric.type === 'categorical') { | |
| colorScale = phlamHashColor; | |
| // No swatch legend here: the categorical case is annotation text, | |
| // often dozens of distinct values -- genes still get distinct | |
| // colors per annotation, but a legend listing them all isn't | |
| // usable. Hover tooltip still shows each gene's own annotation. | |
| } else { | |
| const [lo, hi] = colorMetric.domain || d3.extent(colorMetric.values); | |
| colorScale = d3.scaleSequential(d3.interpolatePlasma).domain([lo, hi === lo ? lo + 1 : hi]); | |
| this._renderLegend(colorMetric.label, lo, hi, colorScale); | |
| } | |
| } | |
| // Background ring | |
| this.axisG.append('circle').attr('r', R).attr('fill', 'none') | |
| .attr('stroke', 'var(--phlam-surface)').attr('stroke-width', rH * 2 + 6); | |
| // Tick marks | |
| d3.range(8).forEach(i => { | |
| const a = (i / 8) * Math.PI * 2 - Math.PI / 2; | |
| const pos = Math.round((i / 8) * genomeSize); | |
| const lbl = pos >= 1e6 ? (pos / 1e6).toFixed(1) + 'M' : pos >= 1e3 ? (pos / 1e3).toFixed(0) + 'k' : pos; | |
| const r1 = R + rH + 5, r2 = r1 + 10; | |
| this.axisG.append('line') | |
| .attr('x1', Math.cos(a) * r1).attr('y1', Math.sin(a) * r1) | |
| .attr('x2', Math.cos(a) * r2).attr('y2', Math.sin(a) * r2) | |
| .attr('stroke', 'var(--phlam-muted)').attr('stroke-width', 1); | |
| if (i > 0) this.axisG.append('text') | |
| .attr('x', Math.cos(a) * (r2 + 12)).attr('y', Math.sin(a) * (r2 + 12)) | |
| .attr('text-anchor', 'middle').attr('dominant-baseline', 'middle') | |
| .attr('fill', 'var(--phlam-muted)').attr('font-size', '11') | |
| .attr('font-family', "'Azeret Mono', monospace").text(lbl); | |
| }); | |
| this.geneElements = []; | |
| const self = this; | |
| genes.forEach((gn, i) => { | |
| const isFwd = gn.strand === '+' || gn.strand === 1; | |
| let color = gn.color; | |
| if (!color) { | |
| if (colorScale) color = colorScale(colorMetric.values[i]); | |
| else if (gn.partial) color = 'var(--phlam-warn)'; | |
| else color = isFwd ? 'var(--phlam-fwd)' : 'var(--phlam-rev)'; | |
| } | |
| const geneRH = rH; | |
| const gStart = gn.start; | |
| const angS = ang(gStart), angE = ang(gn.end); | |
| const span = angE - angS; | |
| const headA = Math.min(HEAD_RAD, Math.abs(span) * 0.4); | |
| const bodyEnd = isFwd ? angE - headA : angS + headA; | |
| let pathD; | |
| if (isFwd) { | |
| const p = [pt(R + geneRH, angS), pt(R + geneRH, bodyEnd), pt(R + geneRH + geneRH * .9, bodyEnd), | |
| pt(R, angE), pt(R - geneRH - geneRH * .9, bodyEnd), pt(R - geneRH, bodyEnd), pt(R - geneRH, angS)]; | |
| pathD = `M${p[0]} A${R + geneRH},${R + geneRH} 0 0,1 ${p[1]} L${p[2]} L${p[3]} L${p[4]} L${p[5]} A${R - geneRH},${R - geneRH} 0 0,0 ${p[6]} Z`; | |
| } else { | |
| const p = [pt(R + geneRH, angE), pt(R + geneRH, bodyEnd), pt(R + geneRH + geneRH * .9, bodyEnd), | |
| pt(R, angS), pt(R - geneRH - geneRH * .9, bodyEnd), pt(R - geneRH, bodyEnd), pt(R - geneRH, angE)]; | |
| pathD = `M${p[0]} A${R + geneRH},${R + geneRH} 0 0,0 ${p[1]} L${p[2]} L${p[3]} L${p[4]} L${p[5]} A${R - geneRH},${R - geneRH} 0 0,1 ${p[6]} Z`; | |
| } | |
| let tipHtml = `<div class="gv-tt-title" style="color:${color}">${gn.id || 'N/A'}</div>`; | |
| tipHtml += `<div class="gv-tt-loc">${gStart.toLocaleString()} β ${gn.end.toLocaleString()} bp Β· <span style="color:${color}">${isFwd ? '(+) Forward' : '(β) Reverse'}</span></div>`; | |
| if (gn.annotation) { | |
| // Two independent axes (lifecycle stage / functional role). Within | |
| // an axis, category/leaf come from the SAME winning pool node (one | |
| // unified ranking per axis), so they share one similarity and are | |
| // guaranteed mutually coherent -- no cross-check between them is | |
| // possible or needed. The two axes are fully independent of each | |
| // other, each gets its own group + node-type badge. | |
| for (const axis of Object.values(gn.annotation)) { | |
| // confidence = fraction of noise-perturbed re-searches that agreed | |
| // with the winning match -- local stability, not raw similarity. | |
| const confPct = (axis.confidence * 100).toFixed(0); | |
| const confCls = axis.confidence >= 0.7 ? ' gv-tt-annot-conf-high' : axis.confidence >= 0.4 ? ' gv-tt-annot-conf-mid' : ' gv-tt-annot-conf-low'; | |
| const meta = (axis.nodeType ? `${axis.nodeType} Β· ` : '') + `<span class="gv-tt-annot-conf${confCls}">${confPct}% stable</span>`; | |
| // Each axis is its own bordered block -- lifecycle_stage and | |
| // functional_role are independently-searched answers, not levels | |
| // of one tree, and should visually read that way, not just blend | |
| // together as one continuous list. | |
| tipHtml += '<div class="gv-tt-annot-axis">'; | |
| tipHtml += `<div class="gv-tt-annot-axis-label"><span>${axis.label}</span><span class="gv-tt-annot-axis-meta">${meta}</span></div>`; | |
| tipHtml += '<div class="gv-tt-annot-group">'; | |
| for (const [level, entry] of [['category', axis.category], ['annotation', axis.leaf]]) { | |
| const cls = entry.resolved ? '' : ' gv-tt-annot-unresolved'; | |
| tipHtml += `<div class="gv-tt-annot-item${cls}"><div class="gv-tt-annot-level">${level}</div>` | |
| + `<div class="gv-tt-annot-text"><span>${entry.text}</span><span class="gv-tt-annot-sim">${(entry.sim * 100).toFixed(0)}%</span></div></div>`; | |
| } | |
| tipHtml += '</div></div>'; | |
| } | |
| } | |
| if (gn.homology) { | |
| // Third, independent annotation signal: plain ESM-embedding | |
| // nearest-neighbor homology (PHROG/SwissProt via Qdrant) -- its own | |
| // bordered block so it's never confused with the CLIP-projected | |
| // hierarchy axes above. Each row is independently optional. | |
| const h = gn.homology; | |
| if (h.topHit || h.otherTopHit || h.majorityVote) { | |
| tipHtml += '<div class="gv-tt-annot-axis">'; | |
| tipHtml += '<div class="gv-tt-annot-axis-label"><span>Homology (ESM)</span></div>'; | |
| tipHtml += '<div class="gv-tt-annot-group">'; | |
| if (h.topHit) { | |
| const pct = h.topHit.score != null ? `${(h.topHit.score * 100).toFixed(0)}%` : ''; | |
| tipHtml += `<div class="gv-tt-annot-item"><div class="gv-tt-annot-level">top hit${h.topHit.source ? ` Β· ${h.topHit.source}` : ''}${h.topHit.id ? ` Β· ${hitIdLabel(h.topHit)}` : ''}</div>` | |
| + `<div class="gv-tt-annot-text"><span>${h.topHit.text}</span><span class="gv-tt-annot-sim">${pct}</span></div></div>`; | |
| } | |
| if (h.otherTopHit) { | |
| const pct = h.otherTopHit.score != null ? `${(h.otherTopHit.score * 100).toFixed(0)}%` : ''; | |
| tipHtml += `<div class="gv-tt-annot-item"><div class="gv-tt-annot-level">other source${h.otherTopHit.source ? ` Β· ${h.otherTopHit.source}` : ''}${h.otherTopHit.id ? ` Β· ${hitIdLabel(h.otherTopHit)}` : ''}</div>` | |
| + `<div class="gv-tt-annot-text"><span>${h.otherTopHit.text}</span><span class="gv-tt-annot-sim">${pct}</span></div></div>`; | |
| } | |
| if (h.majorityVote) { | |
| const frac = h.majorityVote.voteFrac; | |
| const voteCls = frac == null ? '' : frac >= 0.7 ? ' gv-tt-annot-conf-high' : frac >= 0.4 ? ' gv-tt-annot-conf-mid' : ' gv-tt-annot-conf-low'; | |
| const voteBadge = frac != null ? `<span class="gv-tt-annot-conf${voteCls}">${(frac * 100).toFixed(0)}% agree</span>` : ''; | |
| tipHtml += `<div class="gv-tt-annot-item"><div class="gv-tt-annot-level">majority vote${h.majorityVote.id ? ` Β· ${h.majorityVote.id}` : ''}</div>` | |
| + `<div class="gv-tt-annot-text"><span>${h.majorityVote.text}</span>${voteBadge}</div></div>`; | |
| } | |
| tipHtml += '</div></div>'; | |
| } | |
| } | |
| if (gn.community !== undefined) { | |
| tipHtml += `<div class="gv-tt-row"><span>community:</span> ${gn.community}</div>`; | |
| } | |
| if (gn.hoverData) { | |
| for (const [key, val] of Object.entries(gn.hoverData)) { | |
| tipHtml += `<div class="gv-tt-row"><span>${key}:</span> ${val}</div>`; | |
| } | |
| } | |
| const pinnedTipHtml = tipHtml + '<div class="gv-tt-pin">click to unpin Β· dbl-click to copy protein FASTA</div>'; | |
| const geneEl = this.geneG.append('path') | |
| .attr('d', pathD).attr('fill', color).attr('fill-opacity', 0.85) | |
| .attr('stroke', color).attr('stroke-width', 0.4).style('cursor', 'pointer') | |
| .on('mouseover', function () { | |
| if (self._pinnedGeneIdx !== null) return; | |
| self._showTooltip(tipHtml); | |
| self._dimChordsExcept(i); | |
| d3.select(this).attr('fill-opacity', 1); | |
| }) | |
| .on('mouseout', function () { | |
| if (self._pinnedGeneIdx !== null) return; | |
| self._hideTooltip(); | |
| self._restoreChords(); | |
| d3.select(this).attr('fill-opacity', 0.85); | |
| }) | |
| .on('click', function (event) { | |
| event.stopPropagation(); | |
| const node = this; | |
| // Two quick clicks on the same gene β double-click β copy | |
| if (self._clickTimer) { | |
| clearTimeout(self._clickTimer); | |
| self._clickTimer = null; | |
| if (self._lastClickedIdx === i) { | |
| self._copyGeneFasta(gn); | |
| return; | |
| } | |
| } | |
| self._lastClickedIdx = i; | |
| self._clickTimer = setTimeout(() => { | |
| self._clickTimer = null; | |
| if (self._pinnedGeneIdx === i) { | |
| // Unpin | |
| self._pinnedGeneIdx = null; | |
| self._hideTooltip(); | |
| self._restoreChords(); | |
| d3.select(node).attr('fill-opacity', 0.85); | |
| } else { | |
| // Unpin previously pinned gene | |
| if (self._pinnedGeneIdx !== null) { | |
| const prev = self._geneNodes[self._pinnedGeneIdx]; | |
| if (prev) d3.select(prev).attr('fill-opacity', 0.85); | |
| } | |
| // Pin this gene | |
| self._pinnedGeneIdx = i; | |
| self._showTooltip(pinnedTipHtml, true); | |
| self._isolateChordsFor(i); | |
| d3.select(node).attr('fill-opacity', 1); | |
| } | |
| }, 220); | |
| }); | |
| this._geneNodes[i] = geneEl.node(); | |
| this.geneElements.push({ element: geneEl, angS, angE, color }); | |
| }); | |
| this.labelG.append('text').attr('text-anchor', 'middle').attr('y', -12) | |
| .attr('fill', 'var(--phlam-accent)').attr('font-size', '19') | |
| .attr('font-family', "'Azeret Mono', monospace") | |
| .text((genomeSize / 1e3).toFixed(0) + ' kb'); | |
| this.labelG.append('text').attr('text-anchor', 'middle').attr('y', 11) | |
| .attr('fill', 'var(--phlam-muted)').attr('font-size', '13') | |
| .attr('font-family', "'Azeret Mono', monospace") | |
| .text(genes.length + ' genes'); | |
| } | |
| updateArcs(matrix, percentile = 0) { | |
| this.chordG.selectAll('.chord').remove(); | |
| if (!this.genomeData || !this.genomeData.genes || this.genomeData.genes.length === 0) return; | |
| if (!matrix || matrix.length === 0) return; | |
| const genes = this.genomeData.genes; | |
| const genomeSize = this.genomeData.genomeSize; | |
| const N = genes.length; | |
| const ang = pos => (pos / genomeSize) * Math.PI * 2 - Math.PI / 2; | |
| const pt = (r, a) => [Math.cos(a) * r, Math.sin(a) * r]; | |
| const rChord = this.R - this.rH - 8; | |
| const geneMatrix = matrix.slice(1).map(row => row.slice(1)); | |
| const offDiag = []; | |
| for (let i = 0; i < N && i < geneMatrix.length; i++) { | |
| for (let j = 0; j < N && j < geneMatrix[i].length; j++) { | |
| if (i !== j) offDiag.push(geneMatrix[i][j]); | |
| } | |
| } | |
| offDiag.sort((a, b) => a - b); | |
| if (offDiag.length === 0) return; | |
| const threshIdx = Math.floor(offDiag.length * (percentile / 100)); | |
| const threshVal = offDiag[Math.min(threshIdx, offDiag.length - 1)] ?? 0; | |
| const maxVal = offDiag[offDiag.length - 1] ?? 1; | |
| for (let i = 0; i < N && i < geneMatrix.length; i++) { | |
| for (let j = 0; j < N && j < geneMatrix[i].length; j++) { | |
| if (i === j) continue; | |
| const val = geneMatrix[i][j]; | |
| if (val <= threshVal) continue; | |
| const norm = (val - threshVal) / (maxVal - threshVal + 1e-9); | |
| // Width is the primary encoding of attention strength; opacity gives a | |
| // secondary depth cue on top and still drives hover isolation below. | |
| const width = 0.75 + 5.5 * norm; | |
| const opacity = 0.25 + 0.55 * norm; | |
| const midI = (genes[i].start + genes[i].end) / 2; | |
| const midJ = (genes[j].start + genes[j].end) / 2; | |
| const [x1, y1] = pt(rChord, ang(midI)); | |
| const [x2, y2] = pt(rChord, ang(midJ)); | |
| this.chordG.append('path') | |
| .attr('class', `chord chord-i-${i} chord-i-${j}`) | |
| .attr('d', `M ${x1} ${y1} Q 0 0 ${x2} ${y2}`) | |
| .attr('fill', 'none').attr('stroke', 'var(--phlam-accent)') | |
| .attr('stroke-width', width).attr('stroke-opacity', opacity) | |
| .attr('data-base-opacity', opacity) | |
| .attr('marker-end', 'url(#arrowhead)'); | |
| } | |
| } | |
| // Re-apply ego-network isolation if a gene is pinned | |
| if (this._pinnedGeneIdx !== null) { | |
| this._isolateChordsFor(this._pinnedGeneIdx); | |
| } | |
| } | |
| } | |
| // Same calling convention as synteny-view.js's createSyntenyView: data in, | |
| // events out, no knowledge of the host page beyond the element it's given. | |
| // import { createCircularView } from "circular-view.js"; | |
| // const view = createCircularView(document.getElementById("plot")); | |
| // view.renderGenome(genomeData, colorMetric); | |
| // view.updateArcs(matrix, percentile); | |
| export function createCircularView(container, options = {}) { | |
| return new CircularGenomeViewer(container, options); | |
| } | |
| export { CircularGenomeViewer, phlamHashColor }; | |