@biolibs/bionet-tools 0.1.10 → 0.1.12

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 (51) hide show
  1. package/README.md +211 -0
  2. package/dist/codons.d.ts +35 -0
  3. package/dist/codons.d.ts.map +1 -1
  4. package/dist/codons.js +55 -0
  5. package/dist/codons.js.map +1 -1
  6. package/dist/fusion-bench.d.ts +62 -0
  7. package/dist/fusion-bench.d.ts.map +1 -0
  8. package/dist/fusion-bench.js +114 -0
  9. package/dist/fusion-bench.js.map +1 -0
  10. package/dist/fusion.d.ts +120 -0
  11. package/dist/fusion.d.ts.map +1 -0
  12. package/dist/fusion.js +176 -0
  13. package/dist/fusion.js.map +1 -0
  14. package/dist/index.d.ts +12 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +12 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/modify.js +4 -4
  19. package/dist/modify.js.map +1 -1
  20. package/dist/ordering.d.ts +147 -0
  21. package/dist/ordering.d.ts.map +1 -0
  22. package/dist/ordering.js +203 -0
  23. package/dist/ordering.js.map +1 -0
  24. package/dist/protocol.d.ts +91 -0
  25. package/dist/protocol.d.ts.map +1 -0
  26. package/dist/protocol.js +278 -0
  27. package/dist/protocol.js.map +1 -0
  28. package/dist/remedy.d.ts +137 -0
  29. package/dist/remedy.d.ts.map +1 -0
  30. package/dist/remedy.js +234 -0
  31. package/dist/remedy.js.map +1 -0
  32. package/dist/tools.d.ts +1 -1
  33. package/dist/tools.d.ts.map +1 -1
  34. package/dist/tools.js +7 -3
  35. package/dist/tools.js.map +1 -1
  36. package/dist/work.d.ts +18 -0
  37. package/dist/work.d.ts.map +1 -0
  38. package/dist/work.js +155 -0
  39. package/dist/work.js.map +1 -0
  40. package/package.json +2 -2
  41. package/src/codons.ts +53 -0
  42. package/src/fusion-bench.tsx +209 -0
  43. package/src/fusion.ts +270 -0
  44. package/src/index.ts +12 -0
  45. package/src/modify.ts +4 -4
  46. package/src/ordering.ts +301 -0
  47. package/src/protocol.ts +332 -0
  48. package/src/remedy.ts +277 -0
  49. package/src/tools.tsx +8 -4
  50. package/src/work.tsx +319 -0
  51. package/tools.css +18 -0
@@ -0,0 +1,301 @@
1
+ /**
2
+ * The order a lab's open proposals have to be carried out in, worked out from what each one makes
3
+ * and what each one needs.
4
+ *
5
+ * A proposal is one run. Nothing in the log says that eleven of them are one piece of work, or which
6
+ * comes first, and until now nothing read them as anything but eleven unrelated cards. But the order
7
+ * is not missing from the data — it is simply never followed. A plan says what it `expects` to make,
8
+ * each thing with the checksum that would be its identity; another plan says what it needs, and may
9
+ * name a part there is no tube of yet by that same checksum. Where one plan expects what another
10
+ * needs, the first has to happen first. That is a fact about the molecules, not a declaration
11
+ * somebody made, and it is true whether or not anybody wrote it down.
12
+ *
13
+ * So this derives the order rather than adding a way to assert one. No new kind of entry, nothing an
14
+ * older device has to understand, and no way for the stated order and the real one to disagree.
15
+ *
16
+ * **Where the chain stops, and why.** It stops at a transformation. What a transformation makes is
17
+ * alive, so it has no checksum to point at: a strain is this lab's own, known by an ID, and the
18
+ * culture that would be an induction's input does not exist until somebody has grown it. A plan
19
+ * cannot name a tube that is not there. So the work up to and including putting a construct into a
20
+ * host can be proposed as one chain, and what follows it has to be proposed afresh once there is
21
+ * something growing. That is a real limit and it is said here rather than hidden: a plan that
22
+ * claimed to run past it would be claiming to name something nothing can name yet.
23
+ */
24
+ import type { ItemState, PlanState } from "@biolibs/bionet";
25
+
26
+ /** As much of a lab as the ordering reads. */
27
+ export interface OrderingLab {
28
+ plans: readonly PlanState[];
29
+ items: readonly ItemState[];
30
+ }
31
+
32
+ /** Why a step cannot be carried out yet, or `null` if it can. */
33
+ export type Holding =
34
+ | { why: "a step before it"; steps: string[] }
35
+ | { why: "something nobody is making"; parts: string[] }
36
+ | { why: "a tube that has run short"; tubes: string[] };
37
+
38
+ /** One step: a proposal, where it sits in the order, and what stands in its way. */
39
+ export interface Step {
40
+ /** The proposal itself. */
41
+ plan: PlanState;
42
+ /** The plans that have to be carried out before it, by ID. */
43
+ after: string[];
44
+ /** How deep it is: 0 for a step with nothing before it. */
45
+ depth: number;
46
+ /** What stands in its way, or `null` if it could be done now. */
47
+ held: Holding | null;
48
+ /** The checksums it would make. */
49
+ makes: string[];
50
+ }
51
+
52
+ /** The field a plan is filed under, unless a lab uses another word for it. */
53
+ export const FILED_UNDER = "project";
54
+
55
+ /** What a piece of work with no project is called. */
56
+ export const UNFILED = "Not filed";
57
+
58
+ /** One chain of steps that leads to one thing. */
59
+ export interface Thread {
60
+ /** What to call it: what it ends by making. */
61
+ name: string;
62
+ /** Its steps, in an order that can be carried out. */
63
+ steps: Step[];
64
+ /** What it ends with: what it makes that nothing else in it consumes. */
65
+ ends: { checksum: string; name: string }[];
66
+ /** Whether every step of it could be carried out as things stand. */
67
+ clear: boolean;
68
+ }
69
+
70
+ /** Everything on in one project. */
71
+ export interface Project {
72
+ /** What it is called, as somebody filed it. */
73
+ name: string;
74
+ /** Whether anybody actually filed it, or it is the heap of what nobody did. */
75
+ filed: boolean;
76
+ /** Its chains. */
77
+ threads: Thread[];
78
+ /** Its steps, in one order that works. */
79
+ order: Step[];
80
+ /** The ones that could be carried out now. */
81
+ ready: Step[];
82
+ }
83
+
84
+ /** The open proposals, read as work to be done. */
85
+ export interface PlanOfWork {
86
+ /**
87
+ * What is on, by project.
88
+ *
89
+ * A chain is not a project and cannot be: four caseins are four chains in one project, and two
90
+ * unrelated projects are also chains. Which work belongs together is a thing people decide, so it
91
+ * is filed rather than derived, and a plan nobody filed is in `Not filed` rather than silently
92
+ * lumped in with somebody else's.
93
+ */
94
+ projects: Project[];
95
+ /** The chains, each leading to one thing. A lab building four proteins has four. */
96
+ threads: Thread[];
97
+ /** Every open step, in one order that works. */
98
+ order: Step[];
99
+ /** The steps that could be carried out now. */
100
+ ready: Step[];
101
+ /** The steps that could not, and what each is waiting on. */
102
+ held: Step[];
103
+ /**
104
+ * Plans that need something nothing makes and no tube holds: what has to be ordered or
105
+ * synthesised before any of this can start, by checksum.
106
+ */
107
+ toGet: { checksum: string; name: string; forSteps: string[] }[];
108
+ /** Plans that somehow depend on each other in a circle, by ID. Empty, unless something is wrong. */
109
+ tangled: string[];
110
+ }
111
+
112
+ /** Whether the lab holds a tube of a part that has anything in it. */
113
+ const holds = (lab: OrderingLab, checksum: string): boolean =>
114
+ lab.items.some((one) => one.part === checksum && !one.retired && one.amount > 0);
115
+
116
+ /**
117
+ * The open proposals, read as work: what order they go in, what can start now, what is waiting.
118
+ *
119
+ * @param lab - The lab, with its plans and its tubes.
120
+ * @returns The work, in threads and in one order.
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * import { planOfWork } from "@biolibs/bionet-tools";
125
+ *
126
+ * const work = planOfWork(lab);
127
+ * work.ready.map((one) => one.plan.kind); // what somebody could go and do now
128
+ * work.toGet; // what has to be ordered before any of it
129
+ * ```
130
+ */
131
+ export function planOfWork(lab: OrderingLab): PlanOfWork {
132
+ const open = lab.plans.filter((one) => one.settled === null);
133
+ const byId = new Map(open.map((one) => [one.plan, one]));
134
+
135
+ // What each open plan would make, and who would make each thing.
136
+ const makers = new Map<string, string[]>();
137
+ for (const plan of open) {
138
+ for (const expected of plan.expects) makers.set(expected.checksum, [...(makers.get(expected.checksum) ?? []), plan.plan]);
139
+ }
140
+ const nameOf = (checksum: string): string =>
141
+ open.flatMap((one) => one.expects).find((one) => one.checksum === checksum)?.name ?? checksum.slice(0, 12);
142
+
143
+ /** What each plan waits on, and what it needs that nothing is making. */
144
+ const after = new Map<string, string[]>();
145
+ const missing = new Map<string, string[]>();
146
+ for (const plan of open) {
147
+ const waits: string[] = [];
148
+ const nowhere: string[] = [];
149
+ for (const input of plan.inputs) {
150
+ if (input.part === undefined) continue;
151
+ // A plan names a part rather than a tube when there was no tube of it when it was proposed.
152
+ // There may be one now, and that is a fact about the lab, not about the plan.
153
+ if (holds(lab, input.part)) continue;
154
+ const made = (makers.get(input.part) ?? []).filter((one) => one !== plan.plan);
155
+ if (made.length > 0) waits.push(...made);
156
+ else nowhere.push(input.part);
157
+ }
158
+ after.set(plan.plan, [...new Set(waits)]);
159
+ missing.set(plan.plan, [...new Set(nowhere)]);
160
+ }
161
+
162
+ // The order: a step comes after everything it waits on. Kahn's algorithm, which also finds a
163
+ // circle if the proposals somehow make one.
164
+ const left = new Set(open.map((one) => one.plan));
165
+ const depth = new Map<string, number>();
166
+ const order: string[] = [];
167
+ for (let guard = 0; left.size > 0 && guard <= open.length; guard += 1) {
168
+ const free = [...left].filter((id) => (after.get(id) ?? []).every((before) => !left.has(before)));
169
+ if (free.length === 0) break;
170
+ // In the order they were proposed, so that two steps that could both go now keep their order.
171
+ free.sort((a, b) => open.findIndex((one) => one.plan === a) - open.findIndex((one) => one.plan === b));
172
+ for (const id of free) {
173
+ depth.set(id, Math.max(0, ...(after.get(id) ?? []).map((before) => (depth.get(before) ?? 0) + 1)));
174
+ order.push(id);
175
+ left.delete(id);
176
+ }
177
+ }
178
+ const tangled = [...left];
179
+
180
+ const stepOf = (id: string): Step => {
181
+ const plan = byId.get(id)!;
182
+ const waits = (after.get(id) ?? []).filter((one) => byId.has(one));
183
+ const nowhere = missing.get(id) ?? [];
184
+ const held: Holding | null =
185
+ waits.length > 0 ? { why: "a step before it", steps: waits }
186
+ : nowhere.length > 0 ? { why: "something nobody is making", parts: nowhere }
187
+ : plan.wanting.length > 0 ? { why: "a tube that has run short", tubes: [...plan.wanting] }
188
+ : null;
189
+ return { plan, after: waits, depth: depth.get(id) ?? 0, held, makes: plan.expects.map((one) => one.checksum) };
190
+ };
191
+ const steps = order.map(stepOf);
192
+ const tangledSteps = tangled.map(stepOf);
193
+
194
+ // A thread is a set of steps joined by what they make and need: a lab building four proteins has
195
+ // four of them, and they are four separate pieces of work however they were proposed.
196
+ const where = new Map<string, number>();
197
+ const threads: Step[][] = [];
198
+ const join = (id: string, into: number): void => {
199
+ const was = where.get(id);
200
+ if (was === into) return;
201
+ if (was === undefined) { where.set(id, into); return; }
202
+ // Two threads met, so they were one thread: everything in the older joins the newer.
203
+ for (const [each, at] of where) if (at === was) where.set(each, into);
204
+ };
205
+ for (const step of steps) {
206
+ const joined = [step.plan.plan, ...step.after].map((id) => where.get(id)).find((at) => at !== undefined);
207
+ const at = joined ?? threads.push([]) - 1;
208
+ join(step.plan.plan, at);
209
+ for (const before of step.after) join(before, at);
210
+ }
211
+ for (const step of steps) threads[where.get(step.plan.plan)!]!.push(step);
212
+
213
+ const made = new Set(steps.flatMap((one) => one.makes));
214
+ const woven: Thread[] = threads.filter((one) => one.length > 0).map((one) => {
215
+ const inside = new Set(one.flatMap((step) => step.makes));
216
+ const needed = new Set(one.flatMap((step) => step.plan.inputs.flatMap((input) => (input.part === undefined ? [] : [input.part]))));
217
+ // What it ends with is what it makes that nothing in it then uses.
218
+ let ends = [...inside].filter((checksum) => !needed.has(checksum)).map((checksum) => ({ checksum, name: nameOf(checksum) }));
219
+ // Unless there is no such thing, which happens whenever a chain finishes with a transformation:
220
+ // every molecule it made went into the host, and what came out is alive and has no checksum to
221
+ // be named by. The last thing that can be named is then what the chain is known by.
222
+ if (ends.length === 0) {
223
+ const last = [...one].reverse().find((step) => step.makes.length > 0);
224
+ ends = (last?.makes ?? []).map((checksum) => ({ checksum, name: nameOf(checksum) }));
225
+ }
226
+ return {
227
+ // A chain is known by what it is for, which is the last thing it makes.
228
+ name: ends.map((each) => each.name).join(" and ") || `${one.length} ${one.length === 1 ? "step" : "steps"}`,
229
+ steps: one, ends, clear: one.every((step) => step.held === null || step.held.why === "a step before it"),
230
+ };
231
+ });
232
+
233
+ const toGet = new Map<string, string[]>();
234
+ for (const step of [...steps, ...tangledSteps]) {
235
+ for (const checksum of missing.get(step.plan.plan) ?? []) toGet.set(checksum, [...(toGet.get(checksum) ?? []), step.plan.plan]);
236
+ }
237
+
238
+ // Filed, not derived: which chains belong to one project is somebody's decision.
239
+ const filedAs = (step: Step): string => {
240
+ const said = step.plan.fields[FILED_UNDER];
241
+ return typeof said === "string" && said.trim() !== "" ? said.trim() : UNFILED;
242
+ };
243
+ const byProject = new Map<string, Step[]>();
244
+ for (const step of steps) byProject.set(filedAs(step), [...(byProject.get(filedAs(step)) ?? []), step]);
245
+ const projects: Project[] = [...byProject].map(([name, own]) => ({
246
+ name, filed: name !== UNFILED,
247
+ // A chain belongs to a project if any of its steps was filed under it. A chain whose steps were
248
+ // filed differently is shown under each, since the steps really are in both and saying
249
+ // otherwise would hide work from one of them.
250
+ threads: woven.filter((thread) => thread.steps.some((step) => filedAs(step) === name)),
251
+ order: own, ready: own.filter((step) => step.held === null),
252
+ // What nobody filed goes last: it is a heap, not a project.
253
+ })).sort((a, b) => Number(a.name === UNFILED) - Number(b.name === UNFILED) || a.name.localeCompare(b.name));
254
+
255
+ return {
256
+ projects, threads: woven, order: steps,
257
+ ready: steps.filter((one) => one.held === null),
258
+ held: steps.filter((one) => one.held !== null),
259
+ toGet: [...toGet].map(([checksum, forSteps]) => ({ checksum, name: made.has(checksum) ? nameOf(checksum) : checksum.slice(0, 12), forSteps })),
260
+ tangled,
261
+ };
262
+ }
263
+
264
+ /**
265
+ * The work said in a sentence or two, for somebody who wants to know where things stand.
266
+ *
267
+ * @param work - What `planOfWork` gave.
268
+ * @returns A line for each thing worth saying. Empty if nothing is proposed.
269
+ *
270
+ * @example
271
+ * ```ts
272
+ * import { planOfWork, saysWork } from "@biolibs/bionet-tools";
273
+ *
274
+ * saysWork(planOfWork(lab));
275
+ * // ["Eleven steps are proposed, in four pieces of work.", "Three could be done now.", …]
276
+ * ```
277
+ */
278
+ export function saysWork(work: PlanOfWork): string[] {
279
+ if (work.order.length === 0 && work.tangled.length === 0) return [];
280
+ const count = (many: number, one: string, more: string): string => `${many} ${many === 1 ? one : more}`;
281
+ const filed = work.projects.filter((one) => one.filed);
282
+ const said: string[] = [
283
+ `${count(work.order.length, "step is", "steps are")} proposed, in ${count(work.threads.length, "piece", "pieces")} of work`
284
+ + (filed.length === 0 ? "." : `, across ${count(filed.length, "project", "projects")}: ${filed.map((one) => one.name).join(", ")}.`),
285
+ ];
286
+ const loose = work.projects.find((one) => !one.filed);
287
+ if (loose !== undefined && filed.length > 0) {
288
+ said.push(`${count(loose.order.length, "step is", "steps are")} filed under no project.`);
289
+ }
290
+ if (work.ready.length > 0) said.push(`${count(work.ready.length, "step", "steps")} could be carried out now.`);
291
+ else if (work.order.length > 0) said.push("Nothing can be carried out yet.");
292
+ const waiting = work.held.filter((one) => one.held?.why === "a step before it").length;
293
+ if (waiting > 0) said.push(`${count(waiting, "step is", "steps are")} waiting on a step before it.`);
294
+ if (work.toGet.length > 0) {
295
+ said.push(`${count(work.toGet.length, "part has", "parts have")} to be ordered or made first: nothing proposed makes ${work.toGet.length === 1 ? "it" : "them"}, and there is no tube.`);
296
+ }
297
+ const short = work.held.filter((one) => one.held?.why === "a tube that has run short").length;
298
+ if (short > 0) said.push(`${count(short, "step counts", "steps count")} on a tube that has been retired or run short.`);
299
+ if (work.tangled.length > 0) said.push(`${count(work.tangled.length, "step", "steps")} depend on each other in a circle and cannot be ordered.`);
300
+ return said;
301
+ }
@@ -0,0 +1,332 @@
1
+ /**
2
+ * The work written out as something a person can carry to a bench.
3
+ *
4
+ * Everything else here is for a screen: a panel that knows the lab, with the tubes in dropdowns and
5
+ * the working folded away. None of it is any use at a bench with gloves on, and a plan nobody can
6
+ * follow standing up is not finished.
7
+ *
8
+ * The whole difficulty is honesty. A plan records what the operator set — the cycling programme, the
9
+ * enzymes, the inducer and how long for — and a protocol wants rather more than that: a polymerase,
10
+ * a buffer, a final volume, a way of making cells competent. Those are not in the plan, and a tool
11
+ * that wrote in plausible ones would be making things up on a page somebody carries to a bench and
12
+ * trusts. So each step carries two lists and they are kept apart: what the plan says to do, which is
13
+ * exact, and what the plan does not say, which is named so the lab fills it in with its own usual
14
+ * way rather than discovering the hole halfway through.
15
+ *
16
+ * Nothing here invents a number. If a volume is in it, somebody set that volume.
17
+ */
18
+ import type { PlanState } from "@biolibs/bionet";
19
+ import { planOfWork, type OrderingLab, type Step } from "./ordering.js";
20
+
21
+ /**
22
+ * As much of a lab as a protocol reads: the work, plus the names of things, since a sheet carried to
23
+ * a bench says "1 µL of pGene, in Box 1" and not a checksum.
24
+ */
25
+ export interface ProtocolLab extends OrderingLab {
26
+ parts: readonly { checksum: string; name: string; length: number; circular: boolean }[];
27
+ strains?: readonly { strain: string; name: string; host: string }[];
28
+ places?: readonly { place: string; name: string }[];
29
+ }
30
+
31
+ /** One step, as somebody at a bench reads it. */
32
+ export interface ProtocolStep {
33
+ /** Its number within its piece of work. */
34
+ number: number;
35
+ /** What the step is, in a line. */
36
+ title: string;
37
+ /** What to get out before starting, with how much of each and where it is. */
38
+ takeOut: string[];
39
+ /** What to set a machine to, from what the plan recorded. */
40
+ set: { what: string; to: string }[];
41
+ /** What to do, in order. */
42
+ doThis: string[];
43
+ /** What to record afterwards, which is what keeps the lab's history true. */
44
+ thenRecord: string;
45
+ /**
46
+ * What this plan does not say, and the lab has to supply.
47
+ *
48
+ * The most important list on the page. A protocol that quietly left these out would read as
49
+ * complete and send somebody to the bench without a polymerase.
50
+ */
51
+ notSaid: string[];
52
+ /** Whatever the person who proposed it wanted to say. */
53
+ note: string | null;
54
+ }
55
+
56
+ /** One piece of work, written out. */
57
+ export interface Protocol {
58
+ /** What it is called. */
59
+ title: string;
60
+ /** A line or two about what it is and what it leaves you with. */
61
+ about: string[];
62
+ /** What the lab has to have before the first step. */
63
+ haveReady: string[];
64
+ /** The steps, in the order to carry them out. */
65
+ steps: ProtocolStep[];
66
+ /** What you have at the end of it. */
67
+ atTheEnd: string[];
68
+ }
69
+
70
+ /** What a kind of run is called on the page, and what a plan of that kind never says. */
71
+ const KINDS: Readonly<Record<string, { title: string; records: string; notSaid: readonly string[] }>> = {
72
+ pcr: {
73
+ title: "Copy it by PCR",
74
+ records: "at the PCR tool, which takes what it used from each tube and puts the product in the freezer.",
75
+ notSaid: ["which polymerase and which buffer", "the final volume of the reaction, and how much water",
76
+ "how much of each primer, by concentration", "the first denaturation and the last extension"],
77
+ },
78
+ digest: {
79
+ records: "at the digest and gel tool, which takes what it used and notes whether the gel showed what was expected.", title: "Cut it, and run a gel",
80
+ notSaid: ["which buffer, and how much enzyme", "what temperature to cut at and for how long",
81
+ "how the gel is stained and how it is looked at"],
82
+ },
83
+ ligation: {
84
+ records: "at the ligation tool, which takes what it used and puts what came out in the freezer.", title: "Join the pieces",
85
+ notSaid: ["which ligase and which buffer", "the ratio of insert to vector", "what temperature to leave it at, and for how long"],
86
+ },
87
+ assembly: {
88
+ records: "at the assembly tool, which takes what it used and puts the ring in the freezer.", title: "Build the ring",
89
+ notSaid: ["which assembly mix", "what temperature to hold it at, and for how long", "how much of each piece, by concentration"],
90
+ },
91
+ transformation: {
92
+ records: "on the Strains page. Whether it worked is whether colonies grew, which only you can say, and either way it used what it used.", title: "Put it into a host",
93
+ notSaid: ["how the cells are made competent", "heat shock or electroporation, and the settings for it",
94
+ "how long to let them recover, and in what", "what to select on"],
95
+ },
96
+ induction: {
97
+ records: "at the induction tool, which takes what it used and, if the band is there, puts the protein in the freezer.", title: "Grow it and look for the protein",
98
+ notSaid: ["which medium, and what volume", "what density to induce at", "how the cells are broken open, if they are",
99
+ "how the gel is stained"],
100
+ },
101
+ sequencing: { records: "at the checking tool, which compares the read against the design and records what it found.", title: "Have it sequenced", notSaid: ["which facility, and how they want it sent", "how much to send, and at what concentration"] },
102
+ };
103
+
104
+ const count = (value: number): string => value.toLocaleString("en-US");
105
+
106
+ /**
107
+ * The work of one piece, written out as a protocol.
108
+ *
109
+ * @param lab - The lab, for the names of what its tubes hold and where they are.
110
+ * @param options - `project` picks one project's work; `title` names the sheet.
111
+ * @returns One protocol for each piece of work, in the order the pieces come.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * import { protocolsFor, protocolText } from "@biolibs/bionet-tools";
116
+ *
117
+ * for (const sheet of protocolsFor(lab, { project: "Real Vegan Cheese" })) console.log(protocolText(sheet));
118
+ * ```
119
+ */
120
+ export function protocolsFor(lab: ProtocolLab, options: { project?: string; title?: string } = {}): Protocol[] {
121
+ const work = planOfWork(lab);
122
+ const threads = options.project === undefined ? work.threads
123
+ : work.projects.find((one) => one.name === options.project)?.threads ?? [];
124
+
125
+ const partName = (checksum: string | null | undefined): string =>
126
+ lab.parts.find((one) => one.checksum === checksum)?.name ?? "a part";
127
+ const placeName = (place: string | null | undefined): string | null =>
128
+ (lab.places ?? []).find((one) => one.place === place)?.name ?? null;
129
+ /** What is in a tube, by the lab's name for it. */
130
+ const whatIsIn = (item: string): string => {
131
+ const held = lab.items.find((one) => one.item === item);
132
+ if (held === undefined) return "something the lab no longer has";
133
+ return held.part === null
134
+ ? (lab.strains ?? []).find((one) => one.strain === held.strain)?.name ?? "a culture"
135
+ : partName(held.part);
136
+ };
137
+ /**
138
+ * How much of what, for an instruction: short, because the instruction is read while doing it.
139
+ */
140
+ const tubeWords = (item: string, amount: number): string => {
141
+ const held = lab.items.find((one) => one.item === item);
142
+ const unit = held?.unit ?? "";
143
+ return `${count(amount)}${unit === "" ? "" : ` ${unit}`} of ${whatIsIn(item)}`;
144
+ };
145
+ /**
146
+ * The same, with where it is and how much the tube holds: for the list of what to fetch before
147
+ * starting, which is read standing in front of a freezer and wants rather more.
148
+ */
149
+ const fetchWords = (item: string, amount: number): string => {
150
+ const held = lab.items.find((one) => one.item === item);
151
+ if (held === undefined) return "a tube the lab no longer has";
152
+ const unit = held.unit ?? "";
153
+ const where = placeName(held.where?.place);
154
+ return `${tubeWords(item, amount)}${where === null ? "" : ` — in ${where}`}`
155
+ + ` (the tube holds ${count(held.amount)}${unit === "" ? "" : ` ${unit}`})`;
156
+ };
157
+
158
+ const says = (plan: PlanState, key: string): string | null => {
159
+ const value = plan.settings[key];
160
+ return value === undefined ? null : String(value);
161
+ };
162
+
163
+ /** What to do, for a kind of run, from what the plan actually recorded. */
164
+ const doingOf = (step: Step): { doThis: string[]; set: { what: string; to: string }[] } => {
165
+ const plan = step.plan;
166
+ const used = plan.inputs.map((one) => ({
167
+ // A part the lab has no tube of has an amount but no unit, since the unit belongs to the tube.
168
+ // A bare "1 of the insert" reads as a mistake, so it is simply named.
169
+ ...one, words: one.item === undefined ? partName(one.part) : tubeWords(one.item, one.amount),
170
+ }));
171
+ const byRole = (role: string) => used.filter((one) => one.role === role);
172
+ const makes = plan.expects.map((one) => `${one.name} (${count(one.length)} bp${one.circular ? ", a circle" : ""})`);
173
+ const set: { what: string; to: string }[] = [];
174
+ const doThis: string[] = [];
175
+
176
+ if (plan.kind === "pcr") {
177
+ const template = byRole("template")[0] ?? used[0];
178
+ const primers = used.filter((one) => /primer/.test(one.role));
179
+ doThis.push(`Set up the reaction with ${template?.words ?? "the template"} as the template`
180
+ + (primers.length === 0 ? "." : `, and ${primers.map((one) => one.words).join(" and ")}.`));
181
+ const programme = ["denature_c", "anneal_c", "anneal_s", "extend_c", "extend_s", "cycles"].map((key) => says(plan, key));
182
+ if (programme.every((one) => one !== null)) {
183
+ set.push({ what: "Denature", to: `${programme[0]} °C` });
184
+ set.push({ what: "Anneal", to: `${programme[1]} °C for ${programme[2]} s` });
185
+ set.push({ what: "Extend", to: `${programme[3]} °C for ${programme[4]} s` });
186
+ set.push({ what: "Cycles", to: String(programme[5]) });
187
+ doThis.push("Run the programme above.");
188
+ } else {
189
+ doThis.push("Run it on the thermocycler. This plan does not record the programme, so set it as the lab usually does for these primers.");
190
+ }
191
+ doThis.push(`Expect ${makes.join(" and ") || "one product"}.`);
192
+ } else if (plan.kind === "digest") {
193
+ const enzymes = (says(plan, "enzymes") ?? "").split("+").filter((one) => one !== "");
194
+ doThis.push(`Cut ${used.map((one) => one.words).join(" and ")}`
195
+ + (enzymes.length === 0 ? "." : ` with ${enzymes.join(" and ")}.`));
196
+ const gel = says(plan, "gel");
197
+ if (gel !== null) set.push({ what: "Gel", to: `${gel}% agarose` });
198
+ for (const [key, what] of [["volts", "Run at"], ["minutes", "For"]] as const) {
199
+ const value = says(plan, key);
200
+ if (value !== null) set.push({ what, to: key === "volts" ? `${value} V` : `${value} min` });
201
+ }
202
+ const expected = says(plan, "expected");
203
+ doThis.push("Run it on the gel beside a ladder.");
204
+ if (expected !== null) doThis.push(`Expect bands at ${expected.split(",").map((one) => `${count(Number(one))} bp`).join(", ")}.`);
205
+ } else if (plan.kind === "ligation" || plan.kind === "assembly") {
206
+ doThis.push(`Put ${used.map((one) => one.words).join(" and ")} together.`);
207
+ const overlap = says(plan, "overlap");
208
+ if (overlap !== null) set.push({ what: "Overlap at each join", to: `${overlap} bp` });
209
+ const joins = says(plan, "joins");
210
+ if (joins !== null) set.push({ what: "Joins", to: String(joins) });
211
+ doThis.push(`Expect ${makes.join(" and ") || "one product"}.`);
212
+ } else if (plan.kind === "transformation") {
213
+ const construct = byRole("construct")[0];
214
+ const host = byRole("host")[0];
215
+ doThis.push(`Put ${construct?.words ?? "the construct"} into ${host?.words ?? "the host"}.`);
216
+ doThis.push("Plate them out and leave them to grow.");
217
+ doThis.push("Whether it worked is whether colonies grew, which only you can say. Either way it used what it used.");
218
+ } else if (plan.kind === "induction") {
219
+ const culture = used[0];
220
+ doThis.push(`Grow ${culture?.words ?? "the culture"}.`);
221
+ const inducer = says(plan, "inducer");
222
+ const at = says(plan, "at");
223
+ if (inducer !== null) doThis.push(`Add ${inducer}${at === null ? "" : ` to ${at}`}.`);
224
+ for (const [key, what, unit] of [["celsius", "Grow at", "°C"], ["rpm", "Shaking at", "rpm"], ["hours", "For", "h"]] as const) {
225
+ const value = says(plan, key);
226
+ if (value !== null) set.push({ what, to: `${value} ${unit}` });
227
+ }
228
+ const kda = says(plan, "expected_kda");
229
+ doThis.push("Run a sample on a protein gel, beside a lane of the same culture before it was induced.");
230
+ if (kda !== null) doThis.push(`Look for a band at ${kda} kDa that is in the induced lane and not the other.`);
231
+ } else {
232
+ doThis.push(`Carry out the ${plan.kind} with ${used.map((one) => one.words).join(" and ") || "what it names"}.`);
233
+ if (makes.length > 0) doThis.push(`Expect ${makes.join(" and ")}.`);
234
+ }
235
+ return { doThis, set };
236
+ };
237
+
238
+ return threads.map((thread) => {
239
+ const steps: ProtocolStep[] = thread.steps.map((step, at) => {
240
+ const known = KINDS[step.plan.kind];
241
+ const number = at + 1;
242
+ const { doThis, set } = doingOf(step);
243
+ // Something with no tube may be made by a step before this one, which the chain already
244
+ // knows. Saying "order it" when step 1 makes it would send somebody shopping for nothing.
245
+ const madeAt = (checksum: string | undefined): number | null => {
246
+ const at = thread.steps.findIndex((each) => each.makes.includes(checksum ?? ""));
247
+ return at < 0 || at >= number ? null : at + 1;
248
+ };
249
+ const takeOut = step.plan.inputs.map((one) => {
250
+ if (one.item !== undefined) return fetchWords(one.item, one.amount);
251
+ const from = madeAt(one.part);
252
+ return from === null
253
+ ? `${partName(one.part)} — the lab has no tube of it, and nothing here makes it: order or make it first`
254
+ : `${partName(one.part)} — what step ${from} makes`;
255
+ });
256
+ return {
257
+ number,
258
+ title: known?.title ?? `Carry out the ${step.plan.kind}`,
259
+ takeOut, set, doThis,
260
+ // Recording is what keeps the lab's history true, and where it is done differs by kind:
261
+ // a transformation is not run at a machine and is said on the Strains page.
262
+ thenRecord: `Record it ${known?.records ?? `at the ${step.plan.kind} tool.`}`,
263
+ notSaid: [...(known?.notSaid ?? ["what this plan does not record, the lab supplies as usual"])],
264
+ note: step.plan.note,
265
+ };
266
+ });
267
+ const needed = work.toGet.filter((one) => one.forSteps.some((each) => thread.steps.some((step) => step.plan.plan === each)));
268
+ // A chain that makes nothing — a digest, a check — has no product to be named by, so it is
269
+ // named by what it is done to, which is what somebody looking for the sheet would call it.
270
+ const actsOn = thread.steps[0]?.plan.inputs.flatMap((one) => (one.item === undefined ? [partName(one.part)] : [whatIsIn(one.item)])) ?? [];
271
+ return {
272
+ title: options.title ?? (thread.ends.length > 0 ? thread.name
273
+ : actsOn.length > 0 ? `${KINDS[thread.steps[0]!.plan.kind]?.title ?? thread.steps[0]!.plan.kind}: ${actsOn[0]}` : thread.name),
274
+ about: [
275
+ `${steps.length} ${steps.length === 1 ? "step" : "steps"}.`,
276
+ ...(thread.ends.length === 0 ? [] : [`It ends with ${thread.ends.map((one) => partName(one.checksum) === "a part" ? one.name : partName(one.checksum)).join(" and ")}.`]),
277
+ "Every step is proposed, not done: nothing is used and nothing is recorded until somebody carries it out and says so.",
278
+ ],
279
+ haveReady: [
280
+ ...needed.map((one) => `${partName(one.checksum) === "a part" ? one.name : partName(one.checksum)} — nothing here makes it and the lab has no tube: order or make it first.`),
281
+ ...[...new Set(thread.steps.flatMap((step) => step.plan.inputs.flatMap((one) => (one.item === undefined ? [] : [fetchWords(one.item, one.amount)]))))],
282
+ ],
283
+ steps,
284
+ atTheEnd: thread.ends.map((one) => partName(one.checksum) === "a part" ? one.name : partName(one.checksum)),
285
+ };
286
+ });
287
+ }
288
+
289
+ /**
290
+ * A protocol as text, to print or to paste.
291
+ *
292
+ * Markdown, because it reads as well unrendered as rendered, and somebody at a bench is as likely to
293
+ * have it in a terminal or a text file as on a page.
294
+ *
295
+ * @param protocol - What `protocolsFor` gave.
296
+ * @returns The sheet.
297
+ */
298
+ export function protocolText(protocol: Protocol): string {
299
+ const out: string[] = [`# ${protocol.title}`, ""];
300
+ for (const line of protocol.about) out.push(line, "");
301
+ if (protocol.haveReady.length > 0) {
302
+ out.push("## Have ready", "");
303
+ for (const one of protocol.haveReady) out.push(`- ${one}`);
304
+ out.push("");
305
+ }
306
+ for (const step of protocol.steps) {
307
+ out.push(`## ${step.number}. ${step.title}`, "");
308
+ if (step.note !== null) out.push(`*${step.note}*`, "");
309
+ if (step.takeOut.length > 0) {
310
+ out.push("**Take out**", "");
311
+ for (const one of step.takeOut) out.push(`- ${one}`);
312
+ out.push("");
313
+ }
314
+ if (step.set.length > 0) {
315
+ out.push("**Set**", "");
316
+ for (const one of step.set) out.push(`- ${one.what}: ${one.to}`);
317
+ out.push("");
318
+ }
319
+ out.push("**Do**", "");
320
+ for (const [at, one] of step.doThis.entries()) out.push(`${at + 1}. ${one}`);
321
+ out.push("", `**Then** ${step.thenRecord}`, "");
322
+ out.push("**This plan does not say**", "");
323
+ for (const one of step.notSaid) out.push(`- ${one}`);
324
+ out.push("");
325
+ }
326
+ if (protocol.atTheEnd.length > 0) out.push(`At the end you have ${protocol.atTheEnd.join(" and ")}.`, "");
327
+ out.push("---", "",
328
+ "Everything above that is a number — a volume, a temperature, a time, a length — is what somebody",
329
+ "set or what the lab's own tools worked out. Nothing here was filled in to make the page look finished:",
330
+ "what the plan does not say is listed under each step instead.");
331
+ return out.join("\n");
332
+ }