aminoAcid = {
return {A: "Ala", R: "Arg", N: "Asn", D: "Asp", C: "Cys", Q: "Gln", E: "Glu", G: "Gly", H: "His", I: "Ile",
L: "Leu", K: "Lys", M: "Met", F: "Phe", P: "Pro", S: "Ser", T: "Thr", W: "Trp", Y: "Tyr", V: "Val", "*": "Stop"};
}{
const enable = (view, on) => view.querySelectorAll("input").forEach(el => el.disabled = !on);
enable(viewof mutPos, mutType !== "None");
const writes = mutType === "Substitution" || mutType === "Insertion";
enable(viewof mutText, writes);
enable(viewof mutBase, writes && !typed);
enable(viewof mutLen, mutType !== "None" && !(writes && typed));
}// Splits a DNA string into codons. `read` is false after a stop codon.
function translate(seq) {
const table = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG";
const codons = [];
let read = true;
for (let i = 0; i < seq.length; i += 3) {
const bases = seq.slice(i, i + 3);
const [a, b, c] = [...bases].map(ch => "TCAG".indexOf(ch));
const aa = bases.length === 3 ? table[16 * a + 4 * b + c] : null;
codons.push({bases, aa, start: i, read: read && aa !== null});
if (aa === "*") read = false;
}
return codons;
}// Applies one mutation and works out what it does to the protein.
// `bases` are the letters to write (substitution and insertion). `len` is the base count for the other types.
// Underneath there are only three operations: a duplication is an insertion of a copy, and an
// inversion overwrites a stretch with its reverse complement.
function mutate(gene, type, pos, bases, len) {
const flip = t => [...t].reverse().map(b => ({A: "T", T: "A", G: "C", C: "G"})[b]).join("");
const op = type === "Duplication" ? "Insertion" : type === "Inversion" ? "Substitution" : type;
const first = Math.min(pos - 1, gene.length - len);
const write = type === "Duplication" ? gene.slice(first, first + len) : type === "Inversion" ? flip(gene.slice(first, first + len)) : bases;
const n = op === "None" ? 0 : op === "Deletion" ? len : write.length;
const i = type === "Duplication" ? first + len : op === "Insertion" ? pos - 1 : Math.min(pos - 1, gene.length - n);
const sub = op === "Substitution";
const seq = sub ? gene.slice(0, i) + write + gene.slice(i + n)
: op === "Insertion" ? gene.slice(0, i) + write + gene.slice(i)
: op === "Deletion" ? gene.slice(0, i) + gene.slice(i + n)
: gene;
const before = translate(gene), after = translate(seq);
const c = Math.floor(i / 3);
const stop = after.findIndex(d => d.aa === "*");
const plural = n > 1 ? "s" : "";
// For a substitution or inversion: the codons whose letters changed.
const touched = sub ? d3.range(before.length).filter(k => before[k].bases !== after[k].bases) : [];
const swaps = touched.map(k => `Codon ${k + 1} changes from ${before[k].bases} (${aminoAcid[before[k].aa]}) to ${after[k].bases} (${aminoAcid[after[k].aa]}).`).join(" ");
const lead = type === "Inversion" ? `Flipping ${n} base${plural} writes the opposite strand's letters in reverse order. ` : "";
let name = "No mutation", text = "This is the normal sequence. Pick a mutation type to change it.", shifted = false;
if (op !== "None" && !n) {
name = "Nothing typed";
text = "Type one or more of the letters A, T, G and C in the box.";
} else if (op !== "None" && seq === gene) {
name = "No change";
text = type === "Inversion" ? "This stretch reads the same on both strands, so flipping it changes nothing."
: `${n > 1 ? `Positions ${i + 1} to ${i + n} are` : `Position ${pos} is`} already ${write}. Try something different.`;
} else if (sub && touched.every(k => before[k].aa === after[k].aa)) {
name = "Silent mutation";
text = `${lead}${swaps} The amino acid${touched.length > 1 ? "s are" : " is"} the same, so the protein is unchanged.`;
} else if (sub && stop >= 0) {
name = "Nonsense mutation";
text = `${lead}${swaps} ${after[stop].bases} is a stop signal, so the protein ends after ${stop} amino acids.`;
} else if (sub) {
name = "Missense mutation";
text = `${lead}${swaps} Every other amino acid stays the same.`;
} else if (n) {
shifted = n % 3 !== 0;
const verb = type === "Duplication" ? "Copying" : type === "Insertion" ? "Adding" : "Removing";
name = shifted ? "Frameshift" : `In-frame ${type.toLowerCase()}`;
text = shifted
? `${verb} ${n} base${plural} shifts the reading frame. From codon ${c + 1} onward, the bases are grouped into different threes.`
: `${verb} ${n} bases keeps the reading frame, so the codons after the change are read as before.`;
text += stop >= 0 ? ` A stop signal now appears at codon ${stop + 1}, so the protein is cut short.`
: shifted ? "" : ` The protein is ${n / 3 === 1 ? "one amino acid" : `${n / 3} amino acids`} ${op === "Insertion" ? "longer" : "shorter"}.`;
}
// Where each base of the new sequence came from (-1 = new). A codon is unchanged
// only if its three bases are an original codon, still in the original frame.
const from = op === "Insertion" ? [...d3.range(i), ...Array(n).fill(-1), ...d3.range(i, gene.length)]
: op === "Deletion" ? [...d3.range(i), ...d3.range(i + n, gene.length)]
: d3.range(gene.length).map(j => seq[j] !== gene[j] ? -1 : j);
const intact = d => d.aa !== null && from[d.start] % 3 === 0 && from[d.start + 1] === from[d.start] + 1 && from[d.start + 2] === from[d.start] + 2;
const kept = new Set(after.filter(intact).map(d => from[d.start] / 3));
after.forEach((d, k) => d.diff = d.aa !== null && !intact(d) && !(sub && before[k].aa === d.aa));
before.forEach((d, j) => d.diff = !kept.has(j) && !(sub && after[j].aa === d.aa));
const hot = new Set(d3.range(i, i + n).filter(j => !sub || seq[j] !== gene[j]));
// One entry per base pair for the 3D model: the 30 original pairs, then 6 spares for insertions.
const items = [...gene].map((b, j) =>
sub ? {base: seq[j], slot: j, on: 1, hot: seq[j] !== b}
: op === "Insertion" ? {base: b, slot: j < i ? j : j + n, on: 1, hot: false}
: op === "Deletion" && j >= i ? (j < i + n ? {base: b, slot: i - 0.5, on: 0, hot: true} : {base: b, slot: j - n, on: 1, hot: false})
: {base: b, slot: j, on: 1, hot: false});
const spares = d3.range(6).map(k => ({base: write[k] || "A", slot: i + Math.min(k, Math.max(n - 1, 0)), on: +(op === "Insertion" && k < n), hot: true}));
const old = gene.slice(i, i + n);
return {
type, seq, before, after, name, text, shifted, items: [...items, ...spares],
changed: seq !== gene,
hotBefore: op === "Insertion" ? new Set() : hot,
hotAfter: op === "Deletion" ? new Set() : hot,
gone: op === "Deletion",
marks: seq === gene ? [] : op === "Deletion" ? [i - 0.5] : d3.range(i, i + n),
tag: seq === gene ? "" : type === "Inversion" ? `${old} ⇄ ${write}` : type === "Duplication" ? `${write} × 2`
: sub ? `${old} → ${write}` : op === "Insertion" ? `+ ${write}` : `− ${old}`
};
}function sequenceView(m, posInput, rna) {
const row = (label, codons, hot, hotClass, clickable, asRna) => `<div class="seq-row"><span class="seq-label">${label}</span>${
codons.map(c => {
const cls = ["codon", c.diff && "diff", c.aa === "*" && c.read && "stop", !c.read && "unread"].filter(Boolean).join(" ");
const letters = [...c.bases].map((b, j) => {
const p = c.start + j;
return `<b style="color:${baseColor[b]}" class="${hot.has(p) ? hotClass : ""}" ${clickable ? `data-pos="${p + 1}"` : ""}>${asRna && b === "T" ? "U" : b}</b>`;
}).join("");
return `<span class="${cls}"><span>${letters}</span>${asRna ? "" : `<small>${c.aa ? aminoAcid[c.aa] : "–"}</small>`}</span>`;
}).join("")}</div>`;
const box = document.createElement("div");
box.className = "seq";
box.innerHTML = row("Original", m.before, m.hotBefore, m.gone ? "gone" : "hot", true, false)
+ row("Mutated", m.after, m.hotAfter, "hot", false, false)
+ (rna ? row("mRNA", m.after, m.hotAfter, "hot", false, true) : "");
box.onclick = e => {
const b = e.target.closest("[data-pos]");
if (b) setInput(posInput, Math.max(4, +b.dataset.pos));
};
return box;
}// The start of three human genes (first 30 bases of the coding sequence).
// `known` lists named variants: a setting of the controls and what it does to a person.
strands = [
{name: "Hemoglobin (HBB)", seq: "ATGGTGCATCTGACTCCTGAGGAGAAGTCT", source: "https://databases.lovd.nl/shared/refseq/HBB_NM_000518.4_codingDNA.html", protein: "beta-globin",
makes: "beta-globin, half of the hemoglobin that carries oxygen in red blood cells",
loss: "With one working copy a person is usually a healthy carrier. With none, the result is beta-thalassemia major, a severe anemia.",
known: [
["Substitution", 20, "T", 1, "This is the sickle cell change (Hb S). With it in both copies of the gene, red blood cells bend into a sickle shape and block small vessels. One copy usually causes no illness."],
["Substitution", 19, "A", 1, "This is hemoglobin C. Two copies cause hemoglobin C disease, usually a mild anemia."],
["Substitution", 20, "C", 1, "This is Hb G-Makassar, a rare variant at the same base as sickle cell."],
["Deletion", 20, "A", 1, "This is a known beta-thalassemia change, called codon 6 (−A). This copy of the gene makes no working beta-globin."],
["Deletion", 17, "A", 2, "This is a known beta-thalassemia change, called codon 5 (−CT). This copy of the gene makes no working beta-globin."],
["Deletion", 25, "A", 2, "This is a known beta-thalassemia change, called codon 8 (−AA). This copy of the gene makes no working beta-globin."],
["Insertion", 28, "G", 1, "This is a known beta-thalassemia change, called codons 8/9 (+G). This copy of the gene makes no working beta-globin."]
]},
{name: "Insulin (INS)", seq: "ATGGCCCTGTGGATGCGCCTCCTGCCCCTG", source: "https://databases.lovd.nl/shared/refseq/INS_NM_000207.2_codingDNA.html", protein: "insulin",
makes: "the hormone that lets cells take up sugar from the blood",
loss: "One working copy is usually enough. With none, a baby cannot make insulin and has diabetes from birth.", known: []},
{name: "Growth hormone (GH1)", seq: "ATGGCTACAGGCTCCCGGACGTCCCTGCTC", source: "https://databases.lovd.nl/shared/refseq/GH1_NM_000515.3_codingDNA.html", protein: "growth hormone",
makes: "the hormone that tells a child's body to grow",
loss: "One working copy is usually enough. With none, a child makes no growth hormone and grows very slowly unless treated.", known: []}
]function strandPicker(list) {
const box = document.createElement("div");
box.className = "strands";
box.innerHTML = list.map((d, k) => `<button data-k="${k}" title="${d.name}"><b>${d.name.replace(/ \(.*/, "")}</b></button>`).join("")
+ `<p></p><small>Drag the helix to turn it, scroll to zoom, click a base pair to move the mutation there.</small>`;
const pick = k => {
box.querySelectorAll("button").forEach((b, j) => b.classList.toggle("on", j === k));
box.querySelector("p").innerHTML = `${list[k].name}: makes ${list[k].makes}. Shown: its first 30 bases (<a href="${list[k].source}" target="_blank" rel="noopener">source: LOVD reference sequence</a>).`;
box.value = list[k];
};
box.onclick = e => {
const b = e.target.closest("button");
if (!b) return;
pick(+b.dataset.k);
box.dispatchEvent(new CustomEvent("input", {bubbles: true}));
};
pick(0);
return box;
}// What the change could mean for a person. Simplified: real effects depend on the exact change.
function humanEffect(m, strand) {
const hit = strand.known.find(d => mutate(strand.seq, d[0], d[1], d[2].repeat(d[3]), d[3]).seq === m.seq);
return hit ? hit[4]
: !m.changed ? ""
: m.name === "Silent mutation" ? `The ${strand.protein} made is identical, so no effect on the person is expected.`
: m.name === "Missense mutation" ? `One or two building blocks of ${strand.protein} differ. Many such changes are harmless, but some stop the protein working. If this one did: ${strand.loss}`
: m.name === "Nonsense mutation" || m.name === "Frameshift" ? `This copy of the gene would no longer make working ${strand.protein}. ${strand.loss}`
: `The ${strand.protein} made is slightly longer or shorter. It may still work. If it does not: ${strand.loss}`;
}function resultView(m, strand) {
const person = humanEffect(m, strand);
const box = document.createElement("div");
box.className = "verdict";
box.innerHTML = `<div class="big-number">${m.name}</div>
${m.changed ? `<span class="status ${m.shifted ? "shifted" : "kept"}">Reading frame ${m.shifted ? "shifted" : "kept"}</span>` : ""}
<p><b>In the DNA.</b> ${m.text}</p>${person ? `<p><b>In the person.</b> ${person}</p>` : ""}`;
return box;
}// Built once. helix.update() only moves and recolors what is already there.
helix = {
const N = gene.length + 6;
const RISE = 0.34, TURN = 2 * Math.PI / 10.5, R = 1;
const GROOVE = 2.45; // strand 2 leads strand 1 by this angle, which makes the two grooves unequal
const SEG = 8 * (N - 1); // backbone pieces per strand
const pair = {A: "T", T: "A", G: "C", C: "G"};
const wrap = document.createElement("div");
wrap.className = "fill dna";
wrap.innerHTML = `<div class="dna-tag" hidden></div><div class="dna-legend">${
Object.entries(baseColor).map(([b, c]) => `<span style="background:${c}">${b}</span>`).join("")}</div>`;
const tag = wrap.querySelector(".dna-tag");
const renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
const canvas = renderer.domElement;
wrap.prepend(canvas);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x141a22, 10, 30);
const camera = new THREE.PerspectiveCamera(30, 2, 0.1, 100);
scene.add(new THREE.HemisphereLight(0xffffff, 0x2c3648, 0.75));
const sun = new THREE.DirectionalLight(0xffffff, 0.55);
sun.position.set(2, 4, 6);
scene.add(sun);
const group = new THREE.Group();
group.rotation.order = "YXZ";
scene.add(group);
// Three instanced meshes: all rung halves are one draw call, all beads another, all backbone pieces a third.
const material = () => new THREE.MeshStandardMaterial({roughness: 0.5, metalness: 0.05});
const cylinder = new THREE.CylinderGeometry(1, 1, 1, 12);
const rungs = new THREE.InstancedMesh(cylinder, material(), 2 * N);
const beads = new THREE.InstancedMesh(new THREE.SphereGeometry(1, 14, 10), material(), 2 * N);
const links = new THREE.InstancedMesh(cylinder, material(), 2 * SEG);
const strandColor = [new THREE.Color("#c3ccdd"), new THREE.Color("#7383a3")];
for (let k = 0; k < 2 * SEG; k++) links.setColorAt(k, strandColor[k < SEG ? 0 : 1]);
for (let k = 0; k < 2 * N; k++) {
beads.setColorAt(k, strandColor[k % 2]);
rungs.setColorAt(k, strandColor[0]);
}
const ring = new THREE.Mesh(new THREE.TorusGeometry(1.32, 0.035, 8, 60),
new THREE.MeshBasicMaterial({color: 0xff8c42, transparent: true, depthWrite: false}));
ring.rotation.y = Math.PI / 2;
group.add(rungs, beads, links, ring);
const state = d3.range(N).map(() => ({slot: 0, on: 0, hot: 0, split: 0.5, c1: new THREE.Color(), c2: new THREE.Color()}));
let goal = null, marks = [], center = 0;
let spinning = true, turn = 0, yaw = -0.3, zoom = 1, settle = 0;
let visible = true, running = false, drag = null, last = 0;
const a = new THREE.Vector3(), b = new THREE.Vector3(), m = new THREE.Vector3(), mid = new THREE.Vector3(), dir = new THREE.Vector3();
const size = new THREE.Vector3(), quat = new THREE.Quaternion(), still = new THREE.Quaternion(), matrix = new THREE.Matrix4();
const up = new THREE.Vector3(0, 1, 0);
// Right-handed helix along x. strand is 0 or 1.
const point = (v, slot, strand) => {
const angle = slot * TURN + strand * GROOVE;
return v.set((slot - center) * RISE, R * Math.cos(angle), R * Math.sin(angle));
};
const stick = (mesh, k, p, q, radius, stretch) => {
dir.subVectors(q, p);
const length = dir.length() || 1e-6;
quat.setFromUnitVectors(up, dir.divideScalar(length));
mesh.setMatrixAt(k, matrix.compose(mid.addVectors(p, q).multiplyScalar(0.5), quat, size.set(radius, length * stretch, radius)));
};
function layout() {
const live = state.filter((d, k) => goal[k].on);
const lo = d3.min(live, d => d.slot), hi = d3.max(live, d => d.slot);
center = (lo + hi) / 2;
state.forEach((d, k) => {
point(a, d.slot, 0);
point(b, d.slot, 1);
m.lerpVectors(a, b, d.split);
const radius = 0.085 * d.on * (1 + 0.8 * d.hot);
stick(rungs, 2 * k, a, m, radius, 1);
stick(rungs, 2 * k + 1, m, b, radius, 1);
rungs.setColorAt(2 * k, d.c1);
rungs.setColorAt(2 * k + 1, d.c2);
beads.setMatrixAt(2 * k, matrix.compose(a, still, size.setScalar(0.17 * d.on)));
beads.setMatrixAt(2 * k + 1, matrix.compose(b, still, size.setScalar(0.17 * d.on)));
});
for (let strand = 0; strand < 2; strand++) {
for (let k = 0; k < SEG; k++) {
point(a, lo + (hi - lo) * k / SEG, strand);
point(b, lo + (hi - lo) * (k + 1) / SEG, strand);
stick(links, strand * SEG + k, a, b, 0.12, 1.2);
}
}
// One hoop marks the change. Over several bases it stretches into a see-through sleeve.
ring.visible = marks.length > 0;
if (ring.visible) {
ring.position.x = (d3.mean(marks) - center) * RISE;
ring.scale.z = 1 + (marks.length - 1) * RISE / 0.07;
ring.material.opacity = marks.length > 1 ? 0.4 : 0.95;
}
rungs.instanceMatrix.needsUpdate = beads.instanceMatrix.needsUpdate = links.instanceMatrix.needsUpdate = true;
rungs.instanceColor.needsUpdate = true;
}
function tick(time) {
const dt = Math.min(0.05, (time - last) / 1000 || 0);
last = time;
if (settle > 0) {
settle -= dt;
const ease = settle > 0 ? 1 - Math.exp(-dt / 0.13) : 1;
state.forEach((d, k) => {
const g = goal[k];
if (d.on < 0.02 && g.on) d.slot = g.slot;
for (const key of ["slot", "on", "hot", "split"]) d[key] += (g[key] - d[key]) * ease;
d.c1.lerp(g.c1, ease);
d.c2.lerp(g.c2, ease);
});
layout();
}
if (spinning && !drag) turn += dt * 0.45;
draw();
running = visible && (spinning || drag || settle > 0);
if (running) requestAnimationFrame(tick);
}
function draw() {
group.rotation.set(turn, yaw, 0);
if (marks.length) {
m.set((d3.mean(marks) - center) * RISE, R + 0.55, 0).applyAxisAngle(up, yaw).project(camera);
tag.style.left = `${(m.x + 1) * 50}%`;
tag.style.top = `${(1 - m.y) * 50}%`;
}
renderer.render(scene, camera);
}
// Render only while something is changing and the page is on screen.
const wake = () => {
if (!running && visible && goal) {
running = true;
last = performance.now();
requestAnimationFrame(tick);
}
};
function resize() {
const w = wrap.clientWidth, h = wrap.clientHeight;
if (!w || !h) return;
renderer.setSize(w, h, false);
camera.aspect = w / h;
const half = Math.tan(camera.fov * Math.PI / 360);
const distance = zoom * Math.max((N * RISE / 2 + 0.6) / (half * camera.aspect), 2.2 / half);
camera.position.set(0, 0.25, distance);
camera.lookAt(0, 0.15, 0);
camera.updateProjectionMatrix();
scene.fog.near = distance - 1.5;
scene.fog.far = distance + 9;
if (goal) draw();
wake();
}
const sizeWatch = new ResizeObserver(resize);
sizeWatch.observe(wrap);
const viewWatch = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting;
wake();
});
viewWatch.observe(wrap);
const ray = new THREE.Raycaster(), pointer = new THREE.Vector2();
canvas.addEventListener("pointerdown", e => {
drag = {x: e.clientX, y: e.clientY, moved: 0};
canvas.setPointerCapture(e.pointerId);
wake();
});
canvas.addEventListener("pointermove", e => {
if (!drag) return;
const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
drag = {x: e.clientX, y: e.clientY, moved: drag.moved + Math.abs(dx) + Math.abs(dy)};
yaw = Math.max(-1, Math.min(1, yaw + dx * 0.006));
turn += dy * 0.01;
});
canvas.addEventListener("pointerup", e => {
const click = drag && drag.moved < 5;
drag = null;
if (!click) return;
const box = canvas.getBoundingClientRect();
pointer.set((e.clientX - box.left) / box.width * 2 - 1, 1 - (e.clientY - box.top) / box.height * 2);
ray.setFromCamera(pointer, camera);
const hit = ray.intersectObjects([rungs, beads])[0];
if (hit && hit.instanceId >> 1 < gene.length) setInput(viewof mutPos, Math.max(4, (hit.instanceId >> 1) + 1));
});
canvas.addEventListener("wheel", e => {
e.preventDefault();
zoom = Math.max(0.5, Math.min(1.6, zoom * Math.exp(e.deltaY * 0.001)));
resize();
}, {passive: false});
invalidation.then(() => {
visible = false;
sizeWatch.disconnect();
viewWatch.disconnect();
renderer.dispose();
});
function update(mutation, spin) {
const first = !goal;
goal = mutation.items.map(d => ({
slot: d.slot, on: d.on, hot: +d.hot, split: "AG".includes(d.base) ? 0.57 : 0.43,
c1: new THREE.Color(baseColor[d.base]), c2: new THREE.Color(baseColor[pair[d.base]])
}));
marks = mutation.marks;
tag.hidden = !mutation.tag;
tag.textContent = mutation.tag;
spinning = spin;
if (first) state.forEach((d, k) => Object.assign(d, goal[k], {c1: goal[k].c1.clone(), c2: goal[k].c2.clone()}));
settle = first ? 0.01 : 1.2;
wake();
}
return {node: wrap, update};
}