@biolibs/bionet-tools 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +183 -5
  2. package/dist/digest-bench.d.ts +76 -0
  3. package/dist/digest-bench.d.ts.map +1 -0
  4. package/dist/digest-bench.js +127 -0
  5. package/dist/digest-bench.js.map +1 -0
  6. package/dist/digest-tool.d.ts.map +1 -1
  7. package/dist/digest-tool.js +2 -1
  8. package/dist/digest-tool.js.map +1 -1
  9. package/dist/digest-working.d.ts +155 -0
  10. package/dist/digest-working.d.ts.map +1 -0
  11. package/dist/digest-working.js +216 -0
  12. package/dist/digest-working.js.map +1 -0
  13. package/dist/index.d.ts +24 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +24 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/ligate-bench.d.ts +92 -0
  18. package/dist/ligate-bench.d.ts.map +1 -0
  19. package/dist/ligate-bench.js +139 -0
  20. package/dist/ligate-bench.js.map +1 -0
  21. package/dist/ligate-working.d.ts +96 -0
  22. package/dist/ligate-working.d.ts.map +1 -0
  23. package/dist/ligate-working.js +145 -0
  24. package/dist/ligate-working.js.map +1 -0
  25. package/dist/ligate.d.ts +152 -0
  26. package/dist/ligate.d.ts.map +1 -0
  27. package/dist/ligate.js +161 -0
  28. package/dist/ligate.js.map +1 -0
  29. package/dist/map.d.ts +69 -0
  30. package/dist/map.d.ts.map +1 -0
  31. package/dist/map.js +80 -0
  32. package/dist/map.js.map +1 -0
  33. package/dist/pcr-bench.d.ts +103 -0
  34. package/dist/pcr-bench.d.ts.map +1 -0
  35. package/dist/pcr-bench.js +211 -0
  36. package/dist/pcr-bench.js.map +1 -0
  37. package/dist/pcr-scene.d.ts +249 -0
  38. package/dist/pcr-scene.d.ts.map +1 -0
  39. package/dist/pcr-scene.js +287 -0
  40. package/dist/pcr-scene.js.map +1 -0
  41. package/dist/pcr-tool.d.ts.map +1 -1
  42. package/dist/pcr-tool.js +2 -1
  43. package/dist/pcr-tool.js.map +1 -1
  44. package/dist/pcr-working.d.ts +126 -0
  45. package/dist/pcr-working.d.ts.map +1 -0
  46. package/dist/pcr-working.js +175 -0
  47. package/dist/pcr-working.js.map +1 -0
  48. package/dist/run.d.ts +103 -5
  49. package/dist/run.d.ts.map +1 -1
  50. package/dist/run.js +132 -12
  51. package/dist/run.js.map +1 -1
  52. package/dist/sequence-file.d.ts +108 -0
  53. package/dist/sequence-file.d.ts.map +1 -0
  54. package/dist/sequence-file.js +145 -0
  55. package/dist/sequence-file.js.map +1 -0
  56. package/dist/sequences-tool.d.ts +13 -0
  57. package/dist/sequences-tool.d.ts.map +1 -0
  58. package/dist/sequences-tool.js +61 -0
  59. package/dist/sequences-tool.js.map +1 -0
  60. package/dist/tools.d.ts +7 -3
  61. package/dist/tools.d.ts.map +1 -1
  62. package/dist/tools.js +11 -5
  63. package/dist/tools.js.map +1 -1
  64. package/dist/working.d.ts +58 -0
  65. package/dist/working.d.ts.map +1 -0
  66. package/dist/working.js +55 -0
  67. package/dist/working.js.map +1 -0
  68. package/package.json +6 -2
  69. package/src/digest-bench.tsx +307 -0
  70. package/src/digest-tool.tsx +2 -1
  71. package/src/digest-working.ts +288 -0
  72. package/src/index.ts +24 -0
  73. package/src/ligate-bench.tsx +293 -0
  74. package/src/ligate-working.ts +182 -0
  75. package/src/ligate.ts +243 -0
  76. package/src/map.tsx +170 -0
  77. package/src/pcr-bench.tsx +403 -0
  78. package/src/pcr-scene.ts +410 -0
  79. package/src/pcr-tool.tsx +2 -1
  80. package/src/pcr-working.ts +228 -0
  81. package/src/run.ts +186 -14
  82. package/src/sequence-file.ts +172 -0
  83. package/src/sequences-tool.tsx +109 -0
  84. package/src/tools.tsx +15 -9
  85. package/src/working.tsx +96 -0
  86. package/tools.css +82 -0
@@ -0,0 +1,307 @@
1
+ "use client";
2
+
3
+ /**
4
+ * A digest and its gel at the gel station: what is shown beside the instrument, and what the scene
5
+ * is told to draw.
6
+ *
7
+ * A gel box and its power supply show a voltage, a current and a time. They show nothing of the
8
+ * DNA: where it was cut, how many pieces there are, how far each has run. That is pictured, and
9
+ * then read off the gel against a ladder. So the views run the same way as a PCR's: the rig, the
10
+ * gel in it, what the power supply says, then what is in the tube, and the gel once it has run.
11
+ */
12
+ import { useMemo, useState, type ReactNode } from "react";
13
+ import { GELS, LADDERS, gelById } from "@biolibs/gel";
14
+ import { useAct, useLab } from "@biolibs/bionet-react";
15
+ import { Glossed } from "@biolibs/glossary-react";
16
+ import { cutters, enzymeNamed } from "./digest.js";
17
+ import { Gel } from "./digest-tool.js";
18
+ import { cutSites, digestChecks, digestPieces, migrationWorking, piecesWorking, siteWorking, type PieceEnd } from "./digest-working.js";
19
+ import { SequenceMap } from "./map.js";
20
+ import { digestRun, digestTubes } from "./run.js";
21
+ import { moleculeOf, type DrawnMolecule } from "./sequence-file.js";
22
+ import { CutBases, ShowWorking } from "./working.js";
23
+
24
+ /** The views of the gel station, by the same names every instrument's stage uses. */
25
+ export type DigestView = "machine" | "block" | "screen" | "tube" | "result";
26
+
27
+ /** What the scene is told to show. It is shaped to be spread onto `InstrumentStage`. */
28
+ export interface DigestStage {
29
+ model: "gel-station";
30
+ name: string;
31
+ view: DigestView;
32
+ onView: (view: DigestView) => void;
33
+ /** What the power supply's display says. */
34
+ screen: { text: string; lit?: boolean }[];
35
+ /** The lane the digest is loaded in. */
36
+ well?: { row: number; column: number };
37
+ /** The molecule being cut, with the cuts marked, for the view into the tube. */
38
+ molecule?: DrawnMolecule & { marks: { at: number; label: string }[] };
39
+ /** The gel once run: the ladder and the digest, for the last view. */
40
+ gel?: { lanes: { name: string; tone: "dim" | "held"; bands: { position: number; intensity: number; label: string }[] }[]; ran: number };
41
+ }
42
+
43
+ const count = (value: number): string => value.toLocaleString("en-US");
44
+ const whole = (text: string): number | undefined => (/^\d+$/.test(text.trim()) ? Number(text) : undefined);
45
+ const endWords = (end: PieceEnd): ReactNode => (end.enzyme === null ? <span className="dim">the molecule's end</span>
46
+ : <>{end.enzyme} <span className="dim">{end.overhang === "blunt" ? "blunt" : `${end.overhang} `}</span>{end.overhang !== "blunt" && <code>{end.bases}</code>}</>);
47
+
48
+ /**
49
+ * A digest and its gel, at the gel station.
50
+ *
51
+ * @param options - `instrument` is the gel station it is run at, if the lab has one; `onDone` adds a way to leave.
52
+ * @returns `stage`, to spread onto `InstrumentStage` from `@biolibs/bionet-scene`, and `panel`, to put inside it.
53
+ *
54
+ * @example
55
+ * ```tsx
56
+ * import { useDigestBench } from "@biolibs/bionet-tools";
57
+ *
58
+ * // `InstrumentStage` is the scene package's: it is handed what this gives and draws it.
59
+ * const bench = useDigestBench({ instrument });
60
+ * <InstrumentStage {...bench.stage}>{bench.panel}</InstrumentStage>
61
+ * ```
62
+ */
63
+ export function useDigestBench({ instrument = null, onDone }: { instrument?: { id: string; name: string } | null; onDone?: () => void } = {}): { stage: DigestStage; panel: ReactNode } {
64
+ const lab = useLab()?.lab;
65
+ const act = useAct();
66
+ const [view, setView] = useState<DigestView>("machine");
67
+ const [tube, setTube] = useState("");
68
+ const [chosen, setChosen] = useState<string[]>([]);
69
+ const [other, setOther] = useState("");
70
+ const [unknown, setUnknown] = useState<string | null>(null);
71
+ const [used, setUsed] = useState("1");
72
+ const [gel, setGel] = useState("1.0");
73
+ const [ladder, setLadder] = useState("1kb");
74
+ const [volts, setVolts] = useState("100");
75
+ const [minutes, setMinutes] = useState("45");
76
+ const [ran, setRan] = useState(100);
77
+ const [note, setNote] = useState("");
78
+ const [busy, setBusy] = useState(false);
79
+ const [said, setSaid] = useState<string | null>(null);
80
+ const [keep, setKeep] = useState<number[]>([]);
81
+ const [amount, setAmount] = useState("20");
82
+
83
+ const tubes = useMemo(() => (lab === null || lab === undefined ? [] : digestTubes(lab)), [lab]);
84
+ const part = tubes.find((one) => one.item === tube)?.part;
85
+ const offered = useMemo(() => (part === undefined ? [] : cutters(part)), [part]);
86
+ const run = useMemo(() => (lab === null || lab === undefined ? null : digestRun(lab, {
87
+ tube, enzymes: chosen, gel, ladder, instrument: instrument?.id ?? null, note, ...(whole(used) === undefined ? {} : { used: whole(used)! }),
88
+ ...(whole(volts) === undefined ? {} : { volts: whole(volts)! }), ...(whole(minutes) === undefined ? {} : { minutes: whole(minutes)! }),
89
+ keep: keep.map((from) => ({ from, ...(whole(amount) === undefined ? {} : { amount: whole(amount)! }) })),
90
+ })), [lab, tube, chosen, gel, ladder, instrument, note, used, volts, minutes, keep, amount]);
91
+ const plan = run?.plan ?? null;
92
+ const good = plan !== null && plan.problem === null ? plan : null;
93
+ const sites = useMemo(() => (part === undefined || plan === null ? [] : plan.cutters.flatMap((one) => cutSites(part, one)).sort((a, b) => a.at - b.at)), [part, plan]);
94
+ const pieces = useMemo(() => (part === undefined ? [] : digestPieces(part, sites)), [part, sites]);
95
+ // A piece is known by where it starts, so a change of enzymes lets go of pieces that are no longer there.
96
+ const kept = pieces.filter((piece) => keep.includes(piece.from));
97
+ const gelType = useMemo(() => { try { return gelById(gel); } catch { return gelById("1.0"); } }, [gel]);
98
+ const checks = part === undefined || good === null ? [] : digestChecks(part, good, gelType);
99
+
100
+ const stage: DigestStage = {
101
+ model: "gel-station", name: instrument?.name ?? "Gel station", view, onView: setView,
102
+ screen: [{ text: `${whole(volts) ?? "—"} V`, lit: true }, { text: `${whole(minutes) ?? "—"}:00 min` }],
103
+ ...(part === undefined ? {} : { well: { row: 0, column: 1 } }),
104
+ ...(part === undefined || view !== "tube" ? {} : { molecule: (() => {
105
+ const drawn = moleculeOf(part);
106
+ // A piece being kept is drawn on the molecule, so what is taken can be seen against what is left.
107
+ const taken = kept.flatMap((piece) => (piece.to > piece.from ? [[piece.from, piece.to]] : [[piece.from, part.length], [0, piece.to]]).filter(([start, end]) => end! > start!)
108
+ .map(([start, end]) => ({ start: start!, end: end!, strand: 0 as const, tone: "found" as const, label: `kept · ${count(piece.length)} bp` })));
109
+ return { ...drawn, features: [...taken, ...drawn.features], marks: sites.map((one) => ({ at: one.at, label: one.enzyme })) };
110
+ })() }),
111
+ ...(good === null ? {} : { gel: { ran: ran / 100, lanes: [
112
+ { name: "ladder", tone: "dim" as const, bands: good.ladder.map((band) => ({ position: band.position, intensity: 0.6, label: count(band.size) })) },
113
+ { name: part?.name ?? "digest", tone: "held" as const, bands: good.bands.map((band) => ({ position: band.position, intensity: band.intensity,
114
+ label: `${band.sizes.map(count).join(" + ")}${kept.some((piece) => band.sizes.includes(piece.length)) ? " · kept" : ""}` })) },
115
+ ] } }),
116
+ };
117
+
118
+ const toggle = (name: string): void => { setChosen(chosen.includes(name) ? chosen.filter((one) => one !== name) : [...chosen, name]); setSaid(null); setKeep([]); };
119
+ const record = async (what: Record<string, unknown> | null, done: string): Promise<void> => {
120
+ if (what === null) return;
121
+ setBusy(true);
122
+ const answer = await act("recordRun", what);
123
+ setBusy(false);
124
+ if (answer.ok) { setSaid(done); setNote(""); setKeep([]); }
125
+ };
126
+ const here = lab === null || lab === undefined ? [] : lab.runs.filter((one) => one.kind === "digest" && (instrument === null || one.instrument === instrument.id)).slice(-5).reverse();
127
+ const partName = (item: string | undefined): string => lab?.parts.find((one) => one.checksum === lab.items.find((each) => each.item === item)?.part)?.name ?? "a tube";
128
+ const checked = checks.length === 0 ? <p className="small good">Nothing about this digest looks wrong for this gel.</p>
129
+ : <ul className="checks">{checks.map((check) => <li key={check.says} className={check.weight}>{check.says} <code className="because">{check.because}</code></li>)}</ul>;
130
+
131
+ const panel = lab === null || lab === undefined ? null : (
132
+ <div className="bionet benchpanel">
133
+ <section className="card">
134
+ <div className="toolhead">
135
+ <h2>Digest and gel</h2>
136
+ {onDone !== undefined && <button type="button" className="quiet" onClick={onDone}>Back to the lab</button>}
137
+ </div>
138
+ {tubes.length === 0 ? <p className="empty">There are no tubes to digest. Add a part and a tube of it on the Freezer tab.</p> : (
139
+ <fieldset disabled={busy} className="stack">
140
+ <label>Tube
141
+ <select value={tube} onChange={(event) => { setTube(event.target.value); setChosen([]); setSaid(null); setKeep([]); }} aria-label="Tube">
142
+ <option value="">Choose a tube…</option>
143
+ {tubes.map((one) => <option key={one.item} value={one.item}>{one.label}</option>)}
144
+ </select>
145
+ </label>
146
+ {part !== undefined && (
147
+ <>
148
+ <p className="label">Enzymes{offered.length === 0 ? " · none of the usual ones cut this" : ""}</p>
149
+ <div className="enzymes">
150
+ {offered.map((one) => (
151
+ <label key={one.name} className="check" title={`${one.site} · cuts ${one.positions.length === 1 ? "once" : `${one.positions.length} times`}`}>
152
+ <input type="checkbox" checked={chosen.includes(one.name)} onChange={() => toggle(one.name)} /> {one.name} <span className="dim small">×{one.positions.length}</span>
153
+ </label>
154
+ ))}
155
+ {chosen.filter((name) => !offered.some((one) => one.name === name)).map((name) => (
156
+ <label key={name} className="check"><input type="checkbox" checked onChange={() => toggle(name)} /> {name}</label>
157
+ ))}
158
+ </div>
159
+ <form className="row tight" onSubmit={(event) => {
160
+ event.preventDefault();
161
+ const name = enzymeNamed(other);
162
+ setUnknown(name === null && other.trim() !== "" ? other.trim() : null);
163
+ if (name !== null && !chosen.includes(name)) setChosen([...chosen, name]);
164
+ if (name !== null) setOther("");
165
+ }}>
166
+ <input value={other} onChange={(event) => setOther(event.target.value)} placeholder="Another enzyme, by name" aria-label="Another enzyme" maxLength={40} spellCheck={false} />
167
+ <button type="submit" className="quiet">Add</button>
168
+ </form>
169
+ {unknown !== null && <p className="trouble small" role="status">There is no enzyme called {unknown} here.</p>}
170
+ </>
171
+ )}
172
+ </fieldset>
173
+ )}
174
+ {plan !== null && chosen.length > 0 && plan.problem !== null && <p className="trouble" role="status">{plan.problem}</p>}
175
+ </section>
176
+
177
+ {view === "machine" && (
178
+ <section className="card">
179
+ <h2>At the gel box</h2>
180
+ <p className="small"><Glossed text="A restriction enzyme cuts DNA wherever its site occurs, and gel electrophoresis sorts the pieces by size. A check digest cuts a plasmid with enzymes whose sites are known, to see that the pieces come out the lengths they should." /></p>
181
+ <p className="dim small">A gel box and its power supply show volts, current and time. They show nothing of the DNA. The first three views are what is there to see; the last two are what you picture, and then read off the gel.</p>
182
+ </section>
183
+ )}
184
+
185
+ {view === "block" && (
186
+ <section className="card">
187
+ <h2>The gel</h2>
188
+ <p className="voice">The machine</p>
189
+ <fieldset disabled={busy} className="programme">
190
+ <label>Gel<select value={gel} onChange={(event) => setGel(event.target.value)}>{GELS.map((one) => <option key={one.id} value={one.id}>{one.percent}% agarose</option>)}</select></label>
191
+ <label>Ladder<select value={ladder} onChange={(event) => setLadder(event.target.value)}>{LADDERS.map((one) => <option key={one.id} value={one.id}>{one.name}</option>)}</select></label>
192
+ </fieldset>
193
+ <p className="small"><Glossed text="A slab of agarose in buffer, with a row of wells at one end. The wells go at the negative end, since DNA runs towards the positive one." /></p>
194
+ <p className="voice">This run</p>
195
+ <p className="small">{part === undefined ? "Nothing is loaded yet. Choose a tube above." : `The ladder is in the first lane and ${part.name} in the second.`} This gel separates pieces from {count(gelType.largest)} down to {count(gelType.smallest)} bp.</p>
196
+ {good !== null && <><p className="voice">Checks</p>{checked}</>}
197
+ </section>
198
+ )}
199
+
200
+ {view === "screen" && (
201
+ <section className="card">
202
+ <h2>The power supply</h2>
203
+ <p className="voice">The machine</p>
204
+ <fieldset disabled={busy} className="programme">
205
+ <label>Run at<input type="number" min={10} max={300} step={5} value={volts} onChange={(event) => setVolts(event.target.value)} /> V</label>
206
+ <label>for<input type="number" min={1} max={600} step={5} value={minutes} onChange={(event) => setMinutes(event.target.value)} /> min</label>
207
+ </fieldset>
208
+ <p className="voice">What is going on</p>
209
+ <p className="small">DNA carries a negative charge all along its backbone, so in a field every piece is pulled towards the positive electrode. The agarose holds long pieces back more than short ones, and that is what sorts them.</p>
210
+ <p className="dim small">Nothing here works out how far a given voltage and time move the bands: that depends on the box, the buffer and the gel. What is set is kept with the run, and the gel is drawn as run until the smallest pieces it separates near the far end.</p>
211
+ </section>
212
+ )}
213
+
214
+ {view === "tube" && (
215
+ <section className="card">
216
+ <h2>In the tube</h2>
217
+ {part === undefined || good === null ? <p className="dim small">{part === undefined ? "Choose a tube and its enzymes to see where it is cut." : "Choose enzymes that cut this to see the pieces."}</p> : (
218
+ <>
219
+ <SequenceMap name={part.name} length={part.length} circular={part.circular} features={part.features} marks={sites.map((one) => ({ at: one.at, label: one.enzyme }))} />
220
+ <p className="voice">This run</p>
221
+ <p><strong>{pieces.length} {pieces.length === 1 ? "piece" : "pieces"}</strong> <span className="dim">from {sites.length} {sites.length === 1 ? "cut" : "cuts"}</span></p>
222
+ <table className="pieces">
223
+ <thead><tr><th>Keep</th><th>Length</th><th>From</th><th>One end</th><th>Other end</th><th>Carries</th></tr></thead>
224
+ <tbody>
225
+ {pieces.map((piece) => (
226
+ <tr key={`${piece.from} ${piece.to}`}>
227
+ <td><input type="checkbox" checked={keep.includes(piece.from)} aria-label={`Keep the ${count(piece.length)} bp piece`}
228
+ onChange={() => setKeep(keep.includes(piece.from) ? keep.filter((one) => one !== piece.from) : [...keep, piece.from])} /></td>
229
+ <td><strong>{count(piece.length)}</strong></td>
230
+ <td><code>{count(piece.from + 1)}..{count(piece.to)}</code></td>
231
+ <td>{endWords(piece.left)}</td>
232
+ <td>{endWords(piece.right)}</td>
233
+ <td className="dim">{piece.features.map((one) => one.label).join(", ") || "—"}</td>
234
+ </tr>
235
+ ))}
236
+ </tbody>
237
+ </table>
238
+ <p className="small"><Glossed text="An end with unpaired bases is a sticky end, and will only join to an end whose unpaired bases pair with it. A blunt end has none." /></p>
239
+ <p className="dim small">Tick a piece to keep it. Cutting its band out of the gel and cleaning it up gives a tube of that piece, with these ends, once the gel has matched.</p>
240
+ <p className="voice">The working</p>
241
+ {sites.map((site) => <ShowWorking key={`${site.enzyme} ${site.at}`} working={siteWorking(site)}><CutBases site={site} /></ShowWorking>)}
242
+ <ShowWorking working={piecesWorking(part, sites, good)} />
243
+ </>
244
+ )}
245
+ </section>
246
+ )}
247
+
248
+ {view === "result" && (
249
+ <section className="card">
250
+ <h2>The gel, run</h2>
251
+ {part === undefined || good === null ? <p className="dim small">Choose a tube and enzymes that cut it to see the gel it should give.</p> : (
252
+ <>
253
+ <p className="voice">This run</p>
254
+ <Gel ladder={good.ladder} bands={good.bands} name={part.name} />
255
+ <label className="small">How far it has run
256
+ <input type="range" min={0} max={100} step={1} value={ran} onChange={(event) => setRan(Number(event.target.value))} aria-label="How far the gel has run" />
257
+ </label>
258
+ <p className="dim small">Drag it back to see the pieces start together in the well and draw apart as they run. The scene follows.</p>
259
+ {good.bands.some((band) => band.unresolved) && <p className="dim small">* outside what this gel separates.</p>}
260
+ <p className="voice">Checks</p>
261
+ {checked}
262
+ <p className="voice">The working</p>
263
+ {[...new Set(good.fragments)].map((size) => <ShowWorking key={size} working={migrationWorking(size, gelType)} />)}
264
+ <fieldset disabled={busy} className="stack">
265
+ <label>Used, from the tube<input type="number" min={0} step={1} value={used} onChange={(event) => setUsed(event.target.value)} aria-label="Amount used" /></label>
266
+ <label>Note<input value={note} onChange={(event) => setNote(event.target.value)} placeholder="Anything worth remembering about this gel" maxLength={2000} /></label>
267
+ {kept.length > 0 && (
268
+ <>
269
+ <p className="small">Keeping {kept.map((piece) => `${count(piece.length)} bp`).join(" and ")}: {kept.length === 1 ? "a new tube" : `${kept.length} new tubes`}, each a part with the ends the enzymes left.</p>
270
+ <label>Amount of each, in µL<input type="number" min={0} step={1} value={amount} onChange={(event) => setAmount(event.target.value)} aria-label="Amount of each kept piece" /></label>
271
+ </>
272
+ )}
273
+ <div className="row">
274
+ <button type="button" onClick={() => void record(run?.matched ?? null, kept.length === 0 ? "Recorded: the gel showed what was expected." : `Recorded: the gel matched, and ${kept.length === 1 ? "the piece is" : `${kept.length} pieces are`} in the freezer.`)}>
275
+ {kept.length === 0 ? "The gel matched" : `The gel matched · keep ${kept.length === 1 ? "the piece" : `${kept.length} pieces`}`}
276
+ </button>
277
+ <button type="button" className="quiet" onClick={() => void record(run?.differed ?? null, "Recorded: the gel did not show what was expected.")}>The gel did not match</button>
278
+ </div>
279
+ </fieldset>
280
+ {said !== null && <p className="small" role="status">{said}</p>}
281
+ </>
282
+ )}
283
+ </section>
284
+ )}
285
+
286
+ {here.length > 0 && view === "result" && (
287
+ <section className="card">
288
+ <h2>Recent digests{instrument === null ? "" : " here"}</h2>
289
+ <table>
290
+ <thead><tr><th>Tube</th><th>Enzymes</th><th>Expected</th><th>Gel</th></tr></thead>
291
+ <tbody>
292
+ {here.map((one) => (
293
+ <tr key={one.run}>
294
+ <td>{partName(one.inputs[0]?.item)}</td>
295
+ <td>{String(one.settings["enzymes"] ?? "").replace(/\+/g, " + ")}</td>
296
+ <td className="dim">{String(one.settings["expected"] ?? "")}</td>
297
+ <td>{one.outcome === "worked" ? "matched" : <span className="badge">did not match</span>}</td>
298
+ </tr>
299
+ ))}
300
+ </tbody>
301
+ </table>
302
+ </section>
303
+ )}
304
+ </div>
305
+ );
306
+ return { stage, panel };
307
+ }
@@ -10,6 +10,7 @@ import { useMemo, useState } from "react";
10
10
  import type { Band } from "@biolibs/gel";
11
11
  import { GELS, LADDERS } from "@biolibs/gel";
12
12
  import { useAct, useLab } from "@biolibs/bionet-react";
13
+ import { Glossed } from "@biolibs/glossary-react";
13
14
  import { cutters, enzymeNamed } from "./digest.js";
14
15
  import { digestRun, digestTubes } from "./run.js";
15
16
 
@@ -94,7 +95,7 @@ export function DigestTool({ instrument = null, onDone }: { instrument?: { id: s
94
95
  <div className="toolhead">
95
96
  <div>
96
97
  <h2>Digest and gel{instrument === null ? "" : ` · ${instrument.name}`}</h2>
97
- <p className="dim small">Choose a tube and the enzymes to cut it with. The pieces are worked out from its sequence, and drawn as the gel they should give.</p>
98
+ <p className="dim small"><Glossed text="A restriction enzyme cuts DNA wherever its site occurs, and gel electrophoresis sorts the pieces by size. Choose a tube and the enzymes to cut it with. The pieces are worked out from its sequence, and drawn as the gel they should give." /></p>
98
99
  </div>
99
100
  {onDone !== undefined && <button type="button" className="quiet" onClick={onDone}>Back to the lab</button>}
100
101
  </div>
@@ -0,0 +1,288 @@
1
+ /**
2
+ * A digest looked at closely: each cut in its real bases, each piece with its ends, and the working.
3
+ *
4
+ * `digest.ts` says where enzymes cut and how long the pieces are. This says what somebody at the
5
+ * bench pictures and what somebody checking would ask: which bases the enzyme recognised, where it
6
+ * cut each strand and what end that leaves, which cut made each end of each piece, and what is
7
+ * marked on each piece. Like the PCR's working, each figure says whether it is exact or an estimate.
8
+ */
9
+ import type { PartFeature } from "@biolibs/bionet";
10
+ import { bandPosition, type GelType } from "@biolibs/gel";
11
+ import { enzymes } from "@biolibs/restriction";
12
+ import type { Cutter, DigestPlan } from "./digest.js";
13
+ import type { Working } from "./pcr-working.js";
14
+ import { carryFeatures } from "./sequence-file.js";
15
+
16
+ const count = (value: number): string => value.toLocaleString("en-US");
17
+ const clean = (bases: string): string => bases.replace(/\s+/g, "").toUpperCase();
18
+ const PAIR: Readonly<Record<string, string>> = { A: "T", T: "A", G: "C", C: "G", N: "N", R: "Y", Y: "R", K: "M", M: "K", S: "S", W: "W", B: "V", V: "B", D: "H", H: "D" };
19
+ const IUPAC: Readonly<Record<string, string>> = { A: "A", C: "C", G: "G", T: "T", N: "[ACGT]", R: "[AG]", Y: "[CT]", K: "[GT]", M: "[AC]", S: "[CG]", W: "[AT]", B: "[CGT]", D: "[AGT]", H: "[ACT]", V: "[ACG]" };
20
+ const across = (bases: string): string => [...bases].map((base) => PAIR[base] ?? "N").join("");
21
+ const flipped = (bases: string): string => [...bases].reverse().map((base) => PAIR[base] ?? "N").join("");
22
+
23
+ /** One place an enzyme cuts, in the molecule's own bases. */
24
+ export interface CutSite {
25
+ /** The enzyme. */
26
+ enzyme: string;
27
+ /** The sequence it recognises, as it is written for the enzyme. */
28
+ recognises: string;
29
+ /** Where the top strand is cut: the number of bases before the cut. */
30
+ at: number;
31
+ /** Where the bottom strand is cut, counted along the top strand in the same way. */
32
+ bottom: number;
33
+ /** How far the bottom strand's cut is to the right of the top strand's: positive for a 5′ overhang, negative for a 3′ one, 0 for blunt. */
34
+ stagger: number;
35
+ /** Where the recognised bases are, from the first to one past the last. On a circle the end may be past the origin. */
36
+ site: { start: number; end: number };
37
+ /** Whether the site reads along the bottom strand. Only an enzyme whose site is not its own mirror can. */
38
+ backwards: boolean;
39
+ /** What kind of end the cut leaves. */
40
+ overhang: "5′" | "3′" | "blunt";
41
+ /** The single-stranded bases of that end, as the top strand has them. Empty for a blunt cut. */
42
+ bases: string;
43
+ /**
44
+ * The stretch around the cut, for drawing: both strands, the bottom written under the top, and
45
+ * within them where the recognised bases are and how many bases precede each strand's cut.
46
+ */
47
+ around: { from: number; top: string; bottom: string; site: [number, number]; cutTop: number; cutBottom: number };
48
+ }
49
+
50
+ /**
51
+ * Every place one enzyme cuts, with the bases it recognised there.
52
+ *
53
+ * The cut positions come from the restriction engine. This finds the site behind each one by
54
+ * looking for the enzyme's sequence itself, on both strands, and keeps only sites whose cut the
55
+ * engine also found, so each position is explained and none is invented.
56
+ *
57
+ * @param part - The molecule.
58
+ * @param cutter - The enzyme and where it cuts, from `cutsOf`.
59
+ * @returns The sites, in order along the molecule. A cut whose site cannot be found is left out.
60
+ */
61
+ export function cutSites(part: { sequence: string; circular: boolean }, cutter: Cutter): CutSite[] {
62
+ const enzyme = Object.hasOwn(enzymes, cutter.name) ? enzymes[cutter.name] : undefined;
63
+ const bases = clean(part.sequence);
64
+ const length = bases.length;
65
+ if (enzyme === undefined || enzyme.fst5 === null || enzyme.ovhg === null || length === 0) return [];
66
+ const [size, fst5, ovhg] = [enzyme.size, enzyme.fst5, enzyme.ovhg];
67
+ const site = clean(String(enzyme.site));
68
+ // A circle is searched once round and a little further, so a site across the origin is found.
69
+ const searched = part.circular ? bases + bases.slice(0, size - 1) : bases;
70
+ const wrap = (value: number): number => ((value % length) + length) % length;
71
+ const base = (place: number): string => (part.circular ? bases[wrap(place)]! : bases[place] ?? "");
72
+ const found: CutSite[] = [];
73
+ const look = (pattern: string, backwards: boolean): void => {
74
+ const matcher = new RegExp(`(?=(${[...pattern].map((one) => IUPAC[one] ?? one).join("")}))`, "g");
75
+ for (const match of searched.matchAll(matcher)) {
76
+ const start = match.index;
77
+ // Forwards, the top strand is cut `fst5` into the site. Backwards the enzyme sits the other way
78
+ // up, so that is where it cuts the bottom strand, and the top is cut across from its other cut.
79
+ const [top, under] = backwards ? [start + size - fst5 + ovhg, start + size - fst5] : [start + fst5, start + fst5 - ovhg];
80
+ const at = part.circular ? wrap(top) : top;
81
+ if (!cutter.positions.includes(at) || found.some((one) => one.at === at)) continue;
82
+ const [low, high] = [Math.min(top, under), Math.max(top, under)];
83
+ const from = Math.min(start, low) - 4;
84
+ const to = Math.max(start + size, high) + 4;
85
+ const shown = Array.from({ length: to - from }, (_, index) => base(from + index)).join("");
86
+ found.push({
87
+ enzyme: cutter.name, recognises: site, at, bottom: part.circular ? wrap(under) : under, stagger: under - top, site: { start, end: start + size }, backwards,
88
+ overhang: ovhg === 0 ? "blunt" : top < under ? "5′" : "3′",
89
+ bases: Array.from({ length: high - low }, (_, index) => base(low + index)).join(""),
90
+ around: { from, top: shown, bottom: across(shown), site: [start - from, start + size - from], cutTop: top - from, cutBottom: under - from },
91
+ });
92
+ }
93
+ };
94
+ look(site, false);
95
+ if (flipped(site) !== site) look(flipped(site), true);
96
+ return found.sort((a, b) => a.at - b.at);
97
+ }
98
+
99
+ /** One end of a piece: what made it. */
100
+ export interface PieceEnd {
101
+ /** The enzyme that cut here, or `null` if this is the molecule's own end. */
102
+ enzyme: string | null;
103
+ /** What kind of end it is. */
104
+ overhang: "5′" | "3′" | "blunt" | "end";
105
+ /** Its single-stranded bases, as the top strand has them. */
106
+ bases: string;
107
+ }
108
+
109
+ /** One piece of a digest. */
110
+ export interface DigestPiece {
111
+ /** Where it starts and stops on the molecule. On a circle a piece may run through the origin, so `to` can be the smaller. */
112
+ from: number;
113
+ to: number;
114
+ /** How long it is. */
115
+ length: number;
116
+ /** Its two ends. */
117
+ left: PieceEnd;
118
+ right: PieceEnd;
119
+ /** What is marked on it, placed on the piece's own sequence. Something cut through is kept as far as it is on the piece. */
120
+ features: PartFeature[];
121
+ /** Every base either of its strands has, read along the top strand: the piece as a molecule of its own. */
122
+ sequence: string;
123
+ /** How many of those bases at each end are on one strand only: positive for a 5′ overhang, negative for a 3′ one. */
124
+ ends: { left: number; right: number };
125
+ }
126
+
127
+ /**
128
+ * The pieces a digest gives, each with what made its ends and what it carries.
129
+ *
130
+ * @param part - The molecule, with what is marked on it.
131
+ * @param sites - Every cut, from `cutSites` for each enzyme.
132
+ * @returns The pieces, longest first. Nothing if there are no cuts.
133
+ */
134
+ export function digestPieces(part: { sequence: string; circular: boolean; features?: readonly PartFeature[] }, sites: readonly CutSite[]): DigestPiece[] {
135
+ const length = clean(part.sequence).length;
136
+ const cuts = [...new Map(sites.map((one) => [one.at, one])).values()].sort((a, b) => a.at - b.at);
137
+ if (cuts.length === 0) return [];
138
+ const end = (site: CutSite | undefined): PieceEnd => (site === undefined ? { enzyme: null, overhang: "end", bases: "" } : { enzyme: site.enzyme, overhang: site.overhang, bases: site.bases });
139
+ const features = part.features ?? [];
140
+ const bases = clean(part.sequence);
141
+ const piece = (from: number, to: number, left: CutSite | undefined, right: CutSite | undefined): DigestPiece => {
142
+ const span = to > from ? to - from : length - from + to;
143
+ // A strand cut further out than the other gives the piece bases beyond the top strand's cut.
144
+ const [before, after] = [Math.max(0, -(left?.stagger ?? 0)), Math.max(0, right?.stagger ?? 0)];
145
+ const read = (start: number, many: number): string => Array.from({ length: many }, (_, index) => bases[(((start + index) % length) + length) % length]!).join("");
146
+ return {
147
+ from, to, left: end(left), right: end(right), length: span,
148
+ sequence: read(from - before, before + span + after), ends: { left: left?.stagger ?? 0, right: right?.stagger ?? 0 },
149
+ // Through the origin, what is carried is what lies before it and then what lies after.
150
+ features: to > from ? carryFeatures(features, from, to, before) : [...carryFeatures(features, from, length, before), ...carryFeatures(features, 0, to, length - from + before)],
151
+ };
152
+ };
153
+ const pieces: DigestPiece[] = [];
154
+ if (part.circular) {
155
+ cuts.forEach((cut, index) => { const next = cuts[(index + 1) % cuts.length]!; pieces.push(piece(cut.at, next.at, cut, next)); });
156
+ // One cut opens a circle into a single piece: it runs from the cut right round to the cut again.
157
+ } else {
158
+ const edges = [0, ...cuts.map((one) => one.at), length];
159
+ for (let index = 0; index + 1 < edges.length; index++) {
160
+ if (edges[index + 1]! > edges[index]!) pieces.push(piece(edges[index]!, edges[index + 1]!, cuts[index - 1], cuts[index]));
161
+ }
162
+ }
163
+ return pieces.sort((a, b) => b.length - a.length);
164
+ }
165
+
166
+ /**
167
+ * One cut, said as steps that can be checked against the bases.
168
+ *
169
+ * @param site - The cut, from `cutSites`.
170
+ * @returns The working.
171
+ */
172
+ export function siteWorking(site: CutSite): Working {
173
+ const wide = Math.abs(site.at - site.bottom);
174
+ return {
175
+ of: `${site.enzyme} at base ${count(site.at)}`, kind: "exact",
176
+ comes: site.overhang === "blunt" ? "a blunt end" : `a ${wide}-base ${site.overhang} overhang, ${site.bases}`,
177
+ steps: [
178
+ `${site.enzyme} recognises ${site.recognises}. Those bases are at ${count(site.site.start + 1)} to ${count(site.site.end)}${site.backwards ? ", reading along the bottom strand" : ""}.`,
179
+ `It cuts the top strand after base ${count(site.at)} and the bottom strand after base ${count(site.bottom)}.`,
180
+ site.overhang === "blunt" ? "Both strands are cut at the same place, so the ends are blunt."
181
+ : `The cuts are ${wide} bases apart, so each piece is left with ${wide} unpaired bases at its ${site.overhang} end: ${site.bases} on one piece and its partner on the other.`,
182
+ ],
183
+ };
184
+ }
185
+
186
+ /**
187
+ * How long the pieces are, as differences between the cuts, with the check that they add up.
188
+ *
189
+ * @param part - How long the molecule is, and whether it is a circle.
190
+ * @param sites - Every cut.
191
+ * @param plan - The digest as the gel engine worked it out, to compare with.
192
+ * @returns The working.
193
+ */
194
+ export function piecesWorking(part: { length: number; circular: boolean }, sites: readonly CutSite[], plan?: Pick<DigestPlan, "fragments">): Working {
195
+ const cuts = [...new Set(sites.map((one) => one.at))].sort((a, b) => a - b);
196
+ const sizes: number[] = [];
197
+ const steps: string[] = [`The cuts, in order along the molecule: after base ${cuts.map(count).join(", ")}.`];
198
+ if (part.circular) {
199
+ cuts.forEach((cut, index) => {
200
+ const next = cuts[(index + 1) % cuts.length]!;
201
+ const size = cuts.length === 1 ? part.length : next > cut ? next - cut : part.length - cut + next;
202
+ sizes.push(size);
203
+ steps.push(cuts.length === 1 ? `One cut opens the circle into one piece, the whole ${count(part.length)}.`
204
+ : next > cut ? `From ${count(cut)} to ${count(next)}: ${count(next)} − ${count(cut)} = ${count(size)}.`
205
+ : `From ${count(cut)} through the origin to ${count(next)}: ${count(part.length)} − ${count(cut)} + ${count(next)} = ${count(size)}.`);
206
+ });
207
+ } else {
208
+ const edges = [0, ...cuts, part.length];
209
+ for (let index = 0; index + 1 < edges.length; index++) {
210
+ const size = edges[index + 1]! - edges[index]!;
211
+ if (size <= 0) continue;
212
+ sizes.push(size);
213
+ steps.push(`From ${index === 0 ? "the start" : count(edges[index]!)} to ${index + 2 === edges.length ? "the end" : count(edges[index + 1]!)}: ${count(edges[index + 1]!)} − ${count(edges[index]!)} = ${count(size)}.`);
214
+ }
215
+ }
216
+ const total = sizes.reduce((sum, size) => sum + size, 0);
217
+ steps.push(`They add up to the whole molecule: ${sizes.map(count).join(" + ")} = ${count(total)}${total === part.length ? "." : `, which is not its ${count(part.length)}. Something is wrong.`}`);
218
+ if (plan !== undefined) {
219
+ const same = [...sizes].sort((a, b) => b - a).join(",") === [...plan.fragments].sort((a, b) => b - a).join(",");
220
+ steps.push(same ? "The gel engine, working the pieces out its own way, gives the same lengths." : `The gel engine gives ${plan.fragments.map(count).join(", ")}, which does not agree. Trust neither until that is understood.`);
221
+ }
222
+ return { of: "the pieces", comes: `${[...sizes].sort((a, b) => b - a).map(count).join(", ")} bp`, kind: "exact", steps };
223
+ }
224
+
225
+ /**
226
+ * Where a piece runs to on a gel, with the rule behind it.
227
+ *
228
+ * @param size - How long the piece is.
229
+ * @param gel - The gel.
230
+ * @returns The working. It is an estimate: the rule is a straight line that real gels only roughly follow.
231
+ */
232
+ export function migrationWorking(size: number, gel: GelType): Working {
233
+ const [high, low, own] = [Math.log10(gel.largest), Math.log10(gel.smallest), Math.log10(size)];
234
+ const round = (value: number): string => String(Math.round(value * 100) / 100);
235
+ const position = bandPosition(size, gel);
236
+ const inside = size <= gel.largest && size >= gel.smallest;
237
+ return {
238
+ of: `how far ${count(size)} bp runs on ${gel.percent}% agarose`, comes: `${Math.round(position * 100)}% of the way down`, kind: "estimate",
239
+ steps: [
240
+ `This gel separates pieces from ${count(gel.largest)} bp, which barely leave the wells, down to ${count(gel.smallest)} bp, which reach the front.`,
241
+ `Distance goes with the logarithm of length: log₁₀ ${count(gel.largest)} = ${round(high)}, log₁₀ ${count(gel.smallest)} = ${round(low)}, log₁₀ ${count(size)} = ${round(own)}.`,
242
+ inside ? `(${round(high)} − ${round(own)}) ÷ (${round(high)} − ${round(low)}) = ${round(position)} of the way from the wells to the front.`
243
+ : `${count(size)} bp is ${size > gel.largest ? "longer" : "shorter"} than this gel separates, so it is drawn at the ${size > gel.largest ? "wells" : "front"}, with anything else of that kind.`,
244
+ ],
245
+ rests: "Small pieces thread through agarose faster than large ones, and over a gel's working range the distance is close to a straight line against the logarithm of length. Real distance also depends on voltage, time, buffer and the shape of the DNA, so read a piece's size against the ladder beside it, never off the distance alone.",
246
+ };
247
+ }
248
+
249
+ /** Something a careful operator would stop and ask about a digest before running the gel. */
250
+ export interface DigestCheck {
251
+ /** `stop` if the gel is unlikely to show what is hoped, `look` if it is only worth a second glance. */
252
+ weight: "stop" | "look";
253
+ /** What to ask, said for a person. */
254
+ says: string;
255
+ /** The comparison that raised it, so it can be checked. */
256
+ because: string;
257
+ }
258
+
259
+ /**
260
+ * What a careful operator would ask of a digest, given the gel it is to be run on.
261
+ *
262
+ * Each may be wrong for a particular bench, and none stops a run.
263
+ *
264
+ * @param part - The molecule.
265
+ * @param plan - The digest, from `planDigest`.
266
+ * @param gel - The gel.
267
+ * @returns The checks that apply, the ones most likely to matter first.
268
+ */
269
+ export function digestChecks(part: { length: number; circular: boolean }, plan: Pick<DigestPlan, "cutters" | "fragments" | "bands">, gel: GelType): DigestCheck[] {
270
+ const checks: DigestCheck[] = [];
271
+ for (const one of plan.cutters.filter((cutter) => cutter.positions.length === 0)) {
272
+ checks.push({ weight: "look", says: `${one.name} does not cut this. It is in the tube and does nothing.`, because: `${one.site} is not in the sequence` });
273
+ }
274
+ for (const band of plan.bands.filter((one) => one.sizes.length > 1 && !one.unresolved)) {
275
+ checks.push({ weight: "stop", says: `${band.sizes.map(count).join(" and ")} bp are too close in size to tell apart. They will look like one band.`, because: `${count(band.sizes[0]! - band.sizes.at(-1)!)} bp apart, under 3% of ${count(band.sizes[0]!)}` });
276
+ }
277
+ const small = plan.fragments.filter((size) => size < gel.smallest);
278
+ if (small.length > 0) checks.push({ weight: "stop", says: `${small.map(count).join(", ")} bp ${small.length === 1 ? "is" : "are"} smaller than ${gel.percent}% agarose separates. ${small.length === 1 ? "It" : "They"} may run off the gel or be too faint to see. A higher percentage would hold ${small.length === 1 ? "it" : "them"}.`, because: `${count(Math.max(...small))} < ${count(gel.smallest)} bp` });
279
+ const large = plan.fragments.filter((size) => size > gel.largest);
280
+ if (large.length > 0) checks.push({ weight: "look", says: `${large.map(count).join(", ")} bp ${large.length === 1 ? "is" : "are"} larger than ${gel.percent}% agarose separates, and will stay near the wells. A lower percentage would spread ${large.length === 1 ? "it" : "them"}.`, because: `${count(Math.min(...large))} > ${count(gel.largest)} bp` });
281
+ if (part.circular && plan.fragments.length === 1) {
282
+ checks.push({ weight: "look", says: "One cut opens the circle into one piece of its full length. The gel shows that it cut and how long the plasmid is, and nothing about what is where on it. Two cuts say more.", because: "1 cut, 1 piece" });
283
+ }
284
+ if (plan.cutters.some((one) => one.name === "DpnI" && one.positions.length > 0)) {
285
+ checks.push({ weight: "look", says: "DpnI only cuts DNA that is methylated, as it is when grown in most lab strains of E. coli. It will not cut a PCR product.", because: "DpnI needs methylated GATC" });
286
+ }
287
+ return checks.sort((a, b) => Number(b.weight === "stop") - Number(a.weight === "stop"));
288
+ }