@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,410 @@
1
+ /**
2
+ * A PCR as a person at the machine meets it: what the machine shows, and what they have to picture.
3
+ *
4
+ * A thermocycler shows a programme, a temperature and a cycle count. It says nothing about DNA. What
5
+ * is happening in the tube — strands parting, primers finding their places, copies being made, and
6
+ * which of those copies are the product — the operator has to picture. This works both out as plain
7
+ * data, so a scene can draw them and a test can check them:
8
+ *
9
+ * - the **programme**, as the machine shows it, suggested from the reaction;
10
+ * - the **checks** a careful operator would make of it, each about this run and each able to be wrong;
11
+ * - where each **primer binds**, on which strand;
12
+ * - what is **in the tube** at each step of each cycle.
13
+ */
14
+
15
+ /** The three things a cycle does. */
16
+ export type PcrStepName = "denature" | "anneal" | "extend";
17
+
18
+ /** One step of a programme: how hot, and for how long. */
19
+ export interface PcrStep {
20
+ /** Which step it is. */
21
+ name: PcrStepName;
22
+ /** The block's temperature, in whole degrees Celsius. */
23
+ celsius: number;
24
+ /** How long it is held, in whole seconds. */
25
+ seconds: number;
26
+ }
27
+
28
+ /** A thermocycler's programme. */
29
+ export interface PcrProgramme {
30
+ /** The first, longer melt before cycling starts. */
31
+ initial: { celsius: number; seconds: number };
32
+ /** The three steps of a cycle, in order. */
33
+ steps: [PcrStep, PcrStep, PcrStep];
34
+ /** How many times the cycle is run. */
35
+ cycles: number;
36
+ /** The last, longer extension after cycling ends. */
37
+ final: { celsius: number; seconds: number };
38
+ }
39
+
40
+ /** What the tool knows of a reaction when it suggests or checks a programme. */
41
+ export interface PcrReaction {
42
+ /** How long the product is, in bases. */
43
+ length: number;
44
+ /** Each primer's name and rough melting temperature, in degrees Celsius. */
45
+ primers: { name: string; tm: number }[];
46
+ }
47
+
48
+ const clamp = (value: number, least: number, most: number): number => Math.min(Math.max(value, least), most);
49
+
50
+ /** How long a polymerase is usually given: a minute for every thousand bases. */
51
+ export const SECONDS_PER_KB = 60;
52
+
53
+ /**
54
+ * A programme that suits a reaction, to start from.
55
+ *
56
+ * The annealing step is five degrees under the cooler primer, and the extension allows a minute for
57
+ * every thousand bases. Both are conventions, and the operator may know better.
58
+ *
59
+ * @param reaction - The product's length and the primers' melting temperatures.
60
+ * @returns The programme.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * import { suggestProgramme } from "@biolibs/bionet-tools";
65
+ *
66
+ * const programme = suggestProgramme({ length: 1500, primers: [{ name: "fwd", tm: 60 }, { name: "rev", tm: 58 }] });
67
+ * programme.steps[1]; // { name: "anneal", celsius: 53, seconds: 30 }
68
+ * programme.steps[2]; // { name: "extend", celsius: 72, seconds: 90 }
69
+ * ```
70
+ */
71
+ export function suggestProgramme(reaction: PcrReaction): PcrProgramme {
72
+ const coolest = reaction.primers.length === 0 ? 60 : Math.min(...reaction.primers.map((one) => one.tm));
73
+ const extend = Math.max(15, Math.ceil(((reaction.length / 1000) * SECONDS_PER_KB) / 5) * 5);
74
+ return {
75
+ initial: { celsius: 95, seconds: 120 },
76
+ steps: [
77
+ { name: "denature", celsius: 95, seconds: 30 },
78
+ { name: "anneal", celsius: clamp(Math.round(coolest) - 5, 45, 72), seconds: 30 },
79
+ { name: "extend", celsius: 72, seconds: extend },
80
+ ],
81
+ cycles: 30,
82
+ final: { celsius: 72, seconds: 300 },
83
+ };
84
+ }
85
+
86
+ /** A length of time as a machine writes it: minutes and seconds. */
87
+ const clock = (seconds: number): string => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
88
+
89
+ /** One line of a thermocycler's screen. */
90
+ export interface ScreenLine {
91
+ /** What it says. */
92
+ text: string;
93
+ /** The step of the cycle it is, if it is one. */
94
+ step?: PcrStepName;
95
+ }
96
+
97
+ /**
98
+ * A programme as a thermocycler's screen shows it.
99
+ *
100
+ * @param programme - The programme.
101
+ * @returns The lines, top to bottom.
102
+ */
103
+ export function screenOf(programme: PcrProgramme): ScreenLine[] {
104
+ const row = (label: string, at: { celsius: number; seconds: number }): string => `${label.padEnd(9)}${String(at.celsius).padStart(3)} °C ${clock(at.seconds).padStart(5)}`;
105
+ return [
106
+ { text: row("Start", programme.initial) },
107
+ { text: `${programme.cycles} cycles of` },
108
+ ...programme.steps.map((step) => ({ text: row(` ${step.name[0]!.toUpperCase()}${step.name.slice(1)}`, step), step: step.name })),
109
+ { text: row("Finish", programme.final) },
110
+ { text: `About ${clock(runSeconds(programme))} in all` },
111
+ ];
112
+ }
113
+
114
+ /**
115
+ * How long a programme takes, not counting the time the block spends changing temperature.
116
+ *
117
+ * @param programme - The programme.
118
+ * @returns Seconds.
119
+ */
120
+ export function runSeconds(programme: PcrProgramme): number {
121
+ return programme.initial.seconds + programme.cycles * programme.steps.reduce((sum, step) => sum + step.seconds, 0) + programme.final.seconds;
122
+ }
123
+
124
+ /** Something a careful operator would stop and ask about a programme. */
125
+ export interface PcrCheck {
126
+ /** The part of the programme it is about. */
127
+ about: PcrStepName | "cycles";
128
+ /** `stop` if the run is unlikely to work as set, `look` if it is only worth a second glance. */
129
+ weight: "stop" | "look";
130
+ /** What to ask, said for a person. */
131
+ says: string;
132
+ /** The comparison that raised it, so it can be checked. */
133
+ because: string;
134
+ }
135
+
136
+ /**
137
+ * What a careful operator would ask of a programme, given the reaction it is for.
138
+ *
139
+ * Each is about this run and may be wrong: an operator who knows their polymerase extends at fifteen
140
+ * seconds a thousand bases can ignore what is said about extension. None of them stops a run.
141
+ *
142
+ * @param programme - The programme as set.
143
+ * @param reaction - The product's length and the primers' melting temperatures.
144
+ * @returns The checks that apply, the ones most likely to matter first.
145
+ */
146
+ export function programmeChecks(programme: PcrProgramme, reaction: PcrReaction): PcrCheck[] {
147
+ const checks: PcrCheck[] = [];
148
+ const [denature, anneal, extend] = programme.steps;
149
+ const sorted = [...reaction.primers].sort((a, b) => a.tm - b.tm);
150
+ const coolest = sorted[0];
151
+ const warmest = sorted.at(-1);
152
+ if (coolest !== undefined && anneal.celsius > coolest.tm) {
153
+ checks.push({ about: "anneal", weight: "stop", says: `Annealing at ${anneal.celsius} °C is above ${coolest.name}'s melting temperature, about ${Math.round(coolest.tm)} °C. It may not bind.`, because: `${anneal.celsius} °C > ${Math.round(coolest.tm)} °C` });
154
+ } else if (coolest !== undefined && anneal.celsius < coolest.tm - 10) {
155
+ checks.push({ about: "anneal", weight: "look", says: `Annealing at ${anneal.celsius} °C is more than ten degrees under the primers' melting temperatures. They may bind in places they should not.`, because: `${anneal.celsius} °C < ${Math.round(coolest.tm)} − 10 = ${Math.round(coolest.tm) - 10} °C` });
156
+ }
157
+ if (coolest !== undefined && warmest !== undefined && warmest.tm - coolest.tm > 5) {
158
+ checks.push({ about: "anneal", weight: "look", says: `${warmest.name} melts about ${Math.round(warmest.tm - coolest.tm)} degrees above ${coolest.name}. No one annealing temperature suits both well.`, because: `${Math.round(warmest.tm)} − ${Math.round(coolest.tm)} = ${Math.round(warmest.tm - coolest.tm)} > 5` });
159
+ }
160
+ const wanted = (reaction.length / 1000) * SECONDS_PER_KB;
161
+ if (extend.seconds < wanted / 2) {
162
+ checks.push({ about: "extend", weight: "stop", says: `${extend.seconds} seconds is short for a ${reaction.length.toLocaleString("en-US")} base product. Allow about a minute for every thousand bases unless the polymerase is a fast one.`, because: `${extend.seconds} s < half of ${reaction.length.toLocaleString("en-US")} ÷ 1,000 × ${SECONDS_PER_KB} = ${Math.round(wanted)} s` });
163
+ } else if (extend.seconds < wanted) {
164
+ checks.push({ about: "extend", weight: "look", says: `${extend.seconds} seconds is under a minute per thousand bases for a ${reaction.length.toLocaleString("en-US")} base product. Fine for a fast polymerase.`, because: `${extend.seconds} s < ${reaction.length.toLocaleString("en-US")} ÷ 1,000 × ${SECONDS_PER_KB} = ${Math.round(wanted)} s` });
165
+ }
166
+ if (denature.celsius < 90) checks.push({ about: "denature", weight: "stop", says: `${denature.celsius} °C may not separate the strands. It is usually 94 to 98 °C.`, because: `${denature.celsius} °C < 90 °C` });
167
+ if (programme.cycles > 40) checks.push({ about: "cycles", weight: "look", says: `${programme.cycles} cycles is a lot. Past about 35, wrong products build up faster than the right one.`, because: `${programme.cycles} > 40` });
168
+ if (programme.cycles < 15) checks.push({ about: "cycles", weight: "look", says: `${programme.cycles} cycles may not make enough to see on a gel.`, because: `${programme.cycles} < 15` });
169
+ return checks.sort((a, b) => Number(b.weight === "stop") - Number(a.weight === "stop"));
170
+ }
171
+
172
+ /** Where a primer binds a template. Positions count bases from the start of the template's top strand. */
173
+ export interface Binding {
174
+ /** The first base it covers. */
175
+ start: number;
176
+ /** One past the last base it covers. */
177
+ end: number;
178
+ /** `top` if it has the top strand's sequence, and so binds the bottom strand and is copied rightwards; `bottom` the other way. */
179
+ reads: "top" | "bottom";
180
+ /** How many bases at its 5′ end do not bind: a tail it carries onto the product. */
181
+ tail: number;
182
+ }
183
+
184
+ const PAIR: Readonly<Record<string, string>> = { A: "T", T: "A", G: "C", C: "G", U: "A", N: "N" };
185
+ const reversed = (bases: string): string => [...bases].reverse().map((base) => PAIR[base] ?? "N").join("");
186
+
187
+ /**
188
+ * Where one primer binds a template, if it does.
189
+ *
190
+ * It is looked for by the bases at its 3′ end, which are the ones that have to match, on either
191
+ * strand. Its match is then followed back towards its 5′ end for as long as it holds.
192
+ *
193
+ * @param template - The template's top strand.
194
+ * @param primer - The primer, 5′ to 3′.
195
+ * @param least - How many bases at its 3′ end must match.
196
+ * @returns Where it binds, or `null` if it does not or binds in more than one place.
197
+ */
198
+ export function primerBinding(template: string, primer: string, least = 18): Binding | null {
199
+ const top = template.replace(/\s+/g, "").toUpperCase();
200
+ const bases = primer.replace(/\s+/g, "").toUpperCase();
201
+ if (bases.length < least || least < 1) return null;
202
+ const found: Binding[] = [];
203
+ // Reading as the top strand: its 3′ end is its right-hand end.
204
+ const end3 = bases.slice(-least);
205
+ for (let at = top.indexOf(end3); at !== -1; at = top.indexOf(end3, at + 1)) {
206
+ let matched = least;
207
+ while (matched < bases.length && at - (matched - least) - 1 >= 0 && top[at - (matched - least) - 1] === bases[bases.length - matched - 1]) matched++;
208
+ found.push({ start: at - (matched - least), end: at + least, reads: "top", tail: bases.length - matched });
209
+ }
210
+ // Reading as the bottom strand: reversed, its 3′ end is its left-hand end.
211
+ const flipped = reversed(bases);
212
+ const start3 = flipped.slice(0, least);
213
+ for (let at = top.indexOf(start3); at !== -1; at = top.indexOf(start3, at + 1)) {
214
+ let matched = least;
215
+ while (matched < flipped.length && at + matched < top.length && top[at + matched] === flipped[matched]) matched++;
216
+ found.push({ start: at, end: at + matched, reads: "bottom", tail: bases.length - matched });
217
+ }
218
+ return found.length === 1 ? found[0]! : null;
219
+ }
220
+
221
+ /** One line drawn in the tube: a strand, or a primer on one. */
222
+ export interface TubeStrand {
223
+ /** Where it starts and ends, in bases along the template. */
224
+ from: number;
225
+ to: number;
226
+ /** Which of the four rows it is drawn on, from the top: 0 and 3 are the template's strands, 1 and 2 what lies between them. */
227
+ row: 0 | 1 | 2 | 3;
228
+ /** What it is. */
229
+ kind: "template" | "primer" | "growing" | "long" | "product";
230
+ /** Whether its 3′ end is at `to` (it points right) or at `from`. */
231
+ points: "right" | "left";
232
+ /**
233
+ * What it does during the step, if it does anything: `parts` from the strand it was paired with,
234
+ * `lands` on the strand it matches, or `grows` from its primer towards its 3′ end.
235
+ */
236
+ moves?: "parts" | "lands" | "grows";
237
+ }
238
+
239
+ /** What is in the tube at one step of one cycle. */
240
+ export interface TubeView {
241
+ /** What to draw. */
242
+ strands: TubeStrand[];
243
+ /** How many strands of each kind there are after this cycle, starting from one double-stranded template. */
244
+ counts: { template: number; long: number; product: number };
245
+ /** What is happening, in a sentence. */
246
+ says: string;
247
+ }
248
+
249
+ /**
250
+ * How many strands of each kind a tube holds after some cycles, from one double-stranded template.
251
+ *
252
+ * The template's two strands are never made more of. Each cycle copies them once more into strands
253
+ * that start at a primer and run on past the other one: there are two more of those every cycle.
254
+ * Everything else is the product, cut to length at both ends, and it doubles.
255
+ *
256
+ * @param cycles - How many cycles have finished.
257
+ * @returns The counts. They add up to twice two to the power of the cycles.
258
+ */
259
+ export function strandCounts(cycles: number): { template: number; long: number; product: number } {
260
+ const done = Math.max(0, Math.floor(cycles));
261
+ return { template: 2, long: 2 * done, product: Math.max(0, 2 ** (done + 1) - 2 * done - 2) };
262
+ }
263
+
264
+ /**
265
+ * What is in the tube at one step of one cycle.
266
+ *
267
+ * It draws the one thing each early cycle adds, since that is what is hard to picture: the first
268
+ * cycle makes strands that run on past the far primer, the second makes the first strands of exactly
269
+ * the product's length, and from the third the product is double-stranded and takes over.
270
+ *
271
+ * @param length - How long the template is, in bases.
272
+ * @param forward - Where the primer that reads as the top strand binds.
273
+ * @param reverse - Where the primer that reads as the bottom strand binds.
274
+ * @param step - Which step of the cycle.
275
+ * @param cycle - Which cycle, counting from 1.
276
+ * @returns What to draw, how many strands of each kind there are once the cycle ends, and a sentence.
277
+ */
278
+ export function tubeView(length: number, forward: Binding, reverse: Binding, step: PcrStepName, cycle: number): TubeView {
279
+ const at = Math.max(1, Math.floor(cycle));
280
+ const template: TubeStrand[] = [
281
+ { from: 0, to: length, row: 0, kind: "template", points: "right" },
282
+ { from: 0, to: length, row: 3, kind: "template", points: "left" },
283
+ ];
284
+ const primers: TubeStrand[] = [
285
+ { from: reverse.start, to: reverse.end, row: 1, kind: "primer", points: "left" },
286
+ { from: forward.start, to: forward.end, row: 2, kind: "primer", points: "right" },
287
+ ];
288
+ // What each strand is copied into depends on what it is copied from, which changes over the first cycles.
289
+ const made = (kind: TubeStrand["kind"]): TubeStrand[] => (at === 1
290
+ ? [{ from: 0, to: reverse.end, row: 1, kind, points: "left" }, { from: forward.start, to: length, row: 2, kind, points: "right" }]
291
+ : [{ from: forward.start, to: reverse.end, row: 1, kind, points: "left" }, { from: forward.start, to: reverse.end, row: 2, kind, points: "right" }]);
292
+ const templates: TubeStrand[] = at === 1 ? template
293
+ : at === 2 ? [{ from: forward.start, to: length, row: 0, kind: "long", points: "right" }, { from: 0, to: reverse.end, row: 3, kind: "long", points: "left" }]
294
+ : [{ from: forward.start, to: reverse.end, row: 0, kind: "product", points: "right" }, { from: forward.start, to: reverse.end, row: 3, kind: "product", points: "left" }];
295
+ const counts = strandCounts(step === "extend" ? at : at - 1);
296
+ if (step === "denature") {
297
+ return { strands: templates.map((one) => ({ ...one, moves: "parts" as const })), counts, says: at === 1
298
+ ? "Heat pulls the template's two strands apart. Nothing can be copied until they are single."
299
+ : at === 2 ? "The strands made in the first cycle part from the template. Each starts at a primer and runs on past the other."
300
+ : "Every double strand parts, including the product made so far." };
301
+ }
302
+ if (step === "anneal") {
303
+ return { strands: [...templates, ...primers.map((one) => ({ ...one, moves: "lands" as const }))], counts, says: "Cooler, the primers find the one place each matches and bind. A primer always points along the strand towards the other primer." };
304
+ }
305
+ return {
306
+ strands: [...templates, ...made(at === 1 ? "long" : "product").map((one) => ({ ...one, moves: "grows" as const }))], counts,
307
+ says: at === 1 ? "The polymerase copies from each primer to the end of the template. These first copies start in the right place and run on too far."
308
+ : at === 2 ? "Copied from a strand that already starts at a primer, the new strand stops where that one began. These are the first strands of exactly the product's length."
309
+ : "From the third cycle the product is copied from the product. It doubles each cycle, and the over-long strands are left behind.",
310
+ };
311
+ }
312
+
313
+ /** One base in the magnified view, and what it is doing. */
314
+ export interface LensCell {
315
+ /** The base, or `""` where the strand has none at this place. */
316
+ base: string;
317
+ /** `paired` with the base opposite, `single`, or `fresh`: just added by the polymerase, and paired. */
318
+ state: "paired" | "single" | "fresh";
319
+ }
320
+
321
+ /** The real bases around one primer's site, at one moment of one step. */
322
+ export interface TubeLens {
323
+ /** The stretch of the template it shows, in bases from the start of the top strand. */
324
+ from: number;
325
+ to: number;
326
+ /** The upper strand, written 5′ to 3′ from the left, one cell for each place on the template. */
327
+ upper: { label: string; cells: LensCell[] };
328
+ /** The lower strand, written 3′ to 5′ from the left, so that each base is under the one it pairs with. */
329
+ lower: { label: string; cells: LensCell[] };
330
+ /** For each place, whether the base above is paired with the base below. */
331
+ joined: boolean[];
332
+ /** The place the polymerase is at, counted from the left of the view, if it is copying. */
333
+ polymerase: number | null;
334
+ /** How many more bases the copy has to go beyond what is shown, when it is being made. */
335
+ beyond: number;
336
+ }
337
+
338
+ /**
339
+ * The real bases at a primer's site, at one moment of one step.
340
+ *
341
+ * The strands in the tube are thousands of bases long and are drawn as lines. This is the same
342
+ * moment magnified at the one place worth reading: where a primer binds. Heat unzips the template
343
+ * there base by base; the primer lands and pairs, A with T and G with C, leaving any tail it carries
344
+ * unpaired; and the polymerase adds the next bases one at a time, each the partner of the base
345
+ * opposite. Every letter is from the lab's own sequences.
346
+ *
347
+ * @param template - The template's top strand.
348
+ * @param primer - The primer, 5′ to 3′.
349
+ * @param binding - Where it binds, from `primerBinding`.
350
+ * @param step - Which step of the cycle.
351
+ * @param through - How far through the step it is, from 0 to 1.
352
+ * @param names - What to call the primer and the template.
353
+ * @returns The two rows of bases, which are paired, and where the polymerase is.
354
+ */
355
+ export function tubeLens(template: string, primer: string, binding: Binding, step: PcrStepName, through: number,
356
+ names: { primer?: string; template?: string } = {}): TubeLens {
357
+ const top = template.replace(/\s+/g, "").toUpperCase();
358
+ const bases = primer.replace(/\s+/g, "").toUpperCase();
359
+ const at = Math.min(Math.max(through, 0), 1);
360
+ const rightward = binding.reads === "top";
361
+ const [ahead, behind] = [22, 3];
362
+ // Room for the primer and its tail, a little behind it, and the first bases copied ahead of it.
363
+ const from = Math.max(0, rightward ? binding.start - binding.tail - behind : binding.start - ahead);
364
+ const to = Math.min(top.length, rightward ? binding.end + ahead : binding.end + binding.tail + behind);
365
+ const places = Array.from({ length: to - from }, (_, index) => from + index);
366
+ const templateName = names.template ?? "template";
367
+ const primerName = names.primer ?? "primer";
368
+
369
+ if (step === "denature") {
370
+ // The two strands come apart from one end of the view to the other.
371
+ const joined = places.map((_, index) => (index + 0.5) / places.length > at * 1.2);
372
+ const cell = (base: string, index: number): LensCell => ({ base, state: joined[index]! ? "paired" : "single" });
373
+ return {
374
+ from, to, joined, polymerase: null, beyond: 0,
375
+ upper: { label: `${templateName}, top strand`, cells: places.map((place, index) => cell(top[place]!, index)) },
376
+ lower: { label: `${templateName}, bottom strand`, cells: places.map((place, index) => cell(PAIR[top[place]!] ?? "N", index)) },
377
+ };
378
+ }
379
+
380
+ // The primer, laid where it binds: left to right 5′→3′ if it reads as the top strand, 3′→5′ if not.
381
+ const laid = rightward ? bases : [...bases].reverse().join("");
382
+ const first = rightward ? binding.start - binding.tail : binding.start;
383
+ const primerBase = (place: number): string => (place >= first && place < first + laid.length ? laid[place - first]! : "");
384
+ const binds = (place: number): boolean => place >= binding.start && place < binding.end;
385
+ const width = binding.end - binding.start;
386
+ // Pairs form along the primer from its 5′ end to its 3′ end, in the second half of the step.
387
+ const zipped = (place: number): boolean => {
388
+ const along = rightward ? place - binding.start : binding.end - 1 - place;
389
+ return step === "extend" || (along + 0.5) / width < (at - 0.45) / 0.5;
390
+ };
391
+ // How many bases the polymerase has added, of those the view has room for.
392
+ const room = rightward ? to - binding.end : binding.start - from;
393
+ const added = step === "extend" ? Math.min(room, Math.floor(at * (room + 1))) : 0;
394
+ const copied = (place: number): boolean => (rightward ? place >= binding.end && place < binding.end + added : place < binding.start && place >= binding.start - added);
395
+ const joined = places.map((place) => (binds(place) && zipped(place)) || copied(place));
396
+ const strand = places.map((place, index): LensCell => {
397
+ if (copied(place)) return { base: rightward ? top[place]! : PAIR[top[place]!] ?? "N", state: "fresh" };
398
+ const base = primerBase(place);
399
+ return { base, state: base !== "" && joined[index]! ? "paired" : "single" };
400
+ });
401
+ const other = places.map((place, index): LensCell => ({ base: rightward ? PAIR[top[place]!] ?? "N" : top[place]!, state: joined[index]! ? "paired" : "single" }));
402
+ const length = rightward ? top.length - binding.end : binding.start;
403
+ return {
404
+ from, to, joined,
405
+ polymerase: step === "extend" && added < room ? (rightward ? binding.end + added : binding.start - added - 1) - from : null,
406
+ beyond: step === "extend" ? Math.max(0, length - added) : 0,
407
+ upper: rightward ? { label: step === "extend" ? `${primerName}, and the copy` : primerName, cells: strand } : { label: `${templateName}, top strand`, cells: other },
408
+ lower: rightward ? { label: `${templateName}, bottom strand`, cells: other } : { label: step === "extend" ? `${primerName}, and the copy` : primerName, cells: strand },
409
+ };
410
+ }
package/src/pcr-tool.tsx CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { useMemo, useState } from "react";
11
11
  import { useAct, useLab } from "@biolibs/bionet-react";
12
+ import { Glossed } from "@biolibs/glossary-react";
12
13
  import { primerTm } from "./pcr.js";
13
14
  import { pcrRun, pcrTubes, type TubeChoice } from "./run.js";
14
15
 
@@ -88,7 +89,7 @@ export function PcrTool({ instrument = null, onDone }: { instrument?: { id: stri
88
89
  <div className="toolhead">
89
90
  <div>
90
91
  <h2>PCR{instrument === null ? "" : ` · ${instrument.name}`}</h2>
91
- <p className="dim small">Choose tubes from the freezer. The product is worked out from their sequences, and recording the run takes what was used from each.</p>
92
+ <p className="dim small"><Glossed text="PCR copies the stretch of a template that lies between two primers. Choose tubes from the freezer. The product is worked out from their sequences, and recording the run takes what was used from each." /></p>
92
93
  </div>
93
94
  {onDone !== undefined && <button type="button" className="quiet" onClick={onDone}>Back to the lab</button>}
94
95
  </div>
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The working behind what a PCR tool says: each figure, with the steps that give it.
3
+ *
4
+ * Everything the tool says is worked out in the window, from the lab's own sequences. Nothing is
5
+ * looked up and nothing comes back from a server. So it can all be shown: which bases a primer
6
+ * matched, the count behind a melting temperature, the subtraction behind a length. Somebody who
7
+ * doubts a figure can follow it, and somebody learning can see where it comes from.
8
+ *
9
+ * Some of this is exact and some is a rule of thumb, and each piece says which. That a primer's
10
+ * bases match the template's is a fact about two sequences. That it melts at 58 °C is an estimate
11
+ * from a simple rule, and a different rule would give a different figure.
12
+ */
13
+ import type { PartFeature } from "@biolibs/bionet";
14
+ import { primerTm } from "./pcr.js";
15
+ import { SECONDS_PER_KB, strandCounts, type Binding, type PcrProgramme, type PcrReaction } from "./pcr-scene.js";
16
+
17
+ /** One figure, and how it was reached. */
18
+ export interface Working {
19
+ /** What was worked out, in a few words. */
20
+ of: string;
21
+ /** What it came to. */
22
+ comes: string;
23
+ /** `exact` if it follows from the sequences alone; `estimate` if it rests on a rule that could have been another. */
24
+ kind: "exact" | "estimate";
25
+ /** The steps, in order. Each can be checked by hand. */
26
+ steps: string[];
27
+ /** For an estimate, what it rests on and how far to trust it. */
28
+ rests?: string;
29
+ }
30
+
31
+ const count = (value: number): string => value.toLocaleString("en-US");
32
+ const clean = (bases: string): string => bases.replace(/\s+/g, "").toUpperCase();
33
+ const PAIR: Readonly<Record<string, string>> = { A: "T", T: "A", G: "C", C: "G", N: "N" };
34
+
35
+ /**
36
+ * A primer's melting temperature, with the count behind it.
37
+ *
38
+ * @param name - What the primer is called.
39
+ * @param sequence - Its bases.
40
+ * @returns The working, or `null` if that is not a sequence the rule can be applied to.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { tmWorking } from "@biolibs/bionet-tools";
45
+ *
46
+ * tmWorking("fwd", "GGATCACAGTCTACACTG")?.steps;
47
+ * // ["9 of its 18 bases are A or T, and 9 are G or C.", "2 × 9 + 4 × 9 = 54 °C."]
48
+ * ```
49
+ */
50
+ export function tmWorking(name: string, sequence: string): Working | null {
51
+ const bases = clean(sequence);
52
+ const tm = primerTm(bases);
53
+ if (tm === null) return null;
54
+ const weak = [...bases].filter((base) => base === "A" || base === "T" || base === "W").length;
55
+ const strong = [...bases].filter((base) => base === "G" || base === "C" || base === "S").length;
56
+ return {
57
+ of: `${name}'s melting temperature`, comes: `about ${Math.round(tm)} °C`, kind: "estimate",
58
+ steps: [
59
+ `${count(weak)} of its ${count(bases.length)} bases are A or T, and ${count(strong)} are G or C.`,
60
+ `2 × ${weak} + 4 × ${strong} = ${2 * weak + 4 * strong} °C.`,
61
+ ],
62
+ rests: "The Wallace rule: an A·T pair holds with two bonds and a G·C pair with three, so each is given 2 °C or 4 °C. It ignores salt, how much primer there is and which bases are neighbours, and is rough past about 20 bases. It is good for seeing that two primers are near each other.",
63
+ };
64
+ }
65
+
66
+ /** One place along a primer laid against the template: the primer's base, the base it faces, and whether they pair. */
67
+ export interface FacedBase {
68
+ /** The primer's base here. */
69
+ primer: string;
70
+ /** The base of the strand it binds that faces it, or `""` where the template has run out. */
71
+ faces: string;
72
+ /** Whether the two pair: A with T, G with C. */
73
+ pairs: boolean;
74
+ /** Whether this base is one of those at the 3′ end that must pair for the primer to bind. */
75
+ needed: boolean;
76
+ }
77
+
78
+ /** A primer laid against the strand it binds, base by base. */
79
+ export interface BindingWorking extends Working {
80
+ /** The primer 5′ to 3′, each base with the one it faces. */
81
+ faced: FacedBase[];
82
+ /** Which strand it binds. */
83
+ strand: "top" | "bottom";
84
+ /** Where on the template it sits, counting bases from 1 as a sequence file does. */
85
+ from: number;
86
+ to: number;
87
+ }
88
+
89
+ /**
90
+ * A primer laid against the strand it binds, to show that it does.
91
+ *
92
+ * @param template - The template's top strand.
93
+ * @param primer - What the primer is called, and its bases 5′ to 3′.
94
+ * @param binding - Where it binds, from `primerBinding`.
95
+ * @param least - How many bases at its 3′ end must pair.
96
+ * @returns Each of the primer's bases with the base it faces, and what that shows.
97
+ */
98
+ export function bindingWorking(template: string, primer: { name: string; sequence: string }, binding: Binding, least: number): BindingWorking {
99
+ const top = clean(template);
100
+ const bases = clean(primer.sequence);
101
+ const bound = bases.length - binding.tail;
102
+ // A primer that reads as the top strand binds the bottom one, and the other way about. Walking the
103
+ // primer 5′ to 3′ walks the template rightwards for the first and leftwards for the second.
104
+ const faced = [...bases].map((base, at): FacedBase => {
105
+ const along = at - binding.tail;
106
+ const place = binding.reads === "top" ? binding.start + along : binding.end - 1 - along;
107
+ const there = along < 0 || place < 0 || place >= top.length ? "" : top[place]!;
108
+ const faces = there === "" ? "" : binding.reads === "top" ? PAIR[there] ?? "N" : there;
109
+ return { primer: base, faces, pairs: faces !== "" && PAIR[base] === faces, needed: at >= bases.length - least };
110
+ });
111
+ const paired = faced.filter((one) => one.pairs).length;
112
+ const end = faced.slice(-least);
113
+ // Every place the 3′ end could sit, on either strand: binding in one place only is part of what is claimed.
114
+ const flipped = [...bases].reverse().map((base) => PAIR[base] ?? "N").join("");
115
+ const sites = (needle: string): number => { let found = 0; for (let at = top.indexOf(needle); at !== -1; at = top.indexOf(needle, at + 1)) found++; return found; };
116
+ const places = sites(bases.slice(-least)) + sites(flipped.slice(0, least));
117
+ return {
118
+ of: `where ${primer.name} binds`, kind: "exact", faced, strand: binding.reads === "top" ? "bottom" : "top",
119
+ from: binding.start + 1, to: binding.end,
120
+ comes: `bases ${count(binding.start + 1)} to ${count(binding.end)}, on the ${binding.reads === "top" ? "bottom" : "top"} strand`,
121
+ steps: [
122
+ `The last ${least} bases at its 3′ end ${end.every((one) => one.pairs) ? "each pair with the base they face" : "do not all pair"}. That is what the polymerase needs to start from.`,
123
+ `${count(paired)} of its ${count(bases.length)} bases pair in all${binding.tail === 0 ? "." : `. The first ${binding.tail} at its 5′ end do not: they are a tail, and are carried onto the product.`}`,
124
+ `Those ${least} bases are found in ${places === 1 ? "one place only" : `${places} places`} on the template, counting both strands.`,
125
+ `It has the ${binding.reads} strand's sequence, so it binds the ${binding.reads === "top" ? "bottom" : "top"} strand and is copied ${binding.reads === "top" ? "rightwards" : "leftwards"}.`,
126
+ ],
127
+ };
128
+ }
129
+
130
+ /**
131
+ * How long the product is, as arithmetic on where the primers bind.
132
+ *
133
+ * This is worked out separately from the engine that makes the product, so the two can be compared.
134
+ *
135
+ * @param top - Where the primer that reads as the top strand binds.
136
+ * @param bottom - Where the other binds.
137
+ * @param template - How long the template is, and whether it is a circle.
138
+ * @param made - How long the engine's product is, to compare with.
139
+ * @returns The working.
140
+ */
141
+ export function lengthWorking(top: Binding, bottom: Binding, template: { length: number; circular: boolean }, made?: number): Working {
142
+ const straight = bottom.end > top.start;
143
+ const copied = straight ? bottom.end - top.start : template.length - top.start + bottom.end;
144
+ const total = top.tail + copied + bottom.tail;
145
+ const steps = [
146
+ straight
147
+ ? `The copy runs from base ${count(top.start + 1)}, where one primer starts, to base ${count(bottom.end)}, where the other ends: ${count(bottom.end)} − ${count(top.start + 1)} + 1 = ${count(copied)}.`
148
+ : `The template is a circle and the copy runs through its origin: from base ${count(top.start + 1)} to the end is ${count(template.length - top.start)}, and from the start to base ${count(bottom.end)} is ${count(bottom.end)}, so ${count(copied)}.`,
149
+ ...(top.tail + bottom.tail === 0 ? [] : [`The primers' tails are added at the ends: ${count(copied)} + ${top.tail} + ${bottom.tail} = ${count(total)}.`]),
150
+ ...(made === undefined ? [] : [made === total ? `The engine that builds the product, working it out its own way, also gives ${count(made)}.` : `The engine that builds the product gives ${count(made)}, which does not agree. Trust neither until that is understood.`]),
151
+ ];
152
+ return { of: "the product's length", comes: `${count(total)} bp`, kind: "exact", steps };
153
+ }
154
+
155
+ /**
156
+ * Where the suggested programme's two figures come from.
157
+ *
158
+ * @param reaction - The product's length and the primers' melting temperatures.
159
+ * @param programme - The programme suggested for it.
160
+ * @returns The working for the annealing temperature and for the extension time.
161
+ */
162
+ export function programmeWorking(reaction: PcrReaction, programme: PcrProgramme): Working[] {
163
+ const sorted = [...reaction.primers].sort((a, b) => a.tm - b.tm);
164
+ const coolest = sorted[0];
165
+ const [, anneal, extend] = programme.steps;
166
+ const wanted = (reaction.length / 1000) * SECONDS_PER_KB;
167
+ const under = coolest === undefined ? null : Math.round(coolest.tm) - 5;
168
+ return [
169
+ ...(coolest === undefined || under === null ? [] : [{
170
+ of: "the annealing temperature suggested", comes: `${anneal.celsius} °C`, kind: "estimate" as const,
171
+ steps: [
172
+ `The cooler primer is ${coolest.name}, at about ${Math.round(coolest.tm)} °C.`,
173
+ `Five degrees under it: ${Math.round(coolest.tm)} − 5 = ${under} °C${under === anneal.celsius ? "." : `, kept between 45 and 72, so ${anneal.celsius} °C.`}`,
174
+ ],
175
+ rests: "Five under the cooler primer is a convention. It rests on the melting temperatures, which are estimates themselves, so it is where to start and not where to stop.",
176
+ }]),
177
+ {
178
+ of: "the extension time suggested", comes: `${extend.seconds} s`, kind: "estimate" as const,
179
+ steps: [
180
+ `${count(reaction.length)} bases at a minute for every thousand: ${count(reaction.length)} ÷ 1,000 × ${SECONDS_PER_KB} = ${Math.round(wanted * 10) / 10} s.`,
181
+ `Rounded up to the next 5 s, and never under 15: ${extend.seconds} s.`,
182
+ ],
183
+ rests: "A minute for every thousand bases suits an ordinary polymerase. A fast one needs a quarter of that, and its maker says so.",
184
+ },
185
+ ];
186
+ }
187
+
188
+ /**
189
+ * How many strands a tube holds after each cycle, as a table that can be followed down.
190
+ *
191
+ * @param cycles - How many cycles the programme runs.
192
+ * @returns The working, and a row for each of the first cycles and for the last.
193
+ */
194
+ export function countsWorking(cycles: number): Working & { rows: { cycle: number; template: number; long: number; product: number; total: number }[] } {
195
+ const last = Math.max(0, Math.floor(cycles));
196
+ const shown = [...new Set([0, 1, 2, 3, 4, 5, last].filter((one) => one <= last))];
197
+ const rows = shown.map((cycle) => { const at = strandCounts(cycle); return { cycle, ...at, total: at.template + at.long + at.product }; });
198
+ const end = strandCounts(last);
199
+ return {
200
+ of: `how many strands there are after ${last} cycles`, comes: `${count(end.product)} of the product`, kind: "estimate", rows,
201
+ steps: [
202
+ "Every cycle copies every strand once, so the number of strands doubles: 2, 4, 8, and after n cycles 2 × 2ⁿ.",
203
+ "The template's two strands are only ever copied, never made: 2.",
204
+ "Each cycle copies those two into two strands that start at a primer and run on too far: 2 × n.",
205
+ `Everything else is the product: 2 × 2ⁿ − 2n − 2. After ${last} cycles, ${count(2 * 2 ** last)} − ${count(2 * last)} − 2 = ${count(end.product)}.`,
206
+ ],
207
+ rests: "The counting is exact for a tube in which every strand is copied every cycle. A real one falls behind as primers and nucleotides run low, usually after 25 to 30 cycles, so the real figure is lower.",
208
+ };
209
+ }
210
+
211
+ /**
212
+ * How each feature on the product was carried from the template, one line for each.
213
+ *
214
+ * @param features - What is marked on the template.
215
+ * @param from - Where the stretch copied starts.
216
+ * @param to - Where it stops.
217
+ * @param shift - How many bases precede it on the product: the forward primer's tail.
218
+ * @returns A line for each feature that touches the stretch, with the subtraction that moved it.
219
+ */
220
+ export function carriedWorking(features: readonly PartFeature[], from: number, to: number, shift = 0): string[] {
221
+ return features.flatMap((feature) => feature.parts.flatMap((piece) => {
222
+ const [start, end] = [Math.max(piece.start, from), Math.min(piece.end, to)];
223
+ if (end <= start) return [];
224
+ const cut = start !== piece.start || end !== piece.end;
225
+ return [`${feature.label}: ${count(piece.start + 1)}..${count(piece.end)} on the template${cut ? `, of which ${count(start + 1)}..${count(end)} is copied` : ""}. `
226
+ + `Less the ${count(from)} bases before the copy${shift === 0 ? "" : ` and plus the tail's ${shift}`}: ${count(start - from + shift + 1)}..${count(end - from + shift)} on the product.`];
227
+ }));
228
+ }