@biolibs/bionet-tools 0.1.6 → 0.1.9

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 (83) hide show
  1. package/dist/assembly-bench.d.ts +62 -0
  2. package/dist/assembly-bench.d.ts.map +1 -0
  3. package/dist/assembly-bench.js +114 -0
  4. package/dist/assembly-bench.js.map +1 -0
  5. package/dist/assembly-design.d.ts +119 -0
  6. package/dist/assembly-design.d.ts.map +1 -0
  7. package/dist/assembly-design.js +157 -0
  8. package/dist/assembly-design.js.map +1 -0
  9. package/dist/codon-bench.d.ts +51 -0
  10. package/dist/codon-bench.d.ts.map +1 -0
  11. package/dist/codon-bench.js +93 -0
  12. package/dist/codon-bench.js.map +1 -0
  13. package/dist/codons.d.ts +126 -0
  14. package/dist/codons.d.ts.map +1 -0
  15. package/dist/codons.js +287 -0
  16. package/dist/codons.js.map +1 -0
  17. package/dist/digest-bench.d.ts.map +1 -1
  18. package/dist/digest-bench.js +11 -2
  19. package/dist/digest-bench.js.map +1 -1
  20. package/dist/digest.d.ts +14 -0
  21. package/dist/digest.d.ts.map +1 -1
  22. package/dist/digest.js +18 -0
  23. package/dist/digest.js.map +1 -1
  24. package/dist/index.d.ts +16 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +16 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/ligate-bench.d.ts.map +1 -1
  29. package/dist/ligate-bench.js +10 -2
  30. package/dist/ligate-bench.js.map +1 -1
  31. package/dist/pcr-bench.d.ts.map +1 -1
  32. package/dist/pcr-bench.js +13 -2
  33. package/dist/pcr-bench.js.map +1 -1
  34. package/dist/pcr-tool.js +1 -1
  35. package/dist/pcr-tool.js.map +1 -1
  36. package/dist/plans.d.ts +66 -0
  37. package/dist/plans.d.ts.map +1 -0
  38. package/dist/plans.js +106 -0
  39. package/dist/plans.js.map +1 -0
  40. package/dist/primer-bench.js +1 -1
  41. package/dist/primer-bench.js.map +1 -1
  42. package/dist/protein.d.ts +106 -0
  43. package/dist/protein.d.ts.map +1 -0
  44. package/dist/protein.js +158 -0
  45. package/dist/protein.js.map +1 -0
  46. package/dist/run.d.ts +12 -0
  47. package/dist/run.d.ts.map +1 -1
  48. package/dist/run.js +19 -4
  49. package/dist/run.js.map +1 -1
  50. package/dist/sequences-tool.js +1 -1
  51. package/dist/sequences-tool.js.map +1 -1
  52. package/dist/tools.d.ts +1 -1
  53. package/dist/tools.d.ts.map +1 -1
  54. package/dist/tools.js +7 -3
  55. package/dist/tools.js.map +1 -1
  56. package/dist/verify-bench.d.ts +48 -0
  57. package/dist/verify-bench.d.ts.map +1 -0
  58. package/dist/verify-bench.js +77 -0
  59. package/dist/verify-bench.js.map +1 -0
  60. package/dist/verify.d.ts +138 -0
  61. package/dist/verify.d.ts.map +1 -0
  62. package/dist/verify.js +263 -0
  63. package/dist/verify.js.map +1 -0
  64. package/package.json +5 -3
  65. package/src/assembly-bench.tsx +232 -0
  66. package/src/assembly-design.ts +219 -0
  67. package/src/codon-bench.tsx +189 -0
  68. package/src/codons.ts +339 -0
  69. package/src/digest-bench.tsx +10 -1
  70. package/src/digest.ts +19 -0
  71. package/src/index.ts +16 -0
  72. package/src/ligate-bench.tsx +9 -1
  73. package/src/pcr-bench.tsx +11 -1
  74. package/src/pcr-tool.tsx +1 -1
  75. package/src/plans.tsx +137 -0
  76. package/src/primer-bench.tsx +1 -1
  77. package/src/protein.ts +204 -0
  78. package/src/run.ts +20 -4
  79. package/src/sequences-tool.tsx +1 -1
  80. package/src/tools.tsx +7 -3
  81. package/src/verify-bench.tsx +161 -0
  82. package/src/verify.ts +310 -0
  83. package/tools.css +18 -0
package/src/verify.ts ADDED
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Checking that what came back is what was designed.
3
+ *
4
+ * Everything else in this package proposes. This is the one that confirms: a sequencing read
5
+ * against the construct it was supposed to be, difference by difference, with what each difference
6
+ * does to the protein. It is the check that stands between a plasmid map and a plasmid.
7
+ *
8
+ * Three things it does that a plain alignment does not.
9
+ *
10
+ * - **It tries both strands.** A read comes off whichever end the primer sat at, and a read that is
11
+ * simply the other way round is not a construct that is wrong.
12
+ * - **It says where on the design**, not where in the alignment, so a difference can be looked up on
13
+ * the map and found.
14
+ * - **It says what the difference costs.** A changed base that leaves the amino acid alone is a
15
+ * nuisance; one that makes a stop codon is a dead construct; one base missing is a frameshift and
16
+ * everything after it is wrong. Those are not the same finding and are not reported as if they were.
17
+ *
18
+ * One thing it cannot do, and does not pretend to: a base gained or lost inside a run of the same
19
+ * base has no single place it could have happened, since deleting any of them gives the same read.
20
+ * The earliest is reported. What was gained or lost, and what it costs, are right either way; only
21
+ * the position inside the run is a choice the alignment made.
22
+ */
23
+ import { PairwiseAligner } from "@biolibs/align";
24
+ import type { PartFeature } from "@biolibs/bionet";
25
+ import { translate } from "@biolibs/seq";
26
+ import { CODON } from "./codons.js";
27
+ import type { Working } from "./pcr-working.js";
28
+
29
+ /** What kind of difference it is. */
30
+ export type DifferenceKind = "substitution" | "insertion" | "deletion";
31
+
32
+ /** What a difference does to a protein. */
33
+ export type ProteinEffect =
34
+ /** The amino acid is unchanged. */
35
+ | { kind: "silent"; codon: number; aminoAcid: string }
36
+ /** One amino acid becomes another. */
37
+ | { kind: "missense"; codon: number; from: string; to: string }
38
+ /** It makes a stop codon, so everything after it is lost. */
39
+ | { kind: "nonsense"; codon: number; from: string }
40
+ /** Bases are gained or lost in a multiple of three: amino acids come or go, the rest reads on. */
41
+ | { kind: "in frame"; codon: number; by: number }
42
+ /** Bases are gained or lost out of step, so everything after is read wrong. */
43
+ | { kind: "frameshift"; codon: number; by: number }
44
+ /** It falls in a coding sequence this does not work out, such as one in several pieces. */
45
+ | { kind: "not worked out"; codon: number; why: string };
46
+
47
+ /** One place the read differs from the design. */
48
+ export interface Difference {
49
+ /** Where on the design, counting from 1. For an insertion, the base it comes after. */
50
+ at: number;
51
+ kind: DifferenceKind;
52
+ /** What the design has there. Empty for an insertion. */
53
+ was: string;
54
+ /** What the read has there. Empty for a deletion. */
55
+ now: string;
56
+ /** What is marked on the design at that place. */
57
+ inside: { label: string; type: string }[];
58
+ /** What it does to the protein, for a difference in a coding sequence. */
59
+ protein: ProteinEffect | null;
60
+ }
61
+
62
+ /** What came of checking a read against a design. */
63
+ export interface Verification {
64
+ /** Whether the read had to be turned round to line up, which is not a fault. */
65
+ reversed: boolean;
66
+ /** The stretch of the design the read covers, counting from 1, or `null` if it lines up nowhere. */
67
+ covers: { from: number; to: number; bases: number } | null;
68
+ /** How much of the design that stretch is, from 0 to 1. */
69
+ covered: number;
70
+ /** How much of the covered stretch matches, from 0 to 1. */
71
+ identity: number;
72
+ /** Every place they differ, in order along the design. */
73
+ differences: Difference[];
74
+ /** Whether the read is the design over everything it covers. */
75
+ matches: boolean;
76
+ /** Whether anything found would change a protein. */
77
+ changesProtein: boolean;
78
+ /** Anything a careful person would look at. */
79
+ warnings: string[];
80
+ /** Why it could not be checked, or `null`. */
81
+ problem: string | null;
82
+ }
83
+
84
+ const clean = (bases: string): string => bases.replace(/\s+/g, "").toUpperCase();
85
+ const PAIR: Readonly<Record<string, string>> = { A: "T", T: "A", G: "C", C: "G", N: "N" };
86
+ const flip = (bases: string): string => [...bases].reverse().map((one) => PAIR[one] ?? "N").join("");
87
+
88
+ /** An aligner that finds where a read sits on a design, rather than forcing the two end to end. */
89
+ function reader(): PairwiseAligner {
90
+ const aligner = new PairwiseAligner();
91
+ aligner.mode = "local";
92
+ aligner.match = 2;
93
+ aligner.mismatch = -3;
94
+ aligner.openGapScore = -5;
95
+ aligner.extendGapScore = -2;
96
+ return aligner;
97
+ }
98
+
99
+ /** The coding sequences a difference can be read against: one piece, so the frame is plain. */
100
+ const codingAt = (features: readonly PartFeature[], at: number): PartFeature[] =>
101
+ features.filter((one) => /^cds$/i.test(one.type) && one.parts.some((piece) => at >= piece.start && at < piece.end));
102
+
103
+ /**
104
+ * What one changed base does to the protein of a coding sequence.
105
+ *
106
+ * @param design - The design's bases.
107
+ * @param cds - The coding sequence it falls in.
108
+ * @param at - Where the change is, counting from 0.
109
+ * @param now - What the read has there.
110
+ * @returns What it does, said as one of the kinds.
111
+ */
112
+ function effectOf(design: string, cds: PartFeature, at: number, now: string): ProteinEffect {
113
+ const piece = cds.parts[0]!;
114
+ if (cds.parts.length > 1) return { kind: "not worked out", codon: 0, why: `${cds.label} is marked in ${cds.parts.length} pieces, so the reading frame across it is not worked out here` };
115
+ const bases = design.slice(piece.start, piece.end);
116
+ const forward = cds.strand !== -1;
117
+ // On the other strand the coding sequence runs the other way, and so do its codons.
118
+ const offset = forward ? at - piece.start : piece.end - 1 - at;
119
+ const coding = forward ? bases : flip(bases);
120
+ const codon = Math.floor(offset / CODON);
121
+ const start = codon * CODON;
122
+ const was = coding.slice(start, start + CODON);
123
+ if (was.length < CODON) return { kind: "not worked out", codon: codon + 1, why: `${cds.label} does not end on a whole codon` };
124
+ const changed = `${was.slice(0, offset - start)}${forward ? now : (PAIR[now] ?? "N")}${was.slice(offset - start + 1)}`;
125
+ const before = String(translate(was));
126
+ const after = String(translate(changed));
127
+ if (before === after) return { kind: "silent", codon: codon + 1, aminoAcid: before };
128
+ if (after === "*") return { kind: "nonsense", codon: codon + 1, from: before };
129
+ return { kind: "missense", codon: codon + 1, from: before, to: after };
130
+ }
131
+
132
+ /**
133
+ * Check a sequencing read against the design it was supposed to be.
134
+ *
135
+ * @param design - The construct as designed: its bases and what is marked on it.
136
+ * @param read - The read, as bases. Either strand.
137
+ * @param options - `least` is how much of the read has to line up for the check to mean anything,
138
+ * as a fraction, 0.5 unless said.
139
+ * @returns What matched, what did not, and what each difference costs.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * import { checkRead } from "@biolibs/bionet-tools";
144
+ *
145
+ * const checked = checkRead({ sequence: designed, features }, fromTheFacility);
146
+ * checked.matches; // whether it is what was designed, over what the read covers
147
+ * checked.differences; // each one, where on the design, and what it does to the protein
148
+ * ```
149
+ */
150
+ export function checkRead(design: { sequence: string; features?: readonly PartFeature[] }, read: string,
151
+ options: { least?: number } = {}): Verification {
152
+ const nothing = (problem: string): Verification =>
153
+ ({ reversed: false, covers: null, covered: 0, identity: 0, differences: [], matches: false, changesProtein: false, warnings: [], problem });
154
+ const bases = clean(design.sequence);
155
+ const given = clean(read);
156
+ if (bases.length === 0) return nothing("There is nothing to check against.");
157
+ if (given.length === 0) return nothing("There is no read to check.");
158
+ if (!/^[ACGTN]+$/.test(bases)) return nothing("The design has bases that are not A, C, G, T or N.");
159
+ if (!/^[ACGTN]+$/.test(given)) return nothing("The read has bases that are not A, C, G, T or N. A base call that could not be made is N.");
160
+
161
+ const aligner = reader();
162
+ // A read comes off whichever end its primer sat at, so both ways round are tried and the better kept.
163
+ const turned = flip(given);
164
+ const forward = aligner.score(bases, given);
165
+ const backward = aligner.score(bases, turned);
166
+ const reversed = backward > forward;
167
+ const query = reversed ? turned : given;
168
+ const [best] = aligner.align(bases, query);
169
+ if (best === undefined) return nothing("The read does not line up against the design at all.");
170
+ const [onDesign, onRead] = best.indices as unknown as [number[], number[]];
171
+
172
+ const warnings: string[] = [];
173
+ const differences: Difference[] = [];
174
+ const features = design.features ?? [];
175
+ /** Gather a run of gaps into one difference rather than reporting each base of it. */
176
+ let run: { kind: DifferenceKind; at: number; was: string; now: string } | null = null;
177
+ const settle = (): void => {
178
+ if (run === null) return;
179
+ const at = run.at;
180
+ const inside = features.filter((one) => one.parts.some((piece) => at - 1 >= piece.start && at - 1 < piece.end)).map((one) => ({ label: one.label, type: one.type }));
181
+ const cds = codingAt(features, at - 1)[0];
182
+ const by = run.kind === "insertion" ? run.now.length : -run.was.length;
183
+ const protein: ProteinEffect | null = cds === undefined ? null
184
+ : cds.parts.length > 1 ? { kind: "not worked out", codon: 0, why: `${cds.label} is marked in ${cds.parts.length} pieces, so the reading frame across it is not worked out here` }
185
+ : { kind: Math.abs(by) % CODON === 0 ? "in frame" : "frameshift", codon: Math.floor((at - 1 - cds.parts[0]!.start) / CODON) + 1, by };
186
+ differences.push({ at, kind: run.kind, was: run.was, now: run.now, inside, protein });
187
+ run = null;
188
+ };
189
+
190
+ let matched = 0;
191
+ let from = Number.POSITIVE_INFINITY;
192
+ let to = 0;
193
+ for (let column = 0; column < onDesign.length; column++) {
194
+ const d = onDesign[column]!;
195
+ const q = onRead[column]!;
196
+ if (d >= 0) { from = Math.min(from, d + 1); to = Math.max(to, d + 1); }
197
+ if (d >= 0 && q >= 0) {
198
+ settle();
199
+ if (bases[d] === query[q]) { matched += 1; continue; }
200
+ const at = d + 1;
201
+ const inside = features.filter((one) => one.parts.some((piece) => d >= piece.start && d < piece.end)).map((one) => ({ label: one.label, type: one.type }));
202
+ const cds = codingAt(features, d)[0];
203
+ differences.push({ at, kind: "substitution", was: bases[d]!, now: query[q]!, inside, protein: cds === undefined ? null : effectOf(bases, cds, d, query[q]!) });
204
+ continue;
205
+ }
206
+ // A gap on one side or the other: bases the read is missing, or bases it has over.
207
+ const kind: DifferenceKind = d < 0 ? "insertion" : "deletion";
208
+ const at = d < 0 ? Math.max(1, to) : d + 1;
209
+ if (run === null || run.kind !== kind) { settle(); run = { kind, at, was: "", now: "" }; }
210
+ if (d < 0) run.now += query[q]!;
211
+ else run.was += bases[d]!;
212
+ }
213
+ settle();
214
+
215
+ const covers = to === 0 ? null : { from, to, bases: to - from + 1 };
216
+ const span = covers === null ? 0 : covers.bases;
217
+ const identity = span === 0 ? 0 : matched / span;
218
+ const least = options.least ?? 0.5;
219
+ if (given.length > 0 && span / given.length < least) {
220
+ warnings.push(`Only ${Math.round((span / given.length) * 100)}% of the read lines up against the design, so this says little. It may be a read of something else.`);
221
+ }
222
+ if (given.includes("N")) warnings.push(`The read has ${[...given].filter((one) => one === "N").length} bases that could not be called, which are not counted as differences.`);
223
+ if (covers !== null && covers.bases < bases.length) {
224
+ warnings.push(`The read covers ${covers.from}–${covers.to} of ${bases.length} bases. The rest of the design is unchecked.`);
225
+ }
226
+ return {
227
+ reversed, covers, covered: covers === null ? 0 : covers.bases / bases.length, identity,
228
+ differences, matches: differences.length === 0 && covers !== null,
229
+ changesProtein: differences.some((one) => one.protein !== null && one.protein.kind !== "silent"),
230
+ warnings, problem: null,
231
+ };
232
+ }
233
+
234
+ /** A difference, said in a line. */
235
+ export function saysDifference(one: Difference): string {
236
+ const where = `at ${one.at.toLocaleString("en-US")}`;
237
+ const what = one.kind === "substitution" ? `${one.was} became ${one.now}`
238
+ : one.kind === "deletion" ? `${one.was.length} ${one.was.length === 1 ? "base" : "bases"} missing (${one.was})`
239
+ : `${one.now.length} ${one.now.length === 1 ? "base" : "bases"} over (${one.now})`;
240
+ const effect = one.protein === null ? ""
241
+ : one.protein.kind === "silent" ? `, which leaves ${one.protein.aminoAcid} at codon ${one.protein.codon} alone`
242
+ : one.protein.kind === "missense" ? `, which makes codon ${one.protein.codon} ${one.protein.from} into ${one.protein.to}`
243
+ : one.protein.kind === "nonsense" ? `, which makes codon ${one.protein.codon} a stop, so everything after it is lost`
244
+ : one.protein.kind === "frameshift" ? `, which shifts the frame from codon ${one.protein.codon} on, so the rest is read wrong`
245
+ : one.protein.kind === "in frame" ? `, which adds or removes whole codons from codon ${one.protein.codon}` : `, ${one.protein.why}`;
246
+ return `${where}: ${what}${effect}`;
247
+ }
248
+
249
+ /**
250
+ * The working behind a check: what was compared, and what was found.
251
+ *
252
+ * @param checked - What came of checking.
253
+ * @param design - How long the design is, for saying how much was covered.
254
+ * @returns One working for the comparison and one for what it costs.
255
+ */
256
+ export function verifyWorking(checked: Verification, design: { sequence: string }): Working[] {
257
+ if (checked.problem !== null) return [];
258
+ const count = (value: number): string => value.toLocaleString("en-US");
259
+ const span = checked.covers;
260
+ return [
261
+ {
262
+ of: "the comparison",
263
+ comes: span === null ? "the read lines up nowhere on the design" : `${Math.round(checked.identity * 1000) / 10}% the same over ${count(span.bases)} bases`,
264
+ kind: "exact",
265
+ steps: [
266
+ `the design is ${count(clean(design.sequence).length)} bases`,
267
+ ...(checked.reversed ? ["the read was turned round to line up, which is only which end its primer sat at"] : ["the read lines up as it was given"]),
268
+ ...(span === null ? [] : [`it covers ${count(span.from)}–${count(span.to)}, which is ${Math.round(checked.covered * 100)}% of the design`]),
269
+ `${count(checked.differences.length)} ${checked.differences.length === 1 ? "place differs" : "places differ"}`,
270
+ "what is outside that stretch was not read and is not checked",
271
+ ],
272
+ },
273
+ {
274
+ of: "what it costs",
275
+ comes: checked.matches ? "nothing: it is the design over everything the read covers"
276
+ : checked.changesProtein ? "a protein is changed" : "the differences leave the proteins alone",
277
+ kind: "exact",
278
+ steps: checked.differences.length === 0
279
+ ? ["every base the read covers is the base the design has"]
280
+ : checked.differences.slice(0, 8).map((one) => saysDifference(one)).concat(checked.differences.length > 8 ? [`and ${count(checked.differences.length - 8)} more`] : []),
281
+ },
282
+ ];
283
+ }
284
+
285
+ /**
286
+ * A check as a run the lab would record.
287
+ *
288
+ * It uses up some of the tube that was sent and makes nothing. Whether it worked is whether the
289
+ * read is the design, which is what the check says, so the outcome is not a separate judgement.
290
+ *
291
+ * @param checked - What came of checking.
292
+ * @param choice - The tube that was sequenced, how much went, and what to say about it.
293
+ * @returns What to hand to the lab's `recordRun`, or `null` if there is nothing to record.
294
+ */
295
+ export function verifyRun(checked: Verification, choice: { tube: string; used?: number; primer?: string | null; note?: string | null }): Record<string, unknown> | null {
296
+ if (checked.problem !== null || checked.covers === null) return null;
297
+ return {
298
+ kind: "sequencing", instrument: null,
299
+ inputs: [{ item: choice.tube, amount: Math.max(0, Math.round(choice.used ?? 1)), role: "sequenced" }],
300
+ outputs: [],
301
+ settings: {
302
+ covered: `${checked.covers.from}-${checked.covers.to}`,
303
+ identity: Math.round(checked.identity * 1000) / 10,
304
+ differences: checked.differences.length,
305
+ ...(choice.primer === undefined || choice.primer === null || choice.primer.trim() === "" ? {} : { primer: choice.primer.trim() }),
306
+ },
307
+ outcome: checked.matches ? "worked" : "failed",
308
+ note: choice.note ?? (checked.matches ? null : checked.differences.slice(0, 3).map(saysDifference).join("; ")),
309
+ };
310
+ }
package/tools.css CHANGED
@@ -149,3 +149,21 @@
149
149
  .bionet .faced.paired .row { flex-wrap: nowrap; gap: 0; width: max-content }
150
150
  .bionet .faced.paired + .faced.paired { margin-top: .9rem }
151
151
  .bionet .primers .strip { max-width: 46rem }
152
+ .bionet .proposed .plan { padding: .55rem .7rem; margin: .5rem 0; border: 1px solid var(--bionet-rule); border-radius: 8px }
153
+ .bionet .proposed .plan.now { border-color: var(--bionet-good) }
154
+ .bionet .proposed .plan p { margin: 0 0 .35rem }
155
+ .bionet .proposed .plan .why { color: var(--bionet-dim); font-style: italic }
156
+ .bionet .proposed .attention { color: var(--bionet-attention) }
157
+ /* Building a ring: the pieces in the order they go round it. */
158
+ .bionet .assembly { container-type: inline-size }
159
+ .bionet .assembly .pieces { margin: .6rem 0 0; padding-left: 1.3rem; display: grid; gap: .35rem }
160
+ .bionet .assembly .pieces li { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem }
161
+ .bionet .assembly .pieces li > span:first-child { font-weight: 600 }
162
+ .bionet .assembly .attention { color: var(--bionet-attention) }
163
+ .bionet .assembly code.wrap .dim { opacity: .55 }
164
+ /* Checking a construct: what was read, and what it costs. */
165
+ .bionet .verify { container-type: inline-size }
166
+ .bionet .verify textarea { font: 12px/1.5 ui-monospace, "SF Mono", Menlo, monospace; width: 100%; resize: vertical;
167
+ color: var(--bionet-ink); padding: .4rem .5rem; border: 1px solid var(--bionet-rule); border-radius: 6px; background: var(--bionet-field, var(--bionet-ground)) }
168
+ .bionet .verify .attention { color: var(--bionet-attention) }
169
+ .bionet .verify .checks .stop { color: var(--bionet-attention) }