Turn the Sankey down the page and add lineage shortcuts (#4)
Browse files- Turn the Sankey down the page and add lineage shortcuts (9021c344f420160c757d6a415920d6d3f0b5f798)
Files changed (7)
- README.md+1-1
- atlas.css+6-4
- atlas.js+12-3
- data/common_names.json+6-6
- refresh_common_names.py+5-5
- taxonomy.py+72-56
- tests/test_taxonomy.py+29-16
16 unmodified lines1718192021222316 unmodified lines## GenBank taxonomyThe landing page opens with an interactive **tree of eukaryotic life**, using NCBI's current GenBank assembly summary and taxonomy. It is drawn as a Sankey diagram: each group is a bar split into annotated (green) and not-annotated (gray) assemblies, and flows carry both parts from a group into its lineages. Counts and percentages appear beside the groups, with details on hover. Each group is labelled with its scientific name and, where one exists, a plain-English name underneath, so the Latin backbone of the tree (Opisthokonta, Eumetazoa, Ecdysozoa) stays readable without prior knowledge. The default **Genome Atlas** tab contains the tree and its lineage controls. A separate **Database** tab holds accession search, segment visualization, and downloads, using the full published-file snapshot. RefSeq exploration can be added beneath the tree. The two equal-width navigation options span the top of the page.The viewer is restricted to **Eukaryota (NCBI taxid 2759) and its descendants**, including search, breadcrumbs, and parent navigation. The model predicts eukaryotic annotations; bacteria, archaea, and viruses are outside this display. The current eukaryotic snapshot contains **70,395 assemblies**, of which **17,561 (24.9%)** have published annotations. The underlying SQLite snapshot retains the full NCBI inventory for refresh/provenance, while the interface uses only the eukaryotic subtree and its denominators. Assemblies with unresolved taxonomy cannot be assigned to that subtree and are excluded.16 unmodified lines1718192021222316 unmodified lines## GenBank taxonomyThe landing page opens with an interactive **tree of eukaryotic life**, using NCBI's current GenBank assembly summary and taxonomy. It is drawn as a Sankey diagram running **down the page**: each group is a horizontal bar split into annotated (green) and not-annotated (gray) assemblies, and flows carry both parts from a group into its lineages on the level below. Expanding a group adds a level underneath rather than a column to the right, so a full lineage — eukaryotes down to humans is about thirty levels — is one ordinary page scroll instead of an endless sideways one. The chart itself only scrolls on screens too narrow to keep the labels legible. Shortcut buttons above the tree jump straight to a lineage: animals, mammals, humans, birds, ray-finned fish, insects, jellyfish, green plants, flowering plants and fungi. Counts and percentages appear beside the groups, with details on hover. Each group is labelled with its scientific name and, where one exists, a plain-English name underneath, so the Latin backbone of the tree (Opisthokonta, Eumetazoa, Ecdysozoa) stays readable without prior knowledge. The default **Genome Atlas** tab contains the tree and its lineage controls. A separate **Database** tab holds accession search, segment visualization, and downloads, using the full published-file snapshot. RefSeq exploration can be added beneath the tree. The two equal-width navigation options span the top of the page.The viewer is restricted to **Eukaryota (NCBI taxid 2759) and its descendants**, including search, breadcrumbs, and parent navigation. The model predicts eukaryotic annotations; bacteria, archaea, and viruses are outside this display. The current eukaryotic snapshot contains **70,395 assemblies**, of which **17,561 (24.9%)** have published annotations. The underlying SQLite snapshot retains the full NCBI inventory for refresh/provenance, while the interface uses only the eukaryotic subtree and its denominators. Assemblies with unresolved taxonomy cannot be assigned to that subtree and are excluded.
20 unmodified lines2122232425262712 unmodified lines4041424344454611 unmodified lines58596061626364656667686970717220 unmodified lines.atlas-breadcrumb button { border:0; background:none; color:inherit; padding:2px 0; }.atlas-breadcrumb button:hover { text-decoration:underline; }.crumb-divider { opacity:.4; }.tree-scroll { overflow-x:auto; overscroll-behavior-x:contain; margin:0 -5px; }.life-tree { display:block; width:100%; height:auto; overflow:visible; }.flow { stroke:none; transition:opacity .15s; }.flow-annotated { fill:#40916f; opacity:.42; }12 unmodified lines.tree-icon { opacity:.62; transition:opacity .15s; }.tree-node.is-selected .tree-icon { opacity:.85; }.tree-node:not(.is-direct):hover .tree-icon { opacity:.9; }.tree-label,.tree-english,.tree-count { paint-order:stroke; stroke:#f7f8f0; stroke-width:4px; stroke-linejoin:round; }.tree-label { font:600 13px Arial,Helvetica,sans-serif; fill:#254735; transition:fill .15s; }.tree-node.is-selected .tree-label { font-weight:700; fill:#173c30; }.tree-english { font:italic 11.5px Georgia,'Times New Roman',serif; fill:#5d7a66; }11 unmodified lines.atlas-tooltip[hidden] { display:none; }.atlas button:focus-visible { outline:2px solid #327555; outline-offset:3px; }.atlas-leaf-note { color:#647467; font-size:13px; text-align:center; margin:0 0 20px; }.atlas-mobile-hint { display:none; }@media(max-width:800px) {.atlas { padding:22px 16px 16px; border-radius:18px; }.atlas-header { align-items:flex-start; flex-direction:column; gap:18px; }.atlas-summary-block { border-left:0; padding:0; min-width:0; }.atlas-summary { flex-wrap:wrap; }.atlas h1 { font-size:35px; }.atlas-nav { flex-wrap:wrap; margin-top:18px; }.atlas-mobile-hint { display:inline; }.atlas-footer { gap:9px; }}@media(prefers-reduced-motion:reduce) { .atlas * { transition:none!important; } }20 unmodified lines2122232425262712 unmodified lines4041424344454611 unmodified lines585960616263646566676869707172737420 unmodified lines.atlas-breadcrumb button { border:0; background:none; color:inherit; padding:2px 0; }.atlas-breadcrumb button:hover { text-decoration:underline; }.crumb-divider { opacity:.4; }.tree-scroll { margin:0 -5px; }.life-tree { display:block; width:100%; height:auto; overflow:visible; }.flow { stroke:none; transition:opacity .15s; }.flow-annotated { fill:#40916f; opacity:.42; }12 unmodified lines.tree-icon { opacity:.62; transition:opacity .15s; }.tree-node.is-selected .tree-icon { opacity:.85; }.tree-node:not(.is-direct):hover .tree-icon { opacity:.9; }.tree-label,.tree-english,.tree-count { paint-order:stroke; stroke:#f7f8f0; stroke-width:4px; stroke-linejoin:round; text-anchor:middle; }.tree-label { font:600 13px Arial,Helvetica,sans-serif; fill:#254735; transition:fill .15s; }.tree-node.is-selected .tree-label { font-weight:700; fill:#173c30; }.tree-english { font:italic 11.5px Georgia,'Times New Roman',serif; fill:#5d7a66; }11 unmodified lines.atlas-tooltip[hidden] { display:none; }.atlas button:focus-visible { outline:2px solid #327555; outline-offset:3px; }.atlas-leaf-note { color:#647467; font-size:13px; text-align:center; margin:0 0 20px; }@media(max-width:800px) {.atlas { padding:22px 16px 16px; border-radius:18px; }/* Levels fill the page width, so on a phone the only way to keep the labelslegible is to let the chart itself scroll sideways again. */.tree-scroll { overflow-x:auto; overscroll-behavior-x:contain; }.life-tree { min-width:720px; }.atlas-header { align-items:flex-start; flex-direction:column; gap:18px; }.atlas-summary-block { border-left:0; padding:0; min-width:0; }.atlas-summary { flex-wrap:wrap; }.atlas h1 { font-size:35px; }.atlas-nav { flex-wrap:wrap; margin-top:18px; }.atlas-footer { gap:9px; }}@media(prefers-reduced-motion:reduce) { .atlas * { transition:none!important; } }
25 unmodified lines26272829303132333435363725 unmodified linesconst tooltip = element.querySelector('.atlas-tooltip');if (tooltip) tooltip.hidden = true;});// Newly expanded columns appear on the right; keep them in view after each update.let shownRoute = element.querySelector('.life-tree')?.dataset.route;new MutationObserver(() => {const route = element.querySelector('.life-tree')?.dataset.route;if (!route || route === shownRoute) return;shownRoute = route;const scroller = element.querySelector('.tree-scroll');if (scroller) requestAnimationFrame(() => { scroller.scrollLeft = scroller.scrollWidth; });}).observe(element, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-route']});25 unmodified lines26272829303132333435363738394041424344454625 unmodified linesconst tooltip = element.querySelector('.atlas-tooltip');if (tooltip) tooltip.hidden = true;});// Expanding adds a level below. The page scrolls, not the widget, so only nudge// it when the new bottom of the tree has fallen past the viewport.let shownRoute = element.querySelector('.life-tree')?.dataset.route;new MutationObserver(() => {const route = element.querySelector('.life-tree')?.dataset.route;if (!route || route === shownRoute) return;const grew = route.length > shownRoute.length;shownRoute = route;if (!grew) return;requestAnimationFrame(() => {const tree = element.querySelector('.life-tree');if (!tree) return;const bottom = tree.getBoundingClientRect().bottom;if (bottom > window.innerHeight) {window.scrollBy({top: Math.min(bottom - window.innerHeight + 24, 400), behavior: 'smooth'});}});}).observe(element, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-route']});
123457354 unmodified lines7360736173627363736473657366238 unmodified lines76057606760776087609761076111035 unmodified lines86478648864986508651865286531 unmodified line8655865686578658865986608661401 unmodified lines9063906490659066906790689069{"created_at": "2026-10-07T13:47:40.354639+00:00","sources": {"ncbi_taxonomy": "https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz","name_classes": [7354 unmodified lines"313693": "citrus nematode","314003": "bluebanded goby","314082": "pram bug","314145": "carnivores, bats and ungulates","314146": "primates and rodents","314147": "Rodents and rabbits","314285": "unknown marine gamma proteobacterium NOR5",238 unmodified lines"358446": "deep-sea limpets","358815": "black redstart","358819": "Isabelline wheatear","359160": "bamboo, rice and wheat grasses","360508": "javelin grunt","360967": "Great evening bat","363190": "Gray's grenadier anchovy",1035 unmodified lines"1324310": "pale-rose death cap","1328047": "Battersby's green snake","1328070": "greater bamboo lemur","1329799": "turtles, birds and crocodiles","1329912": "lizards and snakes","1329950": "lizards and snakes","1329961": "split-tongued squamates",1 unmodified line"1330544": "Old World anguimorph lizards","1333648": "Mekong tiger perch","1334976": "Pawak croaker","1338369": "lungfish and land vertebrates","1342827": "Ethiopian burrowing tree frog","1342833": "Erlanger's grass frog","1342840": "Shoa forest treefrog",401 unmodified lines"2677969": "Greater spotted eagle","2681549": "s__Sphingomonas_G profundi","2686024": "amoeboid protists","2687318": "single-celled animal relatives","2692011": "many-banded treefrog","2692248": "green algae","2696291": "brown algae and diatoms",123457354 unmodified lines7360736173627363736473657366238 unmodified lines76057606760776087609761076111035 unmodified lines86478648864986508651865286531 unmodified line8655865686578658865986608661401 unmodified lines9063906490659066906790689069{"created_at": "2026-10-07T15:57:39.505254+00:00","sources": {"ncbi_taxonomy": "https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz","name_classes": [7354 unmodified lines"313693": "citrus nematode","314003": "bluebanded goby","314082": "pram bug","314145": "carnivores, bats, ungulates","314146": "primates and rodents","314147": "Rodents and rabbits","314285": "unknown marine gamma proteobacterium NOR5",238 unmodified lines"358446": "deep-sea limpets","358815": "black redstart","358819": "Isabelline wheatear","359160": "bamboo, rice, wheat grasses","360508": "javelin grunt","360967": "Great evening bat","363190": "Gray's grenadier anchovy",1035 unmodified lines"1324310": "pale-rose death cap","1328047": "Battersby's green snake","1328070": "greater bamboo lemur","1329799": "turtles, birds, crocodiles","1329912": "lizards and snakes","1329950": "lizards and snakes","1329961": "split-tongued squamates",1 unmodified line"1330544": "Old World anguimorph lizards","1333648": "Mekong tiger perch","1334976": "Pawak croaker","1338369": "lungfish and tetrapods","1342827": "Ethiopian burrowing tree frog","1342833": "Erlanger's grass frog","1342840": "Shoa forest treefrog",401 unmodified lines"2677969": "Greater spotted eagle","2681549": "s__Sphingomonas_G profundi","2686024": "amoeboid protists","2687318": "single-celled animal kin","2692011": "many-banded treefrog","2692248": "green algae","2696291": "brown algae and diatoms",
42 unmodified lines4344454647484946 unmodified lines9697989910010110213 unmodified lines1161171181191201211226 unmodified lines12913013113213313413560 unmodified lines19619719819920020120242 unmodified lines1035538: ("Mamiellophyceae", "tiny marine green algae"),13792: ("Mamiellales", "tiny marine green algae"),127916: ("Ichthyosporea", "parasites of fish and kin"),2687318: ("Filasterea", "single-celled animal relatives"),2686024: ("Rotosphaerida", "amoeboid protists"),6042: ("Demospongiae", "common sponges"),1913637: ("Mucoromycota", "bread moulds and kin"),46 unmodified lines89593: ("Craniata", "animals with a skull"),117570: ("Teleostomi", "jawed vertebrates with bone"),8287: ("Sarcopterygii", "lobe-finned fish and kin"),1338369: ("Dipnotetrapodomorpha", "lungfish and land vertebrates"),186623: ("Actinopteri", "ray-finned fish"),41665: ("Neopterygii", "modern ray-finned fish"),1489341: ("Osteoglossocephalai", "bony-tongued fish and kin"),13 unmodified lines32519: ("Ostariophysi", "carps and catfish"),186626: ("Otophysi", "carps and catfish"),186627: ("Cypriniphysae", "carps and loaches"),1329799: ("Archelosauria", "turtles, birds and crocodiles"),8492: ("Archosauria", "birds and crocodiles"),436489: ("Saurischia", "dinosaurs, birds today"),436491: ("Theropoda", "dinosaurs, birds today"),6 unmodified lines32525: ("Theria", "live-bearing mammals"),1437010: ("Boreoeutheria", "most placental mammals"),314146: ("Euarchontoglires", "primates and rodents"),314145: ("Laurasiatheria", "carnivores, bats and ungulates"),376913: ("Haplorrhini", "monkeys, apes and tarsiers"),314293: ("Simiiformes", "monkeys and apes"),9526: ("Catarrhini", "Old World monkeys and apes"),60 unmodified lines4734: ("commelinids", "grasses, palms and kin"),38820: ("Poales", "grasses and sedges"),147368: ("Pooideae", "temperate grasses"),359160: ("BOP clade", "bamboo, rice and wheat grasses"),1648038: ("Triticodae", "wheat and barley grasses"),91827: ("Gunneridae", "core eudicot plants"),1437201: ("Pentapetalae", "core eudicot plants"),42 unmodified lines4344454647484946 unmodified lines9697989910010110213 unmodified lines1161171181191201211226 unmodified lines12913013113213313413560 unmodified lines19619719819920020120242 unmodified lines1035538: ("Mamiellophyceae", "tiny marine green algae"),13792: ("Mamiellales", "tiny marine green algae"),127916: ("Ichthyosporea", "parasites of fish and kin"),2687318: ("Filasterea", "single-celled animal kin"),2686024: ("Rotosphaerida", "amoeboid protists"),6042: ("Demospongiae", "common sponges"),1913637: ("Mucoromycota", "bread moulds and kin"),46 unmodified lines89593: ("Craniata", "animals with a skull"),117570: ("Teleostomi", "jawed vertebrates with bone"),8287: ("Sarcopterygii", "lobe-finned fish and kin"),1338369: ("Dipnotetrapodomorpha", "lungfish and tetrapods"),186623: ("Actinopteri", "ray-finned fish"),41665: ("Neopterygii", "modern ray-finned fish"),1489341: ("Osteoglossocephalai", "bony-tongued fish and kin"),13 unmodified lines32519: ("Ostariophysi", "carps and catfish"),186626: ("Otophysi", "carps and catfish"),186627: ("Cypriniphysae", "carps and loaches"),1329799: ("Archelosauria", "turtles, birds, crocodiles"),8492: ("Archosauria", "birds and crocodiles"),436489: ("Saurischia", "dinosaurs, birds today"),436491: ("Theropoda", "dinosaurs, birds today"),6 unmodified lines32525: ("Theria", "live-bearing mammals"),1437010: ("Boreoeutheria", "most placental mammals"),314146: ("Euarchontoglires", "primates and rodents"),314145: ("Laurasiatheria", "carnivores, bats, ungulates"),376913: ("Haplorrhini", "monkeys, apes and tarsiers"),314293: ("Simiiformes", "monkeys and apes"),9526: ("Catarrhini", "Old World monkeys and apes"),60 unmodified lines4734: ("commelinids", "grasses, palms and kin"),38820: ("Poales", "grasses and sedges"),147368: ("Pooideae", "temperate grasses"),359160: ("BOP clade", "bamboo, rice, wheat grasses"),1648038: ("Triticodae", "wheat and barley grasses"),91827: ("Gunneridae", "core eudicot plants"),1437201: ("Pentapetalae", "core eudicot plants"),
27 unmodified lines2829303132333435145 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152161 unmodified line2182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512521 unmodified line2542552562572582592602 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030118 unmodified lines3203213223233243253 unmodified lines32933033133233333433533633733833934034134234334434534661 unmodified lines40840941041141241341441541627 unmodified lines) """# Scientific names stay the primary label; English glosses are a secondary line.# See refresh_common_names.py for how the lookup is built.MAX_ENGLISH = 30MAX_LABEL = 24COLUMN_LIMIT = 6145 unmodified linesif depth < len(steps) and not any(item['selected'] for item in nodes):raise ValueError("Choose a eukaryotic taxon from this snapshot.")lineage = [taxon(t) for t, _ in steps]shortcuts = {t: encode_path((r['taxid'], 0) for r in self.lineage(conn, t)) for t in (33208, 33090, 4751)}return self.render(columns, steps, lineage, shortcuts, has_children=bool(tail))def render(self, columns, steps, lineage, shortcuts, has_children):top, chart, spacing, bar = 24, 460, 274, 14# Silhouettes are not square: they run from tall and thin to long and# flat. Fitting them all into one box turns most into slivers, so each# gets its own box with the same area and its own proportions.icon_area, icon_max, gutter = 23 * 23, 40, 46width = max(830, 40 + (len(columns) - 1) * spacing + bar + 250)height = top * 2 + chartdef stack(nodes):"""Sankey layout: bar heights follow assembly counts, with room for every label."""gap, slot = (12 if len(nodes) > 1 else 0), 46fixed, scale = set(), 0for _ in range(len(nodes) + 1):free = chart - gap * (len(nodes) - 1) - slot * len(fixed)flexible = sum(n['total'] for k, n in enumerate(nodes) if k not in fixed)scale = free / flexible if flexible else 0small = fixed | {k for k, n in enumerate(nodes) if n['total'] * scale < slot}if small == fixed:breakfixed = smally = topfor k, n in enumerate(nodes):room = slot if k in fixed else n['total'] * scalen['h'] = max(3, n['total'] * scale)n['y'] = y + (room - n['h']) / 2y += room + gapdef clip(text, limit):return text if len(text) <= limit else text[:limit - 2] + "…"1 unmodified linedef share(n):return n['covered'] / n['total'] if self.coverage and n['total'] else 0def ribbon(x0, a0, a1, x1, b0, b1, kind):bend = (x0 + x1) / 2return (f'<path d="M{x0},{a0:.1f} C{bend},{a0:.1f} {bend},{b0:.1f} {x1},{b0:.1f} 'f'L{x1},{b1:.1f} C{bend},{b1:.1f} {bend},{a1:.1f} {x0},{a1:.1f} Z" class="flow flow-{kind}"/>')flows, nodes = [], []for depth, column in enumerate(columns):stack(column)x = 40 + depth * spacingfor n in column:n['x'] = xfor depth, column in enumerate(columns[:-1]):parent = next((n for n in column if n['selected']), None)children = columns[depth + 1]if not parent:continuetotal = sum(c['total'] for c in children) or 1cursor = parent['y']for child in children:a0 = cursora1 = cursor + parent['h'] * child['total'] / totalcursor = a1f = share(child)am, bm = a0 + f * (a1 - a0), child['y'] + f * child['h']x0, x1 = parent['x'] + bar, child['x']if f > 0:flows.append(ribbon(x0, a0, am, x1, child['y'], bm, "annotated"))if f < 1:flows.append(ribbon(x0, am, a1, x1, bm, child['y'] + child['h'], "missing"))for depth, column in enumerate(columns):on_path = depth < len(steps)1 unmodified linefor n in column:if n['borrowed_icon'] and shown[n['icon']] > 1:n['icon'] = "" # identical borrowed outlines read as "same group"x, y, h = n['x'], n['y'], n['h']f = share(n)percent = 100 * ftitle = f"{n['name']} ({n['english']})" if n['english'] else n['name']2 unmodified linesif n.get('aggregate'):detail += " Display aggregate, not a taxonomic clade. Activate to see its lineages."elif not n.get('direct') and not n['selected']:detail += " Activate to expand this group to the right."action = "" if n.get('direct') else f'data-path="{n["path"]}" role="button" tabindex="0"'classes = "tree-node" + (" is-selected" if n['selected'] else " is-sibling" if on_path else "") + \(" is-direct" if n.get('direct') else "")nodes.append(f'<g class="{classes}" {action} aria-label="{escape(detail, quote=True)}" data-detail="{escape(detail, quote=True)}">')cy = y + h / 2nodes.append(f'<rect x="{x - 6}" y="{min(y, cy - 23):.1f}" width="{spacing - 40}" height="{max(h, 46):.1f}" rx="10" class="tree-hit"/>')green = h * fif green > 0:nodes.append(f'<rect x="{x}" y="{y:.1f}" width="{bar}" height="{green:.1f}" class="bar bar-annotated"/>')if green < h:nodes.append(f'<rect x="{x}" y="{y + green:.1f}" width="{bar}" height="{h - green:.1f}" class="bar bar-missing"/>')nodes.append(f'<rect x="{x}" y="{y:.1f}" width="{bar}" height="{h:.1f}" class="bar-outline"/>')label, english = clip(n['label'], MAX_LABEL), clip(n['english'], MAX_ENGLISH)stats = f"{percent:.1f}% · {n['covered']:,} / {n['total']:,}" if self.coverage else f"{n['total']:,} assemblies"# The gutter is reserved whether or not this node has a silhouette, so# labels stay aligned down the column.if n['icon']:ratio = self.icon_credits.get(n['icon'], {}).get('ratio') or 1.0icon_h = min(icon_max, max(6, math.sqrt(icon_area / ratio)))icon_w = min(icon_max, max(6, icon_h * ratio))icon_h = min(icon_max, max(6, icon_w / ratio))nodes.append(f'<image class="tree-icon" x="{x + bar + 8 + (gutter - 12 - icon_w) / 2:.1f}" y="{cy - icon_h / 2:.1f}" 'f'width="{icon_w:.1f}" height="{icon_h:.1f}" 'f'href="{ICON_ROUTE}{ICON_DIR / (n["icon"] + ".svg")}"/>')text_x = x + bar + 8 + gutter# Three lines when there is an English gloss, two without, both centred on the bar.head, stat_line = (cy - 10, cy + 16) if english else (cy - 3, cy + 13)nodes.append(f'<text x="{text_x}" y="{head:.1f}" class="tree-label">{escape(label)}</text>')if english:nodes.append(f'<text x="{text_x}" y="{cy + 3:.1f}" class="tree-english">{escape(english)}</text>')nodes.append(f'<text x="{text_x}" y="{stat_line:.1f}" class="tree-count">{stats}</text></g>')svg = (f'<svg viewBox="0 0 {width} {height}" class="life-tree" data-route="{encode_path(steps)}" style="min-width:{width if width > 1040 else 760}px" 'f'aria-label="Eukaryotic taxonomy and annotation coverage">' + ''.join(flows) + ''.join(nodes) + '</svg>')focus = next(n for n in columns[len(steps) - 1] if n['selected'])18 unmodified lineselse:summary = f'<div class="atlas-kicker">{escape(selected_name)}</div><div class="atlas-summary"><strong>{total:,}</strong><span>GenBank assemblies<br>Coverage unavailable</span></div>'legend = '<div class="atlas-legend"><i class="atlas-swatch atlas-missing"></i><span>Assemblies · coverage unavailable</span></div>'leaf_note = '<p class="atlas-leaf-note">This is a terminal taxon in the assembly snapshot. Use the breadcrumb to explore its relatives.</p>' if not has_children else ''return f'''<section class="atlas" aria-label="Tree of eukaryotic life"><header class="atlas-header">3 unmodified lines<div class="atlas-summary-block">{summary}</div></header><nav class="atlas-nav" aria-label="Explore major lineages"><div class="atlas-shortcuts"><button data-path="{DEFAULT_PATH}">All eukaryotes</button><button data-path="{shortcuts[33208]}">Animals</button><button data-path="{shortcuts[33090]}">Green plants</button><button data-path="{shortcuts[4751]}">Fungi</button></div><button class="atlas-back" data-path="{parent}">← Collapse last group</button></nav><div class="atlas-breadcrumb">{breadcrumbs}</div><div class="tree-scroll" tabindex="0" aria-label="Interactive tree. Scroll horizontally to see deeper lineages.">{svg}</div>{leaf_note}<div class="atlas-tooltip" role="tooltip" hidden></div><footer class="atlas-footer">{legend}<span>Click a group to expand it to the right <span class="atlas-mobile-hint">· Swipe to explore</span></span><span class="atlas-date">Updated {stamp}</span></footer><div class="atlas-footnote">Bar and flow heights are proportional to assembly counts within each column; each column is rescaled to fill the height, so compare sizes within a column. Coverage counts assemblies with published annotations, including partial assemblies.</div></section>'''61 unmodified lineswith gr.Accordion("About the tree and coverage", open=False, elem_classes="atlas-disclosure"):gr.Markdown("This tree follows **NCBI Taxonomy within Eukaryota**. Animals and fungi share the Opisthokonta branch; ""green plants include green algae. ‘Other lineages’ combines the remaining siblings for display and can be expanded. ""Each expanded group adds a column on the right with up to six direct lineages plus any remainder, so every ancestor stays visible. ""The opening view also expands the animal/fungal branch. Bars and flows are drawn like a Sankey diagram: ""heights follow **actual assembly counts** within each column, split into annotated and not-annotated assemblies.\n\n""Each group shows its scientific name with a plain-English name underneath where one is available. These come from ""NCBI Taxonomy's common names plus a curated set of short glosses for the large unranked clades NCBI leaves unnamed, ""such as Opisthokonta (animals and fungi) or Ecdysozoa (moulting animals). The glosses describe the living members of a "27 unmodified lines2829303132333435363738394041145 unmodified lines1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312321 unmodified line2342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672681 unmodified line2702712722732742752762 unmodified lines27928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631718 unmodified lines3363373383393403413423 unmodified lines34634734834935035135235335435535635735835936036161 unmodified lines42342442542642742842943043143227 unmodified lines) """# Scientific names stay the primary label; English glosses are a secondary line.# See refresh_common_names.py for how the lookup is built.MAX_ENGLISH = 28MAX_LABEL = 22# Jumping-off points above the tree. Each one expands its whole lineage, so a# deep pick like humans is also the quickest way to see what a full path looks# like. Order runs broad to narrow.SHORTCUTS = ((33208, "Animals"), (40674, "Mammals"), (9606, "Humans"), (8782, "Birds"),(7898, "Ray-finned fish"), (50557, "Insects"), (6142, "Jellyfish"),(33090, "Green plants"), (3398, "Flowering plants"), (4751, "Fungi"))COLUMN_LIMIT = 6145 unmodified linesif depth < len(steps) and not any(item['selected'] for item in nodes):raise ValueError("Choose a eukaryotic taxon from this snapshot.")lineage = [taxon(t) for t, _ in steps]shortcuts = {t: encode_path((r['taxid'], 0) for r in self.lineage(conn, t)) for t, _ in SHORTCUTS}return self.render(columns, steps, lineage, shortcuts, has_children=bool(tail))def render(self, columns, steps, lineage, shortcuts, has_children):"""Levels run down the page, so a whole lineage is one page scroll.Each level is a horizontal band: bar widths follow assembly counts andthe label sits beneath its bar. Depth now costs height, which the pagecan always give, rather than width, which it cannot."""left, span, bar, top = 16, 1180, 15, 18rung = 172 # distance from one level's bar to the nextlabel_gap, line = 11, 15# Silhouettes are not square: they run from tall and thin to long and# flat. Fitting them all into one box turns most into slivers, so each# gets its own box with the same area and its own proportions.icon_area, icon_max, icon_band = 24 * 24, 42, 44block = bar + icon_band + 3 * line # a level's bar plus the caption under itwidth = left * 2 + spanheight = top + (len(columns) - 1) * rung + block + 14def spread(nodes):"""Bar widths follow assembly counts, with room under each for its label."""gap, slot = (14 if len(nodes) > 1 else 0), 148fixed, scale = set(), 0for _ in range(len(nodes) + 1):free = span - gap * (len(nodes) - 1) - slot * len(fixed)flexible = sum(n['total'] for k, n in enumerate(nodes) if k not in fixed)scale = free / flexible if flexible else 0small = fixed | {k for k, n in enumerate(nodes) if n['total'] * scale < slot}if small == fixed:breakfixed = smallx = leftfor k, n in enumerate(nodes):room = slot if k in fixed else n['total'] * scalen['w'] = max(3, n['total'] * scale)n['x'] = x + (room - n['w']) / 2n['slot'], n['slot_x'] = room, xx += room + gapdef clip(text, limit):return text if len(text) <= limit else text[:limit - 2] + "…"1 unmodified linedef share(n):return n['covered'] / n['total'] if self.coverage and n['total'] else 0def ribbon(y0, a0, a1, y1, b0, b1, kind):bend = (y0 + y1) / 2return (f'<path d="M{a0:.1f},{y0} C{a0:.1f},{bend} {b0:.1f},{bend} {b0:.1f},{y1} 'f'L{b1:.1f},{y1} C{b1:.1f},{bend} {a1:.1f},{bend} {a1:.1f},{y0} Z" class="flow flow-{kind}"/>')flows, nodes = [], []for depth, column in enumerate(columns):spread(column)y = top + depth * rungfor n in column:n['y'] = yfor depth, column in enumerate(columns[:-1]):parent = next((n for n in column if n['selected']), None)children = columns[depth + 1]if not parent:continuetotal = sum(c['total'] for c in children) or 1cursor = parent['x']for child in children:a0 = cursora1 = cursor + parent['w'] * child['total'] / totalcursor = a1f = share(child)am, bm = a0 + f * (a1 - a0), child['x'] + f * child['w']y0, y1 = parent['y'] + block, child['y']if f > 0:flows.append(ribbon(y0, a0, am, y1, child['x'], bm, "annotated"))if f < 1:flows.append(ribbon(y0, am, a1, y1, bm, child['x'] + child['w'], "missing"))for depth, column in enumerate(columns):on_path = depth < len(steps)1 unmodified linefor n in column:if n['borrowed_icon'] and shown[n['icon']] > 1:n['icon'] = "" # identical borrowed outlines read as "same group"x, y, w = n['x'], n['y'], n['w']f = share(n)percent = 100 * ftitle = f"{n['name']} ({n['english']})" if n['english'] else n['name']2 unmodified linesif n.get('aggregate'):detail += " Display aggregate, not a taxonomic clade. Activate to see its lineages."elif not n.get('direct') and not n['selected']:detail += " Activate to open this group below."action = "" if n.get('direct') else f'data-path="{n["path"]}" role="button" tabindex="0"'classes = "tree-node" + (" is-selected" if n['selected'] else " is-sibling" if on_path else "") + \(" is-direct" if n.get('direct') else "")nodes.append(f'<g class="{classes}" {action} aria-label="{escape(detail, quote=True)}" data-detail="{escape(detail, quote=True)}">')centre = n['slot_x'] + n['slot'] / 2nodes.append(f'<rect x="{n["slot_x"] - 5:.1f}" y="{y - 6}" width="{n["slot"] + 10:.1f}" 'f'height="{block:.0f}" rx="12" class="tree-hit"/>')green = w * fif green > 0:nodes.append(f'<rect x="{x:.1f}" y="{y}" width="{green:.1f}" height="{bar}" class="bar bar-annotated"/>')if green < w:nodes.append(f'<rect x="{x + green:.1f}" y="{y}" width="{w - green:.1f}" height="{bar}" class="bar bar-missing"/>')nodes.append(f'<rect x="{x:.1f}" y="{y}" width="{w:.1f}" height="{bar}" class="bar-outline"/>')label, english = clip(n['label'], MAX_LABEL), clip(n['english'], MAX_ENGLISH)stats = f"{percent:.1f}% · {n['covered']:,} / {n['total']:,}" if self.coverage else f"{n['total']:,} assemblies"# The silhouette band is reserved whether or not this node has one,# so labels sit on the same baseline right across a level.if n['icon']:ratio = self.icon_credits.get(n['icon'], {}).get('ratio') or 1.0icon_h = min(icon_max, max(6, math.sqrt(icon_area / ratio)))icon_w = min(icon_max, max(6, icon_h * ratio))icon_h = min(icon_max, max(6, icon_w / ratio))nodes.append(f'<image class="tree-icon" x="{centre - icon_w / 2:.1f}" 'f'y="{y + bar + label_gap + (icon_band - label_gap - icon_h) / 2:.1f}" 'f'width="{icon_w:.1f}" height="{icon_h:.1f}" 'f'href="{ICON_ROUTE}{ICON_DIR / (n["icon"] + ".svg")}"/>')text_y = y + bar + icon_band + linenodes.append(f'<text x="{centre:.1f}" y="{text_y:.0f}" class="tree-label">{escape(label)}</text>')if english:nodes.append(f'<text x="{centre:.1f}" y="{text_y + line:.0f}" class="tree-english">{escape(english)}</text>')nodes.append(f'<text x="{centre:.1f}" y="{text_y + (2 if english else 1) * line:.0f}" class="tree-count">{stats}</text></g>')svg = (f'<svg viewBox="0 0 {width} {height}" class="life-tree" data-route="{encode_path(steps)}" 'f'aria-label="Eukaryotic taxonomy and annotation coverage">' + ''.join(flows) + ''.join(nodes) + '</svg>')focus = next(n for n in columns[len(steps) - 1] if n['selected'])18 unmodified lineselse:summary = f'<div class="atlas-kicker">{escape(selected_name)}</div><div class="atlas-summary"><strong>{total:,}</strong><span>GenBank assemblies<br>Coverage unavailable</span></div>'legend = '<div class="atlas-legend"><i class="atlas-swatch atlas-missing"></i><span>Assemblies · coverage unavailable</span></div>'jumps = ''.join(f'<button data-path="{shortcuts[t]}">{escape(name)}</button>' for t, name in SHORTCUTS)leaf_note = '<p class="atlas-leaf-note">This is a terminal taxon in the assembly snapshot. Use the breadcrumb to explore its relatives.</p>' if not has_children else ''return f'''<section class="atlas" aria-label="Tree of eukaryotic life"><header class="atlas-header">3 unmodified lines<div class="atlas-summary-block">{summary}</div></header><nav class="atlas-nav" aria-label="Explore major lineages"><div class="atlas-shortcuts"><button data-path="{DEFAULT_PATH}">All eukaryotes</button>{jumps}</div><button class="atlas-back" data-path="{parent}">← Collapse last group</button></nav><div class="atlas-breadcrumb">{breadcrumbs}</div><div class="tree-scroll" tabindex="0" aria-label="Interactive tree. Scroll horizontally to see deeper lineages.">{svg}</div>{leaf_note}<div class="atlas-tooltip" role="tooltip" hidden></div><footer class="atlas-footer">{legend}<span>Click a group to open it below</span><span class="atlas-date">Updated {stamp}</span></footer><div class="atlas-footnote">Bar and flow widths are proportional to assembly counts within each level; each level is rescaled to fill the width, so compare sizes within a level. Coverage counts assemblies with published annotations, including partial assemblies.</div></section>'''61 unmodified lineswith gr.Accordion("About the tree and coverage", open=False, elem_classes="atlas-disclosure"):gr.Markdown("This tree follows **NCBI Taxonomy within Eukaryota**. Animals and fungi share the Opisthokonta branch; ""green plants include green algae. ‘Other lineages’ combines the remaining siblings for display and can be expanded. ""Each expanded group adds a level below it with up to six direct lineages plus any remainder, so every ancestor stays visible ""and a whole lineage reads as one page scroll. The opening view also expands the animal/fungal branch. Bars and flows ""are drawn like a Sankey diagram: widths follow **actual assembly counts** within each level, split into annotated ""and not-annotated assemblies.\n\n""Each group shows its scientific name with a plain-English name underneath where one is available. These come from ""NCBI Taxonomy's common names plus a curated set of short glosses for the large unranked clades NCBI leaves unnamed, ""such as Opisthokonta (animals and fungi) or Ecdysozoa (moulting animals). The glosses describe the living members of a "
3 unmodified lines456789102 unmodified lines131415161718192021222324252673 unmodified lines1001011021031041051061071081091101111129 unmodified lines1221231241251261271281293 unmodified linesimport unittestfrom refresh_common_names import CURATEDfrom taxonomy import COMMON_NAMES, DATABASE, DEFAULT_PATH, ICON_DIR, ICONS, MAX_ENGLISH, Taxonomy@unittest.skipUnless(DATABASE.exists(), "taxonomy snapshot unavailable")2 unmodified linesdef setUpClass(cls):cls.taxonomy = Taxonomy()def columns(self, html):return sorted({float(x) for x in re.findall(r'<rect x="([\d.]+)" y="[\d.]+" width="14"', html)})def test_expansion_keeps_every_ancestor_column(self):self.assertEqual(len(self.columns(self.taxonomy.view("2759"))), 2)self.assertEqual(len(self.columns(self.taxonomy.view(DEFAULT_PATH))), 3)html = self.taxonomy.view("2759/33154/33208")self.assertEqual(len(self.columns(html)), 4)self.assertEqual(html.count('class="tree-node is-selected"'), 3)def test_search_path_expands_lineage(self):73 unmodified linesself.skipTest("silhouettes unavailable")for path in ("2759", DEFAULT_PATH, "2759/33154/33208", "2759/33154/33208/6072/33213"):html = self.taxonomy.view(path)# Columns are laid out left to right, so group the icons by their x.drawn = re.findall(r'<image class="tree-icon" x="([\d.]+)"[^>]*?/data/icons/([0-9a-f-]+)\.svg"', html)columns = {}for x, image in drawn:columns.setdefault(round(float(x)), []).append(image)for x, images in columns.items():self.assertEqual(len(images), len(set(images)), f"{path} column at {x}")def test_chart_references_icons_by_url(self):if not self.taxonomy.icons:9 unmodified linesfor path in ("2759", DEFAULT_PATH, "2759/33154/33208"):box = re.search(r'<svg viewBox="0 0 ([\d.]+) ([\d.]+)"', self.taxonomy.view(path))self.assertIsNotNone(box, path)self.assertGreater(float(box.group(1)), 500, path)self.assertGreater(float(box.group(2)), 400, path)def test_rejects_paths_outside_the_tree(self):for path in ("1", "33208", "2759/33208", "2759/2759~3", "2759/9606", "abc"):3 unmodified lines456789102 unmodified lines13141516171819202122232425262728293073 unmodified lines1041051061071081091101111121131141151169 unmodified lines1261271281291301311321331341351361371381391401411423 unmodified linesimport unittestfrom refresh_common_names import CURATEDfrom taxonomy import COMMON_NAMES, DATABASE, DEFAULT_PATH, ICON_DIR, ICONS, MAX_ENGLISH, SHORTCUTS, Taxonomy@unittest.skipUnless(DATABASE.exists(), "taxonomy snapshot unavailable")2 unmodified linesdef setUpClass(cls):cls.taxonomy = Taxonomy()def levels(self, html):"""Each level sits at its own y; bars are horizontal with a fixed height."""return sorted({float(y) for y in re.findall(r'<rect x="[\d.]+" y="([\d.]+)" width="[\d.]+" height="15" class="bar-outline"', html)})def test_expansion_keeps_every_ancestor_level(self):self.assertEqual(len(self.levels(self.taxonomy.view("2759"))), 2)self.assertEqual(len(self.levels(self.taxonomy.view(DEFAULT_PATH))), 3)html = self.taxonomy.view("2759/33154/33208")levels = self.levels(html)self.assertEqual(len(levels), 4)# Levels run down the page, evenly spaced, so depth costs height not width.self.assertEqual({round(b - a) for a, b in zip(levels, levels[1:])}, {172})self.assertEqual(html.count('class="tree-node is-selected"'), 3)def test_search_path_expands_lineage(self):73 unmodified linesself.skipTest("silhouettes unavailable")for path in ("2759", DEFAULT_PATH, "2759/33154/33208", "2759/33154/33208/6072/33213"):html = self.taxonomy.view(path)# Levels are laid out top to bottom, so group the icons by their y.drawn = re.findall(r'<image class="tree-icon" x="[\d.]+" y="([\d.]+)"[^>]*?/data/icons/([0-9a-f-]+)\.svg"', html)levels = {}for y, image in drawn:levels.setdefault(round(float(y)), []).append(image)for y, images in levels.items():self.assertEqual(len(images), len(set(images)), f"{path} level at {y}")def test_chart_references_icons_by_url(self):if not self.taxonomy.icons:9 unmodified linesfor path in ("2759", DEFAULT_PATH, "2759/33154/33208"):box = re.search(r'<svg viewBox="0 0 ([\d.]+) ([\d.]+)"', self.taxonomy.view(path))self.assertIsNotNone(box, path)self.assertGreater(float(box.group(1)), 1000, path)self.assertGreater(float(box.group(2)), 300, path)def test_shortcuts_expand_their_whole_lineage(self):html = self.taxonomy.view(DEFAULT_PATH)for taxid, name in SHORTCUTS:self.assertIn(f">{name}</button>", html)path = self.taxonomy.taxon_path(taxid)self.assertIn(f'data-path="{path}"', html)self.assertTrue(path.startswith("2759/"), name)self.assertTrue(path.endswith(f"/{taxid}"), name)def test_rejects_paths_outside_the_tree(self):for path in ("1", "33208", "2759/33208", "2759/2759~3", "2759/9606", "abc"):
README.md+1-1
atlas.css+6-4
atlas.js+12-3
data/common_names.json+6-6
refresh_common_names.py+5-5
taxonomy.py+72-56
tests/test_taxonomy.py+29-16