679b48855a32f8ea1e1ea8ca3c095a0c2c7f6c7a
max
  Tue Sep 8 10:08:41 2026 -0700
detailsScript: add a scatterPlot plot type, and use it for pcLAI

Clicking a pcLAI window now shows where that window sits in the ancestry space
it was placed in: a scatterplot of the 1000 Genomes reference haplotypes with
the window's own PCA coordinate and its segment's coordinate marked on it. The
numbers were already on the details page and told a reader almost nothing.

New plot type scatterPlot (hg/js/hgc.scatterPlot.js), driven the same way as
histogram. Background points come from a JSON or TSV file named by dataUrl and
may carry a category, which colors them and builds a legend, and a label, which
is shown on mouseover. The cloud is drawn on a canvas, since these files hold
thousands of points and that many <circle> elements make the page crawl; axes
and the highlighted points stay SVG on top. Point lookup for the mouseover goes
through a cell index so a large file stays smooth.

Two additions serve every plot type, not just this one:

- exportFields, a config key listing further bigBed fields whose values are
passed to the module as a fieldValues object. Without it a plot needing two
coordinates would need them packed into one field, and pcLAI keeps them in
pca and pcaSegment. Only fields that exist in the bigBed are exported, at
most 32, and the JSON types are checked rather than asserted because
jsonListVal and jsonStringVal errAbort and this JSON is written by a hub.

- a config key ending in Url is treated as a file, by the convention
trackSettingIsFile() already uses, and a relative one is resolved against the
track's own bigDataUrl. The module does not fetch it directly; it asks
hgTrackUi for it, the route facetedComposite uses for its metadata. That
checks the canonicalized path against the hubs on the cart and reads it with
udc, so a hub-relative path works even for a hub loaded from a local path
(the GenArk /gbdb hubs), no CORS header is needed, and a file outside a
connected hub cannot be read. Verified that /etc/passwd, file://, a dot-dot
escape, an unattached hub and an unrelated host are all refused with 400.
When the session has file caching off, hgc now exports udcTimeout the way
hgTrackUi does and the module POSTs, so the browser cannot answer from cache.

Fixes a crash reachable from any hub: "detailsScript.<plotType>.<field> null"
segfaulted hgc, because jsonObjectVal returns NULL for a JSON null and the hash
routines dereference it. This hit the shipped histogram type too.

trackDbSettingsGen.py stopped reading a setting's description at the first
"Example:" paragraph and never read <ul> at all, so it dropped everything after
the first example and every list item. That silently truncated 226 of the 264
descriptions, including spectrum's minGrayLevel/scoreMin/scoreMax bullets, and
would have dropped this whole scatterPlot section. It now skips the Example
label instead of stopping, and folds list items in. No setting loses a word and
none gains or loses an example.

pcLAI wiring: the background file is the authors' published reference panel
(github.com/AI-sandbox/hprc-pclai reference_pca_metadata.tsv), converted by
hprc2annotMakePclaiRefPanel.py -- 3122 haplotypes, 21 populations, 94 KB, one
file for the collection since it is the reference space rather than per-assembly
data. The four values pcaSegment takes across all 460 assemblies turn out to be
the four continental cluster centres, so the highlighted segment dot always
lands on one of them.

genark: addContrib now rewrites a "...Url" inside a detailsScript value the same
way it rewrites bigDataUrl, and symlinks the collection's shared root-level data
files next to the docs, so contrib/<name>/<file> resolves in the deeper GenArk
layout. It writes the alpha tier only, leaving the assembly's default hub alone,
and clears any unmarked copy of the collection's stanzas that the assembly build
baked in, which would otherwise leave the hub declaring each track twice.

refs #35415

diff --git src/hg/makeDb/scripts/hprc2annot/hprc2annotMakePclaiRefPanel.py src/hg/makeDb/scripts/hprc2annot/hprc2annotMakePclaiRefPanel.py
new file mode 100755
index 00000000000..5ce31ec5c2c
--- /dev/null
+++ src/hg/makeDb/scripts/hprc2annot/hprc2annotMakePclaiRefPanel.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+"""Build the pcLAI reference-panel scatterplot data file for the hprc2annot hub.
+
+The pcLAI authors publish the PCA coordinates of the 1000 Genomes reference
+haplotypes that define the ancestry space each pcLAI window is placed in:
+
+  https://github.com/AI-sandbox/hprc-pclai/blob/main/reference_pca_metadata.tsv
+
+That table is turned into the compact JSON the hgc.scatterPlot.js module reads,
+which the pclai track points at with its detailsScript.scatterPlot setting.
+
+Population names are held in a separate list and referenced by index, because the
+descriptors are long and repeat across thousands of haplotypes; each point also
+carries its own haplotype id, which hgc.scatterPlot.js shows on mouseover.
+
+  hprc2annotMakePclaiRefPanel.py <reference_pca_metadata.tsv> <out.json>
+"""
+import sys
+import csv
+import json
+
+# The published TSV has one mis-decoded en dash (U+00D0 where an en dash belongs),
+# which would otherwise show up in the plot legend.
+FIXUPS = {"Ð": "-"}
+
+
+def clean(s):
+    for bad, good in FIXUPS.items():
+        s = s.replace(bad, good)
+    # collapse the whitespace a fixup can leave behind
+    return " ".join(s.split())
+
+
+def main():
+    if len(sys.argv) != 3:
+        sys.exit(__doc__)
+    inFname, outFname = sys.argv[1], sys.argv[2]
+
+    labels = []
+    labelIdx = {}
+    points = []
+    with open(inFname, encoding="utf-8") as fh:
+        for row in csv.DictReader(fh, delimiter="\t"):
+            try:
+                x = float(row["x1"])
+                y = float(row["x2"])
+            except (TypeError, ValueError):
+                continue
+            pop = clean(row.get("Population_descriptor") or "")
+            if pop not in labelIdx:
+                labelIdx[pop] = len(labels)
+                labels.append(pop)
+            hap = clean(row.get("Sample_hap") or row.get("Sample") or "")
+            # 3 decimals is finer than one screen pixel over this ~2.6 unit range
+            points.append([round(x, 3), round(y, 3), labelIdx[pop], hap])
+
+    if not points:
+        sys.exit("no usable rows in %s" % inFname)
+
+    # Order labels by their cluster's PC1 then PC2, so the legend reads in the same
+    # left-to-right order as the clusters appear in the plot.
+    sums = {}
+    for x, y, li, _hap in points:
+        sx, sy, n = sums.get(li, (0.0, 0.0, 0))
+        sums[li] = (sx + x, sy + y, n + 1)
+    order = sorted(range(len(labels)),
+                   key=lambda li: (sums[li][0] / sums[li][2], sums[li][1] / sums[li][2]))
+    remap = {old: new for new, old in enumerate(order)}
+    labels = [labels[old] for old in order]
+    points = [[x, y, remap[li], hap] for x, y, li, hap in points]
+
+    with open(outFname, "w", encoding="utf-8") as out:
+        json.dump({"labels": labels, "points": points}, out, separators=(",", ":"))
+        out.write("\n")
+
+    sys.stderr.write("%s: %d points, %d populations\n"
+                     % (outFname, len(points), len(labels)))
+
+
+if __name__ == "__main__":
+    main()