@biolibs/bionet-tools 0.0.0-stage → 0.1.1

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 (48) hide show
  1. package/README.md +104 -2
  2. package/dist/digest-tool.d.ts +30 -0
  3. package/dist/digest-tool.d.ts.map +1 -0
  4. package/dist/digest-tool.js +84 -0
  5. package/dist/digest-tool.js.map +1 -0
  6. package/dist/digest.d.ts +94 -0
  7. package/dist/digest.d.ts.map +1 -0
  8. package/dist/digest.js +115 -0
  9. package/dist/digest.js.map +1 -0
  10. package/dist/index.d.ts +29 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +29 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/pcr-bench.d.ts +94 -0
  15. package/dist/pcr-bench.d.ts.map +1 -0
  16. package/dist/pcr-bench.js +187 -0
  17. package/dist/pcr-bench.js.map +1 -0
  18. package/dist/pcr-scene.d.ts +247 -0
  19. package/dist/pcr-scene.d.ts.map +1 -0
  20. package/dist/pcr-scene.js +287 -0
  21. package/dist/pcr-scene.js.map +1 -0
  22. package/dist/pcr-tool.d.ts +18 -0
  23. package/dist/pcr-tool.d.ts.map +1 -0
  24. package/dist/pcr-tool.js +73 -0
  25. package/dist/pcr-tool.js.map +1 -0
  26. package/dist/pcr.d.ts +59 -0
  27. package/dist/pcr.d.ts.map +1 -0
  28. package/dist/pcr.js +79 -0
  29. package/dist/pcr.js.map +1 -0
  30. package/dist/run.d.ts +161 -0
  31. package/dist/run.d.ts.map +1 -0
  32. package/dist/run.js +143 -0
  33. package/dist/run.js.map +1 -0
  34. package/dist/tools.d.ts +27 -0
  35. package/dist/tools.d.ts.map +1 -0
  36. package/dist/tools.js +45 -0
  37. package/dist/tools.js.map +1 -0
  38. package/package.json +61 -4
  39. package/src/digest-tool.tsx +199 -0
  40. package/src/digest.ts +136 -0
  41. package/src/index.ts +28 -0
  42. package/src/pcr-bench.tsx +350 -0
  43. package/src/pcr-scene.ts +408 -0
  44. package/src/pcr-tool.tsx +160 -0
  45. package/src/pcr.ts +87 -0
  46. package/src/run.ts +234 -0
  47. package/src/tools.tsx +64 -0
  48. package/tools.css +50 -0
@@ -0,0 +1,199 @@
1
+ "use client";
2
+
3
+ /**
4
+ * A check digest from the freezer, with the gel it should give.
5
+ *
6
+ * Like the PCR tool it holds only what has been chosen. The pieces and the gel come from
7
+ * `planDigest`, and recording is one thing asked of the lab.
8
+ */
9
+ import { useMemo, useState } from "react";
10
+ import type { Band } from "@biolibs/gel";
11
+ import { GELS, LADDERS } from "@biolibs/gel";
12
+ import { useAct, useLab } from "@biolibs/bionet-react";
13
+ import { Glossed } from "@biolibs/glossary-react";
14
+ import { cutters, enzymeNamed } from "./digest.js";
15
+ import { digestRun, digestTubes } from "./run.js";
16
+
17
+ /**
18
+ * A gel, drawn: a ladder in one lane and the digest in the next.
19
+ *
20
+ * @param props - `ladder` and `bands` are what `planDigest` gave; `name` is what the sample is called.
21
+ */
22
+ export function Gel({ ladder, bands, name }: { ladder: readonly Band[]; bands: readonly Band[]; name: string }) {
23
+ const [top, height] = [26, 250];
24
+ const lane = (x: number, drawn: readonly Band[], tone: string, labelled: "left" | "right"): React.ReactNode => drawn.map((band, at) => {
25
+ const y = top + 10 + band.position * (height - 24);
26
+ return (
27
+ <g key={`${x} ${at}`}>
28
+ <rect x={x} y={y - 1.6} width={54} height={3.2} rx={1.2} fill={tone} opacity={0.3 + 0.7 * band.intensity} />
29
+ <text x={labelled === "left" ? x - 6 : x + 60} y={y + 3.5} textAnchor={labelled === "left" ? "end" : "start"} className={labelled === "left" ? "mark" : "size"}>
30
+ {band.sizes.length > 1 ? `${band.sizes.join(" + ")}` : band.size}{band.unresolved ? " *" : ""}
31
+ </text>
32
+ </g>
33
+ );
34
+ });
35
+ return (
36
+ <svg className="gel" viewBox="0 0 330 290" role="img" aria-label={`A gel: a ladder beside ${name}, cut into pieces of ${bands.flatMap((band) => band.sizes).join(", ")} base pairs`}>
37
+ <rect x={52} y={top} width={176} height={height} rx={6} className="slab" />
38
+ <text x={89} y={16} textAnchor="middle" className="lane">ladder</text>
39
+ <text x={177} y={16} textAnchor="middle" className="lane">{name.length > 16 ? `${name.slice(0, 15)}…` : name}</text>
40
+ <rect x={62} y={top + 4} width={54} height={4} className="well" />
41
+ <rect x={150} y={top + 4} width={54} height={4} className="well" />
42
+ {lane(62, ladder, "var(--bionet-dim)", "left")}
43
+ {lane(150, bands, "var(--bionet-held)", "right")}
44
+ </svg>
45
+ );
46
+ }
47
+
48
+ /**
49
+ * Cut a tube's molecule in silico, see the gel it should give, and record whether the real gel matched.
50
+ *
51
+ * Choose a tube and one or more enzymes. The enzymes usually on a shelf that cut it are offered,
52
+ * the ones that cut fewest times first, and any other can be named. The pieces are listed and drawn
53
+ * as a gel beside a ladder. Recording takes what was used from the tube and notes whether the gel
54
+ * showed what was expected; nothing is made.
55
+ *
56
+ * @param props - `instrument` is the gel station it is run at, if the lab has one; `onDone` adds a
57
+ * way to leave.
58
+ */
59
+ export function DigestTool({ instrument = null, onDone }: { instrument?: { id: string; name: string } | null; onDone?: () => void }) {
60
+ const lab = useLab()?.lab;
61
+ const act = useAct();
62
+ const [tube, setTube] = useState("");
63
+ const [chosen, setChosen] = useState<string[]>([]);
64
+ const [other, setOther] = useState("");
65
+ const [unknown, setUnknown] = useState<string | null>(null);
66
+ const [used, setUsed] = useState("1");
67
+ const [gel, setGel] = useState("1.0");
68
+ const [ladder, setLadder] = useState("1kb");
69
+ const [note, setNote] = useState("");
70
+ const [busy, setBusy] = useState(false);
71
+ const [said, setSaid] = useState<string | null>(null);
72
+
73
+ const tubes = useMemo(() => (lab === null || lab === undefined ? [] : digestTubes(lab)), [lab]);
74
+ const part = tubes.find((one) => one.item === tube)?.part;
75
+ const offered = useMemo(() => (part === undefined ? [] : cutters(part)), [part]);
76
+ const run = useMemo(() => (lab === null || lab === undefined ? null : digestRun(lab, {
77
+ tube, enzymes: chosen, gel, ladder, instrument: instrument?.id ?? null, note, ...(used.trim() === "" ? {} : { used: Number(used) }),
78
+ })), [lab, tube, chosen, gel, ladder, instrument, note, used]);
79
+ if (lab === null || lab === undefined || run === null) return null;
80
+
81
+ const toggle = (name: string): void => { setChosen(chosen.includes(name) ? chosen.filter((one) => one !== name) : [...chosen, name]); setSaid(null); };
82
+ const record = async (what: Record<string, unknown> | null, done: string): Promise<void> => {
83
+ if (what === null) return;
84
+ setBusy(true);
85
+ const answer = await act("recordRun", what);
86
+ setBusy(false);
87
+ if (answer.ok) { setSaid(done); setNote(""); }
88
+ };
89
+ const here = lab.runs.filter((one) => one.kind === "digest" && (instrument === null || one.instrument === instrument.id)).slice(-5).reverse();
90
+ const partName = (item: string | undefined): string => lab.parts.find((one) => one.checksum === lab.items.find((each) => each.item === item)?.part)?.name ?? "a tube";
91
+
92
+ return (
93
+ <div className="pcr digest">
94
+ <section className="card">
95
+ <div className="toolhead">
96
+ <div>
97
+ <h2>Digest and gel{instrument === null ? "" : ` · ${instrument.name}`}</h2>
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>
99
+ </div>
100
+ {onDone !== undefined && <button type="button" className="quiet" onClick={onDone}>Back to the lab</button>}
101
+ </div>
102
+ {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> : (
103
+ <fieldset disabled={busy} className="choose">
104
+ <div className="tube">
105
+ <label>Tube
106
+ <select value={tube} onChange={(event) => { setTube(event.target.value); setChosen([]); setSaid(null); }} aria-label="Tube">
107
+ <option value="">Choose a tube…</option>
108
+ {tubes.map((one) => <option key={one.item} value={one.item}>{one.label}</option>)}
109
+ </select>
110
+ </label>
111
+ <label className="used">used<input type="number" min={0} step={1} value={used} onChange={(event) => setUsed(event.target.value)} aria-label="Amount used" /></label>
112
+ {part !== undefined && <p className="dim small">{part.length} bp{part.circular ? " · circular" : " · linear"}</p>}
113
+ </div>
114
+ {part !== undefined && (
115
+ <div>
116
+ <p className="label">Enzymes{offered.length === 0 ? " · none of the usual ones cut this" : ""}</p>
117
+ <div className="enzymes">
118
+ {offered.map((one) => (
119
+ <label key={one.name} className="check" title={`${one.site} · cuts ${one.positions.length === 1 ? "once" : `${one.positions.length} times`}`}>
120
+ <input type="checkbox" checked={chosen.includes(one.name)} onChange={() => toggle(one.name)} /> {one.name} <span className="dim small">×{one.positions.length}</span>
121
+ </label>
122
+ ))}
123
+ {chosen.filter((name) => !offered.some((one) => one.name === name)).map((name) => (
124
+ <label key={name} className="check"><input type="checkbox" checked onChange={() => toggle(name)} /> {name}</label>
125
+ ))}
126
+ </div>
127
+ <form className="row tight" onSubmit={(event) => {
128
+ event.preventDefault();
129
+ const name = enzymeNamed(other);
130
+ setUnknown(name === null && other.trim() !== "" ? other.trim() : null);
131
+ if (name !== null && !chosen.includes(name)) setChosen([...chosen, name]);
132
+ if (name !== null) setOther("");
133
+ }}>
134
+ <input value={other} onChange={(event) => setOther(event.target.value)} placeholder="Another enzyme, by name" aria-label="Another enzyme" maxLength={40} spellCheck={false} />
135
+ <button type="submit" className="quiet">Add</button>
136
+ </form>
137
+ {unknown !== null && <p className="trouble small" role="status">There is no enzyme called {unknown} here.</p>}
138
+ </div>
139
+ )}
140
+ </fieldset>
141
+ )}
142
+ </section>
143
+
144
+ {run.plan !== null && chosen.length > 0 && (
145
+ <section className="card">
146
+ <h2>What it gives</h2>
147
+ {run.plan.problem !== null ? <p className="trouble" role="status">{run.plan.problem}</p> : (
148
+ <div className="result">
149
+ <Gel ladder={run.plan.ladder} bands={run.plan.bands} name={part?.name ?? "digest"} />
150
+ <div>
151
+ <p><strong>{run.plan.fragments.length} {run.plan.fragments.length === 1 ? "piece" : "pieces"}</strong> <span className="dim">{run.plan.fragments.join(", ")} bp</span></p>
152
+ <table>
153
+ <thead><tr><th>Enzyme</th><th>Site</th><th>Cuts after base</th></tr></thead>
154
+ <tbody>{run.plan.cutters.map((one) => <tr key={one.name}><td>{one.name}</td><td><code>{one.site}</code></td><td>{one.positions.length === 0 ? <span className="dim">does not cut</span> : one.positions.join(", ")}</td></tr>)}</tbody>
155
+ </table>
156
+ <div className="row tight">
157
+ <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>
158
+ <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>
159
+ </div>
160
+ {run.plan.bands.some((band) => band.unresolved) && <p className="dim small">* outside what this gel separates. Try another concentration.</p>}
161
+ {run.plan.bands.some((band) => band.sizes.length > 1) && <p className="dim small">Pieces too close in size to tell apart run as one band.</p>}
162
+ </div>
163
+ </div>
164
+ )}
165
+ {run.plan.problem === null && (
166
+ <fieldset disabled={busy} className="stack">
167
+ <label>Note<input value={note} onChange={(event) => setNote(event.target.value)} placeholder="Anything worth remembering about this gel" maxLength={2000} /></label>
168
+ <div className="row">
169
+ <button type="button" onClick={() => void record(run.matched, "Recorded: the gel showed what was expected.")}>The gel matched</button>
170
+ <button type="button" className="quiet" onClick={() => void record(run.differed, "Recorded: the gel did not show what was expected.")}>The gel did not match</button>
171
+ </div>
172
+ </fieldset>
173
+ )}
174
+ {said !== null && <p className="small" role="status">{said}</p>}
175
+ </section>
176
+ )}
177
+
178
+ {here.length > 0 && (
179
+ <section className="card">
180
+ <h2>Recent digests{instrument === null ? "" : " here"}</h2>
181
+ <table>
182
+ <thead><tr><th>Tube</th><th>Enzymes</th><th>Expected</th><th>Gel</th><th>Note</th></tr></thead>
183
+ <tbody>
184
+ {here.map((one) => (
185
+ <tr key={one.run}>
186
+ <td>{partName(one.inputs[0]?.item)}</td>
187
+ <td>{String(one.settings["enzymes"] ?? "").replace(/\+/g, " + ")}</td>
188
+ <td className="dim">{String(one.settings["expected"] ?? "")}</td>
189
+ <td>{one.outcome === "worked" ? "matched" : <span className="badge">did not match</span>}</td>
190
+ <td className="dim">{one.note ?? ""}</td>
191
+ </tr>
192
+ ))}
193
+ </tbody>
194
+ </table>
195
+ </section>
196
+ )}
197
+ </div>
198
+ );
199
+ }
package/src/digest.ts ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * A restriction digest, and the gel it would give, worked out before either is run.
3
+ *
4
+ * Given a molecule and some enzymes this says where they cut, how long the pieces are, and where
5
+ * each piece would run on a gel beside a ladder. Like `pcr.ts` it knows sequences and nothing of
6
+ * the lab.
7
+ */
8
+ import { bandsOf, fragmentSizes, gelById, ladderBands, ladderById, type Band } from "@biolibs/gel";
9
+ import { enzymes } from "@biolibs/restriction";
10
+ import { Seq } from "@biolibs/seq";
11
+
12
+ /** The enzymes offered first: the ones most often on a lab's shelf. Any other may be named. */
13
+ export const COMMON_ENZYMES: readonly string[] = [
14
+ "EcoRI", "BamHI", "HindIII", "XhoI", "NotI", "XbaI", "SpeI", "PstI", "NcoI", "NdeI", "KpnI", "SacI",
15
+ "SalI", "EcoRV", "SmaI", "BglII", "NheI", "AgeI", "ApaI", "ClaI", "MluI", "BsaI", "BsmBI", "DpnI",
16
+ ];
17
+
18
+ /** The gel a digest is run on unless somebody says otherwise: 1% agarose. */
19
+ export const USUAL_GEL = "1.0";
20
+
21
+ /** The ladder run beside it unless somebody says otherwise. */
22
+ export const USUAL_LADDER = "1kb";
23
+
24
+ /** One enzyme and where it cuts a molecule. */
25
+ export interface Cutter {
26
+ /** The enzyme's name. */
27
+ name: string;
28
+ /** The sequence it recognises. */
29
+ site: string;
30
+ /** Where it cuts, counted from the start of the molecule, in order. */
31
+ positions: number[];
32
+ }
33
+
34
+ /** What a digest would give. */
35
+ export interface DigestPlan {
36
+ /** Each enzyme asked for that is a real one, and where it cuts. */
37
+ cutters: Cutter[];
38
+ /** How long each piece is, longest first. */
39
+ fragments: number[];
40
+ /** The bands the pieces would show. */
41
+ bands: Band[];
42
+ /** The bands of the ladder beside them. */
43
+ ladder: Band[];
44
+ /** The gel and the ladder it was worked out for. */
45
+ gel: string;
46
+ ladderName: string;
47
+ /** Why there is nothing to look at, said for a person, or `null` if there is. */
48
+ problem: string | null;
49
+ }
50
+
51
+ const clean = (text: string): string => text.replace(/\s+/g, "").toUpperCase();
52
+
53
+ /**
54
+ * Find an enzyme whatever case its name was typed in.
55
+ *
56
+ * @param name - Something like `ecori`.
57
+ * @returns Its name as it is written, or `null` if there is no such enzyme.
58
+ */
59
+ export function enzymeNamed(name: string): string | null {
60
+ const typed = name.trim();
61
+ if (typed === "") return null;
62
+ if (Object.hasOwn(enzymes, typed)) return typed;
63
+ const lower = typed.toLowerCase();
64
+ return Object.keys(enzymes).find((one) => one.toLowerCase() === lower) ?? null;
65
+ }
66
+
67
+ /**
68
+ * Where one enzyme cuts a molecule.
69
+ *
70
+ * @param part - The molecule.
71
+ * @param name - The enzyme, by its name as written.
72
+ * @returns The enzyme and its cuts, or `null` if there is no such enzyme or the molecule is not a sequence.
73
+ */
74
+ export function cutsOf(part: { sequence: string; circular: boolean }, name: string): Cutter | null {
75
+ const enzyme = Object.hasOwn(enzymes, name) ? enzymes[name] : undefined;
76
+ if (enzyme === undefined) return null;
77
+ const bases = clean(part.sequence);
78
+ try {
79
+ // The engine counts from 1 and gives the base after the cut.
80
+ const found = enzyme.search(new Seq(bases), !part.circular).map((at) => (at - 1 + bases.length) % bases.length);
81
+ return { name, site: String(enzyme.site), positions: [...new Set(found)].sort((a, b) => a - b) };
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * The enzymes, of those usually on a shelf, that cut a molecule.
89
+ *
90
+ * @param part - The molecule.
91
+ * @param names - The enzymes to try.
92
+ * @returns Those that cut it, the ones that cut fewest times first, since one or two cuts is what a
93
+ * check digest wants.
94
+ */
95
+ export function cutters(part: { sequence: string; circular: boolean }, names: readonly string[] = COMMON_ENZYMES): Cutter[] {
96
+ return names.map((name) => cutsOf(part, name)).filter((one): one is Cutter => one !== null && one.positions.length > 0)
97
+ .sort((a, b) => a.positions.length - b.positions.length || a.name.localeCompare(b.name));
98
+ }
99
+
100
+ /**
101
+ * Work out a digest and the gel it would give.
102
+ *
103
+ * @param part - The molecule.
104
+ * @param names - The enzymes, by name.
105
+ * @param options - `gel` is the agarose concentration's ID and `ladder` the ladder's, from `@biolibs/gel`.
106
+ * @returns The cuts, the pieces, the bands, and what is wrong if there is nothing to look at.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * import { planDigest } from "@biolibs/bionet-tools";
111
+ *
112
+ * const plan = planDigest({ sequence: "AAAAAAAAAAGAATTCAAAAAAAAAAAAAAAAAAAAGGATCCAAAAAAAAAA", circular: true }, ["EcoRI", "BamHI"]);
113
+ * plan.fragments; // [ 26, 26 ]
114
+ * plan.problem; // null
115
+ * ```
116
+ */
117
+ export function planDigest(part: { sequence: string; circular: boolean }, names: readonly string[],
118
+ options: { gel?: string; ladder?: string } = {}): DigestPlan {
119
+ let gel = gelById(USUAL_GEL);
120
+ let ladder = ladderById(USUAL_LADDER);
121
+ try { gel = gelById(options.gel ?? USUAL_GEL); } catch { /* an unknown gel is run as the usual one */ }
122
+ try { ladder = ladderById(options.ladder ?? USUAL_LADDER); } catch { /* and an unknown ladder likewise */ }
123
+ const length = clean(part.sequence).length;
124
+ const found = [...new Set(names)].map((name) => cutsOf(part, name)).filter((one): one is Cutter => one !== null);
125
+ const empty = { cutters: found, fragments: [], bands: [], ladder: ladderBands(ladder.sizes, gel), gel: gel.id, ladderName: ladder.name };
126
+ if (names.length === 0) return { ...empty, problem: "Choose at least one enzyme." };
127
+ if (found.length === 0) return { ...empty, problem: "None of those is an enzyme this knows." };
128
+ const cuts = [...new Set(found.flatMap((one) => one.positions))];
129
+ if (cuts.length === 0) return { ...empty, problem: `${found.map((one) => one.name).join(" and ")} ${found.length === 1 ? "does" : "do"} not cut this.` };
130
+ try {
131
+ const fragments = fragmentSizes(length, part.circular ? "circular" : "linear", cuts).sort((a, b) => b - a);
132
+ return { ...empty, fragments, bands: bandsOf(fragments, gel), problem: null };
133
+ } catch {
134
+ return { ...empty, problem: "That could not be cut into pieces." };
135
+ }
136
+ }
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@biolibs/bionet-tools`: the tools a lab uses at the bench, tied to its freezer.
4
+ *
5
+ * A tool here works on the tubes a lab holds and records what was done with them. Running a PCR is
6
+ * choosing a template and two primers from the freezer, seeing what they would make, and recording
7
+ * the run: the template and primers drop by what was used, and the product is a new tube that knows
8
+ * which run made it.
9
+ *
10
+ * - `pcr.ts` — what a PCR would make, worked out from sequences alone
11
+ * - `pcr-scene.ts` — a PCR as met at the machine: the programme it shows, the checks, and what is in the tube
12
+ * - `digest.ts` — where enzymes cut, the pieces, and the gel they would give
13
+ * - `run.ts` — a PCR as a lab does one: which tubes, and what to record
14
+ * - `pcr-tool.tsx`, `digest-tool.tsx` — the tools
15
+ * - `pcr-bench.tsx` — a PCR at the machine: what is beside the scene, and what the scene is told to show
16
+ * - `tools.tsx` — getting to one: from an instrument, or from a list of them all
17
+ *
18
+ * The tools are drawn with the styles of `@biolibs/bionet-panels` and belong inside its `LabWindow`.
19
+ * Import `@biolibs/bionet-tools/tools.css` once.
20
+ */
21
+ export * from "./pcr.js";
22
+ export * from "./pcr-scene.js";
23
+ export * from "./digest.js";
24
+ export * from "./run.js";
25
+ export * from "./pcr-tool.js";
26
+ export * from "./digest-tool.js";
27
+ export * from "./tools.js";
28
+ export * from "./pcr-bench.js";