@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/plans.tsx ADDED
@@ -0,0 +1,137 @@
1
+ "use client";
2
+
3
+ /**
4
+ * Runs that have been proposed, at the tool that would carry them out.
5
+ *
6
+ * A plan is a run nobody has done: somebody, or something with no hands, saying what they would do
7
+ * and what they expect of it. It is shown where it would be done, with who proposed it and why, and
8
+ * a person there can set the bench up as it says, look at the working their own tools give for it,
9
+ * and then do it or not. Nothing is taken on trust: the plan says what it expects, and the tool says
10
+ * what it would make.
11
+ *
12
+ * A run is said to carry a plan out when it is of the same kind and uses exactly the tubes the plan
13
+ * names. That is decided from what is set up, not from a button pressed earlier, so a bench that is
14
+ * changed after being set up from a plan stops claiming to be that plan.
15
+ */
16
+ import { useState, type ReactNode } from "react";
17
+ import { useAct, useLab } from "@biolibs/bionet-react";
18
+
19
+ /** One proposed run, as the lab holds it. */
20
+ export type Plan = NonNullable<NonNullable<ReturnType<typeof useLab>>["lab"]>["plans"][number];
21
+
22
+ /** As much of a lab as it takes to say which plan a run carries out. */
23
+ export interface PlanLab { plans: readonly Plan[] }
24
+
25
+ /**
26
+ * A run as a tool would record it, turned into the same run proposed.
27
+ *
28
+ * @param run - What would be handed to `recordRun`.
29
+ * @param note - Why it is proposed.
30
+ * @returns What to hand to `planRun`: the same tubes and settings, and what came out as what is expected.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { pcrRun, toPlan } from "@biolibs/bionet-tools";
35
+ *
36
+ * const run = pcrRun(lab, { template, forward, reverse });
37
+ * if (run.worked !== null) await act("planRun", toPlan(run.worked, "to check the insert is there"));
38
+ * ```
39
+ */
40
+ export function toPlan(run: Record<string, unknown>, note?: string): Record<string, unknown> {
41
+ const outputs = (Array.isArray(run["outputs"]) ? run["outputs"] : []) as { sequence: string; circular?: boolean; name: string; ends?: { left: number; right: number } }[];
42
+ const said = note?.trim() ?? "";
43
+ return {
44
+ kind: run["kind"], instrument: run["instrument"] ?? null, inputs: run["inputs"], settings: run["settings"] ?? {},
45
+ expects: outputs.map((one) => ({ sequence: one.sequence, name: one.name, ...(one.circular === true ? { circular: true } : {}), ...(one.ends === undefined ? {} : { ends: one.ends }) })),
46
+ note: said === "" ? (typeof run["note"] === "string" ? run["note"] : null) : said,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The open plan that a run, as it is set up, would carry out.
52
+ *
53
+ * @param lab - The lab.
54
+ * @param run - What would be handed to `recordRun`, or `null` if nothing is set up.
55
+ * @returns The plan of the same kind that names exactly the tubes the run uses and, where the plan
56
+ * names enzymes, the same ones; `undefined` if there is none.
57
+ */
58
+ export function planCarried(lab: PlanLab, run: Record<string, unknown> | null): Plan | undefined {
59
+ if (run === null) return undefined;
60
+ const used = ((Array.isArray(run["inputs"]) ? run["inputs"] : []) as { item?: string }[]).map((one) => one.item).sort().join(" ");
61
+ const enzymes = (run["settings"] as Record<string, unknown> | undefined)?.["enzymes"];
62
+ return lab.plans.find((plan) => plan.settled === null && plan.kind === run["kind"] && plan.inputs.every((one) => one.item !== undefined)
63
+ && plan.inputs.map((one) => one.item).sort().join(" ") === used && (plan.settings["enzymes"] === undefined || plan.settings["enzymes"] === enzymes));
64
+ }
65
+
66
+ /**
67
+ * A run to record, saying which plan it carries out if it does.
68
+ *
69
+ * @param lab - The lab.
70
+ * @param run - What would be handed to `recordRun`.
71
+ * @returns The same, with the plan it carries out named, so that recording it settles the plan.
72
+ */
73
+ export function withPlan(lab: PlanLab | null | undefined, run: Record<string, unknown>): Record<string, unknown> {
74
+ const plan = lab === null || lab === undefined ? undefined : planCarried(lab, run);
75
+ return plan === undefined ? run : { ...run, plan: plan.plan };
76
+ }
77
+
78
+ /**
79
+ * The runs proposed for one kind of tool, and a way to propose the one that is set up.
80
+ *
81
+ * @param props - `kind` is the kind of run; `now` is the run as the tool is set up, the way it would
82
+ * be recorded, or `null`; `onSetUp` is told a plan to set the tool up as.
83
+ */
84
+ export function Proposed({ kind, now, onSetUp }: { kind: string; now: Record<string, unknown> | null; onSetUp: (plan: Plan) => void }): ReactNode {
85
+ const lab = useLab()?.lab;
86
+ const act = useAct();
87
+ const [why, setWhy] = useState("");
88
+ const [busy, setBusy] = useState(false);
89
+ const [trouble, setTrouble] = useState<string | null>(null);
90
+ if (lab === null || lab === undefined) return null;
91
+ const open = lab.plans.filter((one) => one.settled === null && one.kind === kind);
92
+ const carried = planCarried(lab, now);
93
+ const person = (key: string): string => lab.roster.find((one) => one.key === key)?.person ?? "A device";
94
+ const partName = (checksum: string | undefined): string => lab.parts.find((one) => one.checksum === checksum)?.name ?? "a part";
95
+ const tubeName = (item: string | undefined): string => {
96
+ const held = lab.items.find((one) => one.item === item);
97
+ return held?.part === null ? lab.strains.find((one) => one.strain === held.strain)?.name ?? "a culture" : partName(held?.part);
98
+ };
99
+ const ask = async (action: "planRun" | "settlePlan", payload: unknown): Promise<void> => {
100
+ setBusy(true);
101
+ const answer = await act(action, payload);
102
+ setBusy(false);
103
+ setTrouble(answer.ok ? null : answer.error);
104
+ if (answer.ok && action === "planRun") setWhy("");
105
+ };
106
+ if (open.length === 0 && now === null) return null;
107
+ return (
108
+ <section className="card proposed">
109
+ <h2>Proposed</h2>
110
+ {open.length === 0 && <p className="dim small">Nothing is proposed here. What is set up now can be proposed, for somebody to carry out: nothing is used and nothing is recorded as done.</p>}
111
+ {open.map((plan) => {
112
+ const missing = plan.inputs.filter((one) => one.item === undefined);
113
+ return (
114
+ <article key={plan.plan} className={plan === carried ? "plan now" : "plan"}>
115
+ <p className="small"><strong>{person(plan.by)}</strong> proposes using {plan.inputs.map((one) => `${one.item === undefined ? partName(one.part) : tubeName(one.item)} as ${one.role}`).join(", ")}
116
+ {plan.expects.length > 0 && <>, expecting {plan.expects.map((one) => `${one.name} (${one.length.toLocaleString("en-US")} bp${one.circular ? ", circular" : ""})`).join(" and ")}</>}.</p>
117
+ {plan.note !== null && <p className="small why">{plan.note}</p>}
118
+ {missing.length > 0 && <p className="small attention">There is no tube yet of {missing.map((one) => partName(one.part)).join(" or ")}. It has to be ordered or made before this can be done.</p>}
119
+ {plan.wanting.length > 0 && <p className="small attention">Since this was proposed, {plan.wanting.map(tubeName).join(" and ")} {plan.wanting.length === 1 ? "has" : "have"} been retired or run short of what it would use.</p>}
120
+ {plan === carried && <p className="small good">This is what is set up now. Recording the run will say this proposal was carried out.</p>}
121
+ <div className="row tight">
122
+ {plan !== carried && <button type="button" disabled={busy || missing.length > 0} onClick={() => onSetUp(plan)}>Set it up</button>}
123
+ <button type="button" className="quiet" disabled={busy} onClick={() => void ask("settlePlan", { plan: plan.plan })}>Set it aside</button>
124
+ </div>
125
+ </article>
126
+ );
127
+ })}
128
+ {now !== null && carried === undefined && (
129
+ <fieldset disabled={busy} className="stack">
130
+ <label>Why<input value={why} onChange={(event) => setWhy(event.target.value)} maxLength={2000} placeholder="What it is for, for whoever carries it out" aria-label="Why this run is proposed" /></label>
131
+ <div className="row"><button type="button" className="quiet" onClick={() => void ask("planRun", toPlan(now, why))}>Propose what is set up</button></div>
132
+ </fieldset>
133
+ )}
134
+ {trouble !== null && <p className="trouble small" role="alert">{trouble}</p>}
135
+ </section>
136
+ );
137
+ }
@@ -229,7 +229,7 @@ export function usePrimerBench({ start, onPcr }: {
229
229
  latest.current = lab;
230
230
 
231
231
  // Templates worth designing on: anything long enough to hold a pair with something between them.
232
- const parts = useMemo(() => (lab?.parts ?? []).filter((one) => one.length >= 2 * DEFAULT_DESIGN.minLength + 1), [lab?.parts]);
232
+ const parts = useMemo(() => (lab?.parts ?? []).filter((one) => one.kind !== "protein" && one.length >= 2 * DEFAULT_DESIGN.minLength + 1), [lab?.parts]);
233
233
  const part = parts.find((one) => one.checksum === chosen) ?? parts.find((one) => one.features.length > 0) ?? parts[0];
234
234
  const offered = useMemo(() => (part === undefined ? [] : featureStretches(part)), [part]);
235
235
  const choose = (stretch: Stretch): void => { setFrom(String(stretch.start + 1)); setTo(String(stretch.end)); setLengths({}); setSaid(null); };
package/src/protein.ts ADDED
@@ -0,0 +1,204 @@
1
+ /**
2
+ * The protein a gene codes for, and what can be said about it.
3
+ *
4
+ * A lab that keeps only DNA stops one step short of what it is for. The point of putting a casein
5
+ * gene into yeast is the casein, and until the protein is a thing the lab holds there is nowhere
6
+ * to record that it came out, how much there is, or where the tube went.
7
+ *
8
+ * None of the numbers here are asserted. The molecular weight, the isoelectric point and the rest
9
+ * come from `ProteinAnalysis` in `@biolibs/seqtools`, which is a port of Biopython's ProtParam and
10
+ * is tested against it. What is here is the translating, the cutting of a signal peptide, and
11
+ * saying where each figure came from.
12
+ */
13
+ import type { PartFeature, PartState } from "@biolibs/bionet";
14
+ import { translate } from "@biolibs/seq";
15
+ import { ProteinAnalysis } from "@biolibs/seqtools";
16
+ import { CODON } from "./codons.js";
17
+ import type { Working } from "./pcr-working.js";
18
+
19
+ /** What a gene was translated into. */
20
+ export interface Translated {
21
+ /** The amino acids, with no stop. */
22
+ protein: string;
23
+ /** How many amino acids. */
24
+ length: number;
25
+ /** The stretch of the gene it came from, counting from 1, and which strand. */
26
+ from: { start: number; end: number; strand: 1 | -1 };
27
+ /** The signal peptide that was cut off, if one was. */
28
+ signal: { peptide: string; label: string } | null;
29
+ /** Whether the gene ended in a stop codon, which a coding sequence should. */
30
+ stopped: boolean;
31
+ /** Anything a careful person would look at. */
32
+ warnings: string[];
33
+ /** Why it could not be translated, or `null`. */
34
+ problem: string | null;
35
+ }
36
+
37
+ /** What is known about a protein, from its sequence alone. */
38
+ export interface ProteinFacts {
39
+ /** How many amino acids. */
40
+ length: number;
41
+ /** In daltons. */
42
+ weight: number;
43
+ /** The pH at which it carries no net charge. */
44
+ isoelectric: number;
45
+ /** How strongly it absorbs at 280 nm, with and without the cystines paired. */
46
+ extinction: { reduced: number; cystines: number };
47
+ /** Above 40 a protein is reckoned unstable in a test tube. */
48
+ instability: number;
49
+ /** How water-fearing it is on average: positive is water-fearing. */
50
+ gravy: number;
51
+ /** What fraction is each of helix, turn and sheet. */
52
+ structure: { helix: number; turn: number; sheet: number };
53
+ }
54
+
55
+ const clean = (bases: string): string => bases.replace(/\s+/g, "").toUpperCase();
56
+ const PAIR: Readonly<Record<string, string>> = { A: "T", T: "A", G: "C", C: "G", N: "N" };
57
+ const flip = (bases: string): string => [...bases].reverse().map((one) => PAIR[one] ?? "N").join("");
58
+
59
+ /**
60
+ * Translate a gene, or the coding sequence marked on it, into the protein it makes.
61
+ *
62
+ * @param part - The gene: its bases and what is marked on it.
63
+ * @param options - `cds` names a coding sequence marked on the part to translate, in place of the
64
+ * whole of it; `cutSignal` cuts off a signal peptide marked inside that stretch, which is what
65
+ * the mature protein is.
66
+ * @returns The protein, and where it came from.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { translateGene } from "@biolibs/bionet-tools";
71
+ *
72
+ * const made = translateGene(gene, { cds: "casein", cutSignal: true });
73
+ * made.protein; // the mature protein, with the signal peptide gone
74
+ * ```
75
+ */
76
+ export function translateGene(part: Pick<PartState, "sequence" | "features" | "circular">,
77
+ options: { cds?: string; cutSignal?: boolean } = {}): Translated {
78
+ const nothing = (problem: string): Translated =>
79
+ ({ protein: "", length: 0, from: { start: 1, end: 0, strand: 1 }, signal: null, stopped: false, warnings: [], problem });
80
+ const bases = clean(part.sequence);
81
+ if (!/^[ACGT]+$/.test(bases)) return nothing("A gene to translate is written in A, C, G and T, with no uncertain bases.");
82
+
83
+ const named = options.cds === undefined ? undefined
84
+ : part.features.find((one) => one.label === options.cds && /^cds$/i.test(one.type))
85
+ ?? part.features.find((one) => one.label === options.cds);
86
+ if (options.cds !== undefined && named === undefined) return nothing(`Nothing called ${JSON.stringify(options.cds)} is marked on this part.`);
87
+ if (named !== undefined && named.parts.length > 1) return nothing(`${named.label} is marked in ${named.parts.length} pieces, which this does not translate.`);
88
+ const piece = named?.parts[0] ?? { start: 0, end: bases.length };
89
+ const strand: 1 | -1 = named?.strand === -1 ? -1 : 1;
90
+ const stretch = bases.slice(piece.start, piece.end);
91
+ const coding = strand === -1 ? flip(stretch) : stretch;
92
+ if (coding.length < CODON) return nothing("That stretch is shorter than one codon.");
93
+
94
+ const warnings: string[] = [];
95
+ if (coding.length % CODON !== 0) warnings.push(`The stretch is ${coding.length} bases, which is not a whole number of codons, so the last ${coding.length % CODON} were left out.`);
96
+ const whole = coding.slice(0, coding.length - (coding.length % CODON));
97
+ const read = String(translate(whole));
98
+ const stopped = read.endsWith("*");
99
+ let protein = stopped ? read.slice(0, -1) : read;
100
+ if (!stopped) warnings.push("The stretch does not end in a stop codon, so it may not be the whole coding sequence.");
101
+ if (!protein.startsWith("M")) warnings.push("It does not begin with methionine, which a coding sequence usually does.");
102
+ const inside = protein.indexOf("*");
103
+ if (inside >= 0) {
104
+ warnings.push(`There is a stop at amino acid ${inside + 1}, before the end, so this reading frame is wrong or the gene is broken.`);
105
+ }
106
+
107
+ // The signal peptide is the first stretch of a secreted protein, and is cut off on the way out:
108
+ // what the lab ends up with is what is left, so it is worth being able to ask for that.
109
+ let signal: Translated["signal"] = null;
110
+ if (options.cutSignal === true) {
111
+ const marked = part.features.find((one) => /^sig[_ ]?peptide$/i.test(one.type) && one.parts[0] !== undefined
112
+ && one.parts[0].start >= piece.start && one.parts[0].end <= piece.end);
113
+ if (marked === undefined) warnings.push("No signal peptide is marked on this part, so nothing was cut off.");
114
+ else {
115
+ const first = marked.parts[0]!;
116
+ const from = strand === -1 ? Math.floor((piece.end - first.end) / CODON) : Math.floor((first.start - piece.start) / CODON);
117
+ const many = Math.floor((first.end - first.start) / CODON);
118
+ if (from !== 0) warnings.push(`${marked.label} is marked from amino acid ${from + 1}, not from the start, so it was not cut off.`);
119
+ else {
120
+ signal = { peptide: protein.slice(0, many), label: marked.label };
121
+ protein = protein.slice(many);
122
+ }
123
+ }
124
+ }
125
+ return {
126
+ protein, length: protein.length,
127
+ from: { start: piece.start + 1, end: piece.end, strand },
128
+ signal, stopped, warnings, problem: null,
129
+ };
130
+ }
131
+
132
+ /**
133
+ * What can be said about a protein from its sequence.
134
+ *
135
+ * @param protein - The amino acids.
136
+ * @returns The figures, or `null` if that is not a protein of standard amino acids.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * import { proteinFacts } from "@biolibs/bionet-tools";
141
+ *
142
+ * proteinFacts("MKVLILACLVALALAR")?.isoelectric; // the pH it carries no net charge at
143
+ * ```
144
+ */
145
+ export function proteinFacts(protein: string): ProteinFacts | null {
146
+ const amino = clean(protein);
147
+ if (!/^[ACDEFGHIKLMNPQRSTVWY]+$/.test(amino)) return null;
148
+ try {
149
+ const analysis = new ProteinAnalysis(amino);
150
+ const [reduced, cystines] = analysis.molarExtinctionCoefficient();
151
+ const [helix, turn, sheet] = analysis.secondaryStructureFraction();
152
+ return {
153
+ length: amino.length,
154
+ weight: analysis.molecularWeight(),
155
+ isoelectric: analysis.isoelectricPoint(),
156
+ extinction: { reduced, cystines },
157
+ instability: analysis.instabilityIndex(),
158
+ gravy: analysis.gravy(),
159
+ structure: { helix, turn, sheet },
160
+ };
161
+ } catch {
162
+ return null;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * The working behind a translation: what was read, and where each figure came from.
168
+ *
169
+ * @param made - What the gene was translated into.
170
+ * @param facts - What is known about the protein, if it could be worked out.
171
+ * @returns One working for the translation and one for the figures.
172
+ */
173
+ export function proteinWorking(made: Translated, facts: ProteinFacts | null): Working[] {
174
+ if (made.problem !== null) return [];
175
+ const count = (value: number): string => value.toLocaleString("en-US");
176
+ const out: Working[] = [{
177
+ of: "the protein",
178
+ comes: `${count(made.length)} amino acids`,
179
+ kind: "exact",
180
+ steps: [
181
+ `read from bases ${count(made.from.start)}–${count(made.from.end)}${made.from.strand === -1 ? ", on the bottom strand" : ""}`,
182
+ `${count(made.from.end - made.from.start + 1)} bases is ${count(Math.floor((made.from.end - made.from.start + 1) / CODON))} codons`,
183
+ made.stopped ? "the last codon is a stop, which is not an amino acid" : "there is no stop codon at the end",
184
+ ...(made.signal === null ? [] : [`${made.signal.label}, the first ${made.signal.peptide.length} amino acids, was cut off: it is gone from what the cell lets out`]),
185
+ `it begins ${made.protein.slice(0, 24)}${made.protein.length > 24 ? "…" : ""}`,
186
+ ],
187
+ }];
188
+ if (facts !== null) {
189
+ out.push({
190
+ of: "what is known of it",
191
+ comes: `${count(Math.round(facts.weight))} Da, carrying no net charge at pH ${facts.isoelectric.toFixed(2)}`,
192
+ kind: "estimate",
193
+ steps: [
194
+ `the weight is the amino acids added up, less a water for each bond: ${count(Math.round(facts.weight))} Da`,
195
+ `the isoelectric point is where its charges cancel: pH ${facts.isoelectric.toFixed(2)}`,
196
+ `it absorbs at 280 nm with ${count(facts.extinction.reduced)} M⁻¹cm⁻¹, which is how a concentration is read off`,
197
+ `the instability index is ${facts.instability.toFixed(1)}; over 40 is reckoned unstable in a tube`,
198
+ `${Math.round(facts.structure.helix * 100)}% helix, ${Math.round(facts.structure.turn * 100)}% turn, ${Math.round(facts.structure.sheet * 100)}% sheet`,
199
+ ],
200
+ rests: "These come from scales measured on other proteins and applied to this sequence. They are what the sequence suggests, not what anybody has measured of this protein.",
201
+ });
202
+ }
203
+ return out;
204
+ }
package/src/run.ts CHANGED
@@ -21,6 +21,22 @@ export interface ToolLab {
21
21
  places: readonly PlaceState[];
22
22
  }
23
23
 
24
+ /**
25
+ * The DNA part a tube holds, if it holds one.
26
+ *
27
+ * A lab keeps protein as well as DNA, and a tube of protein is nothing a polymerase, an enzyme or a
28
+ * ligase can be pointed at. Everything in this file works on DNA, so everything in it asks for a
29
+ * part this way and a protein is simply not offered.
30
+ *
31
+ * @param lab - The lab.
32
+ * @param checksum - What the tube is of, or `null` for a culture.
33
+ * @returns The part, or `undefined` if it is not one, or is not DNA.
34
+ */
35
+ export function dnaOf(lab: Pick<ToolLab, "parts">, checksum: string | null): PartState | undefined {
36
+ const part = checksum === null ? undefined : lab.parts.find((one) => one.checksum === checksum);
37
+ return part === undefined || part.kind === "protein" ? undefined : part;
38
+ }
39
+
24
40
  /** One tube that could be chosen. */
25
41
  export interface TubeChoice {
26
42
  /** The tube. */
@@ -44,7 +60,7 @@ export interface TubeChoice {
44
60
  export function pcrTubes(lab: ToolLab): { templates: TubeChoice[]; primers: TubeChoice[] } {
45
61
  const all: TubeChoice[] = [];
46
62
  for (const item of lab.items) {
47
- const part = lab.parts.find((one) => one.checksum === item.part);
63
+ const part = dnaOf(lab, item.part);
48
64
  if (part === undefined || item.retired || item.amount <= 0) continue;
49
65
  all.push({ item: item.item, part, label: `${part.name} · ${amountOf(item)} · ${whereWords(item, lab.places)}` });
50
66
  }
@@ -139,7 +155,7 @@ export function pcrFeatures(template: Pick<PartState, "sequence" | "features">,
139
155
  export function pcrRun(lab: ToolLab, choice: PcrChoice): PcrRun {
140
156
  const partOf = (id: string): PartState | undefined => {
141
157
  const item = lab.items.find((one) => one.item === id);
142
- return item === undefined ? undefined : lab.parts.find((one) => one.checksum === item.part);
158
+ return item === undefined ? undefined : dnaOf(lab, item.part);
143
159
  };
144
160
  const [template, forward, reverse] = [partOf(choice.template), partOf(choice.forward), partOf(choice.reverse)];
145
161
  const typed = choice.name?.trim() ?? "";
@@ -237,7 +253,7 @@ export interface DigestRun {
237
253
  */
238
254
  export function digestRun(lab: ToolLab, choice: DigestChoice): DigestRun {
239
255
  const item = lab.items.find((one) => one.item === choice.tube);
240
- const part = item === undefined ? undefined : lab.parts.find((one) => one.checksum === item.part);
256
+ const part = item === undefined ? undefined : dnaOf(lab, item.part);
241
257
  if (part === undefined) return { plan: null, pieces: [], matched: null, differed: null };
242
258
  const plan = planDigest(part, choice.enzymes, { ...(choice.gel === undefined ? {} : { gel: choice.gel }), ...(choice.ladder === undefined ? {} : { ladder: choice.ladder }) });
243
259
  if (plan.problem !== null) return { plan, pieces: [], matched: null, differed: null };
@@ -333,7 +349,7 @@ export function ligationRun(lab: ToolLab, choice: LigationChoice): LigationRun {
333
349
  const pieces: LigationPiece[] = [];
334
350
  for (const item of choice.tubes) {
335
351
  const held = lab.items.find((one) => one.item === item);
336
- const part = held === undefined ? undefined : lab.parts.find((one) => one.checksum === held.part);
352
+ const part = held === undefined ? undefined : dnaOf(lab, held.part);
337
353
  if (part === undefined || part.circular) return { plan: null, pieces: [], product: null, name: "", worked: null, failed: null };
338
354
  pieces.push({ id: item, name: part.name, sequence: part.sequence, ends: part.ends ?? { left: 0, right: 0 }, features: part.features });
339
355
  }
@@ -71,7 +71,7 @@ export function SequencesTool({ part: first }: { part?: string }) {
71
71
  <div className="toolhead">
72
72
  <label>Part
73
73
  <select value={part.checksum} onChange={(event) => setChosen(event.target.value)} aria-label="Part">
74
- {lab.parts.map((one) => <option key={one.checksum} value={one.checksum}>{one.name} · {count(one.length)} bp{one.circular ? " · circular" : ""}</option>)}
74
+ {lab.parts.map((one) => <option key={one.checksum} value={one.checksum}>{one.name} · {count(one.length)} {one.kind === "protein" ? "aa" : "bp"}{one.circular ? " · circular" : ""}</option>)}
75
75
  </select>
76
76
  </label>
77
77
  {endsWords(part) !== null && <span className="small">ends <code>{endsWords(part)}</code></span>}
package/src/tools.tsx CHANGED
@@ -7,11 +7,14 @@ import { DigestTool } from "./digest-tool.js";
7
7
  import { PcrTool } from "./pcr-tool.js";
8
8
  import { instrumentFor, toolFor, type ToolName } from "./run.js";
9
9
  import { LigationTool } from "./ligate-bench.js";
10
+ import { AssemblyTool } from "./assembly-bench.js";
11
+ import { CodonTool } from "./codon-bench.js";
12
+ import { VerifyTool } from "./verify-bench.js";
10
13
  import { PrimerTool } from "./primer-bench.js";
11
14
  import { SequencesTool } from "./sequences-tool.js";
12
15
 
13
16
  /** The tools used at a desk and not at an instrument: the lab's sequences, and designing primers. */
14
- export type DeskTool = "sequences" | "primers";
17
+ export type DeskTool = "sequences" | "primers" | "codons" | "assembly" | "verify";
15
18
 
16
19
  /** What each tool is called. */
17
20
  export const TOOL_NAMES: Readonly<Record<ToolName, string>> = { pcr: "PCR", digest: "Digest and gel", ligation: "Ligation" };
@@ -62,7 +65,7 @@ export function Tools({ tool: first = "pcr", views = {} }: { tool?: ToolName | D
62
65
  const [tool, setTool] = useState<ToolName | DeskTool>(first);
63
66
  if (lab === null || lab === undefined) return null;
64
67
  const shown = views[tool];
65
- const names: [ToolName | DeskTool, string][] = [["sequences", "Sequences"], ["primers", "Primers"], ...(Object.keys(TOOL_NAMES) as ToolName[]).map((one): [ToolName, string] => [one, TOOL_NAMES[one]])];
68
+ const names: [ToolName | DeskTool, string][] = [["sequences", "Sequences"], ["primers", "Primers"], ["codons", "Codons"], ["assembly", "Assembly"], ["verify", "Check"], ...(Object.keys(TOOL_NAMES) as ToolName[]).map((one): [ToolName, string] => [one, TOOL_NAMES[one]])];
66
69
  return (
67
70
  <div className="tools">
68
71
  <div className="row tight pick" role="tablist" aria-label="Tools">
@@ -70,7 +73,8 @@ export function Tools({ tool: first = "pcr", views = {} }: { tool?: ToolName | D
70
73
  <button key={one} type="button" role="tab" aria-selected={one === tool} className={one === tool ? "" : "quiet"} onClick={() => setTool(one)}>{name}</button>
71
74
  ))}
72
75
  </div>
73
- {(typeof shown === "function" ? shown(setTool) : shown) ?? (tool === "sequences" ? <SequencesTool /> : tool === "primers" ? <PrimerTool onPcr={() => setTool("pcr")} />
76
+ {(typeof shown === "function" ? shown(setTool) : shown) ?? (tool === "sequences" ? <SequencesTool /> : tool === "assembly" ? <AssemblyTool /> : tool === "codons" ? <CodonTool /> : tool === "verify" ? <VerifyTool />
77
+ : tool === "primers" ? <PrimerTool onPcr={() => setTool("pcr")} />
74
78
  : <Tool key={tool} tool={tool} instrument={instrumentFor(lab, tool)} />)}
75
79
  </div>
76
80
  );
@@ -0,0 +1,161 @@
1
+ "use client";
2
+
3
+ /**
4
+ * Checking a construct against the design, at a desk.
5
+ *
6
+ * Every other tool here proposes. This one confirms, and the thing it has to be careful about is
7
+ * the opposite of theirs: not to say more than it has checked. A read covers the stretch its primer
8
+ * reached and no more, so what it covers is said before what it found, and the rest is called
9
+ * unchecked rather than passed.
10
+ */
11
+ import { useEffect, useMemo, useState, type ReactNode } from "react";
12
+ import { useAct, useLab } from "@biolibs/bionet-react";
13
+ import { Glossed } from "@biolibs/glossary-react";
14
+ import { SequenceMap } from "./map.js";
15
+ import { checkRead, saysDifference, verifyRun, verifyWorking } from "./verify.js";
16
+ import { ShowWorking } from "./working.js";
17
+
18
+ const count = (value: number): string => value.toLocaleString("en-US");
19
+
20
+ /** What a host is handed to draw beside the panel. */
21
+ export interface VerifyDesk {
22
+ /** The tube of the design, to look at, if the lab has one that has been put somewhere. */
23
+ focus: { place: string; item: string } | null;
24
+ }
25
+
26
+ /**
27
+ * Checking a read against one of the lab's parts.
28
+ *
29
+ * @param options - `start` says what to open on, for a tour or a link.
30
+ * @returns `panel`, the tool itself, and `desk`, what a scene beside it should look at.
31
+ *
32
+ * @example
33
+ * ```tsx
34
+ * import { useVerifyBench } from "@biolibs/bionet-tools";
35
+ *
36
+ * const bench = useVerifyBench();
37
+ * <LabView lab={lab} wide beside={bench.panel} />
38
+ * ```
39
+ */
40
+ export function useVerifyBench({ start }: {
41
+ /** What to show: the design and the read. Followed whenever it changes. */
42
+ start?: { design?: string; read?: string };
43
+ } = {}): { panel: ReactNode; desk: VerifyDesk } {
44
+ const lab = useLab()?.lab;
45
+ const act = useAct();
46
+ const [design, setDesign] = useState(start?.design ?? "");
47
+ const [read, setRead] = useState(start?.read ?? "");
48
+ const [primer, setPrimer] = useState("");
49
+ const [busy, setBusy] = useState(false);
50
+ const [said, setSaid] = useState<string | null>(null);
51
+
52
+ const asked = JSON.stringify(start ?? null);
53
+ useEffect(() => {
54
+ if (start === undefined) return;
55
+ if (start.design !== undefined) setDesign(start.design);
56
+ if (start.read !== undefined) setRead(start.read);
57
+ }, [asked]);
58
+
59
+ // A read is of DNA; a protein is not something to compare bases against.
60
+ const dna = useMemo(() => (lab?.parts ?? []).filter((one) => one.kind !== "protein"), [lab?.parts]);
61
+ const part = dna.find((one) => one.checksum === design);
62
+ const checked = useMemo(() => (part === undefined || read.trim() === "" ? null : checkRead(part, read)), [part, read]);
63
+ const working = useMemo(() => (checked === null || checked.problem !== null || part === undefined ? [] : verifyWorking(checked, part)), [checked, part]);
64
+ const tubes = useMemo(() => (lab?.items ?? []).filter((one) => one.part === design && !one.retired), [lab?.items, design]);
65
+ const held = tubes.find((one) => one.where !== null);
66
+ const desk: VerifyDesk = { focus: held?.where == null ? null : { place: held.where.place, item: held.item } };
67
+
68
+ const record = async (): Promise<void> => {
69
+ const tube = tubes[0];
70
+ if (checked === null || checked.problem !== null || tube === undefined) return;
71
+ setBusy(true);
72
+ const answer = await act("recordRun", verifyRun(checked, { tube: tube.item, primer }));
73
+ setBusy(false);
74
+ setSaid(answer.ok ? `Recorded: the check is in the lab's history, and ${checked.matches ? "it matched" : "it did not match"}.` : answer.error);
75
+ };
76
+
77
+ const panel = lab === null || lab === undefined ? null : (
78
+ <div className="bionet verify">
79
+ <section className="card">
80
+ <h2>Check a construct</h2>
81
+ <p className="small"><Glossed text="Sequencing reads the bases of a piece of DNA, one read covering a few hundred bases from where its primer sat." /></p>
82
+ <p className="dim small">Paste what came back from the facility and it is compared with the design, base by base. Either strand will do. What the read does not reach is not checked, and is said so rather than passed.</p>
83
+ {dna.length === 0 ? <p className="empty">The lab has no DNA to check against.</p> : (
84
+ <fieldset disabled={busy} className="stack">
85
+ <label>It was supposed to be
86
+ <select value={design} onChange={(event) => { setDesign(event.target.value); setSaid(null); }} aria-label="The design">
87
+ <option value="">Choose a part…</option>
88
+ {dna.map((one) => <option key={one.checksum} value={one.checksum}>{one.name} · {count(one.length)} bp</option>)}
89
+ </select>
90
+ </label>
91
+ <label>The read
92
+ <textarea value={read} onChange={(event) => { setRead(event.target.value); setSaid(null); }} rows={5} spellCheck={false}
93
+ placeholder="Paste the bases that came back" aria-label="The read" />
94
+ </label>
95
+ <label>Read from which primer<input value={primer} onChange={(event) => setPrimer(event.target.value)} maxLength={200} placeholder="optional" aria-label="The primer it was read from" /></label>
96
+ </fieldset>
97
+ )}
98
+ </section>
99
+
100
+ {checked !== null && checked.problem !== null && <p className="trouble" role="status">{checked.problem}</p>}
101
+
102
+ {checked !== null && checked.problem === null && part !== undefined && (
103
+ <>
104
+ <section className="card">
105
+ <h2>{checked.matches ? "It is the design" : "It is not the design"}</h2>
106
+ <p className="voice">What was read</p>
107
+ {checked.covers === null ? <p className="trouble small">The read does not line up against this part anywhere. It may be a read of something else.</p> : (
108
+ <>
109
+ <p className="small">
110
+ Bases {count(checked.covers.from)}–{count(checked.covers.to)} of {count(part.length)}, which is {Math.round(checked.covered * 100)}% of it.
111
+ {checked.reversed && <> The read was turned round to line up, which is only which primer it came off.</>}
112
+ </p>
113
+ <SequenceMap name={part.name} length={part.length} circular={part.circular} features={part.features}
114
+ spans={[{ start: checked.covers.from - 1, end: checked.covers.to, label: "read", strand: 0 }]}
115
+ marks={checked.differences.slice(0, 40).map((one) => ({ at: one.at - 1, label: one.kind === "substitution" ? `${one.was}→${one.now}` : one.kind }))} />
116
+ </>
117
+ )}
118
+ <p className="voice">What was found</p>
119
+ {checked.matches ? <p className="small good">Every base the read covers is the base the design has.</p> : (
120
+ <p className={checked.changesProtein ? "small attention" : "small"}>
121
+ {count(checked.differences.length)} {checked.differences.length === 1 ? "difference" : "differences"}
122
+ {checked.changesProtein ? ", and at least one changes a protein." : ", none of which changes a protein."}
123
+ </p>
124
+ )}
125
+ {checked.differences.length > 0 && (
126
+ <ul className="checks">
127
+ {checked.differences.slice(0, 15).map((one) => (
128
+ <li key={`${one.at} ${one.kind}`} className={one.protein !== null && one.protein.kind !== "silent" ? "stop" : "look"}>{saysDifference(one)}</li>
129
+ ))}
130
+ </ul>
131
+ )}
132
+ {checked.differences.length > 15 && <p className="dim small">and {count(checked.differences.length - 15)} more.</p>}
133
+ {checked.warnings.length > 0 && <ul className="checks">{checked.warnings.map((one) => <li key={one} className="look">{one}</li>)}</ul>}
134
+ {tubes.length > 0 && (
135
+ <fieldset disabled={busy} className="row">
136
+ <button type="button" onClick={() => void record()}>Record the check</button>
137
+ <span className="dim small">A run against {part.name}, using a little of its tube.</span>
138
+ </fieldset>
139
+ )}
140
+ {said !== null && <p className="small" role="status">{said}</p>}
141
+ </section>
142
+
143
+ <section className="card">
144
+ <h2>The working</h2>
145
+ {working.map((one) => <ShowWorking key={one.of} working={one} />)}
146
+ </section>
147
+ </>
148
+ )}
149
+ </div>
150
+ );
151
+ return { panel, desk };
152
+ }
153
+
154
+ /**
155
+ * The checking tool on its own, for a lab that has not drawn its room.
156
+ *
157
+ * @param props - `start` says what to open on.
158
+ */
159
+ export function VerifyTool(props: Parameters<typeof useVerifyBench>[0]) {
160
+ return <>{useVerifyBench(props).panel}</>;
161
+ }