@biolibs/bionet 1.6.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/merge.ts CHANGED
@@ -28,9 +28,11 @@
28
28
  */
29
29
  import { Dseq } from "@biolibs/dseq";
30
30
  import { Dseqrecord } from "@biolibs/dseqrecord";
31
+ import { seguid } from "@biolibs/seguid";
31
32
  import type { SignOptions, SigningKey } from "@biolibs/opencloning";
32
33
  import { entryId, readEntry, verifyEntry, writeEntry, type Operation, type PartEnds, type PartFeature, type PlanInput, type Role, type RunInput, type StandingMm,
33
- type SignedEntry } from "./log.js";
34
+ type PartKind, type SignedEntry } from "./log.js";
35
+ export type { PartKind, StrainRecord } from "./log.js";
34
36
  import { INVENTORY_VERSION, type InventoryDocument, type InventoryPart, type LabModel,
35
37
  type PeerModel } from "./model.js";
36
38
 
@@ -53,10 +55,12 @@ export interface RosterKey {
53
55
  removed: { by: string; cutoff: number } | null;
54
56
  }
55
57
 
56
- /** One part the lab knows of. */
58
+ /** One part the lab knows of: a piece of DNA, or a protein. */
57
59
  export interface PartState {
58
- /** Its checksum, which is its identity. */
60
+ /** Its checksum, which is its identity. A protein's is counted differently from DNA's. */
59
61
  checksum: string;
62
+ /** What it is made of. */
63
+ kind: PartKind;
60
64
  /** Its bases. */
61
65
  sequence: string;
62
66
  /** Whether it is a circle. */
@@ -77,12 +81,37 @@ export interface PartState {
77
81
  added: string;
78
82
  }
79
83
 
80
- /** One physical item: a tube, a prep. */
84
+ /** One strain the lab keeps. */
85
+ export interface StrainState {
86
+ /** Its ID. */
87
+ strain: string;
88
+ /** What the lab calls it. */
89
+ name: string;
90
+ /** The organism it is. */
91
+ host: string;
92
+ /** The checksums of the parts it carries. */
93
+ carries: string[];
94
+ /** The strain it was made from, if the lab has that one. */
95
+ parent: string | null;
96
+ /** The run that made it, if one did. */
97
+ from: string | null;
98
+ /** Anything else set on it. */
99
+ fields: Record<string, string | number | null>;
100
+ /** The entry that added it. */
101
+ added: string;
102
+ }
103
+
104
+ /** One physical item: a tube of a molecule, or a culture of a strain. */
81
105
  export interface ItemState {
82
106
  /** Its ID. */
83
107
  item: string;
84
- /** The checksum of the part it is an item of. */
85
- part: string;
108
+ /**
109
+ * The checksum of the part it is an item of, or `null` if it is a culture. Exactly one of this
110
+ * and `strain` is set.
111
+ */
112
+ part: string | null;
113
+ /** The strain it is a culture of, or `null` if it is a tube of a molecule. */
114
+ strain: string | null;
86
115
  /** What one of its amount is, if anybody said: a tube, a microlitre. */
87
116
  unit: string | null;
88
117
  /** How much there is, by the log. Always a whole number of the unit. */
@@ -232,6 +261,8 @@ export interface LabState {
232
261
  roster: RosterKey[];
233
262
  /** Every part. */
234
263
  parts: PartState[];
264
+ /** Every strain. */
265
+ strains: StrainState[];
235
266
  /** Every item. */
236
267
  items: ItemState[];
237
268
  /** Every place. */
@@ -279,6 +310,8 @@ const text = (value: unknown, most: number): value is string =>
279
310
  /** An amount is a whole number of the item's unit: only whole numbers have one agreed spelling to sign. */
280
311
  /** Fields of a place that are changed by their own operations, not by `field.set`. */
281
312
  const PLACE_RESERVED = new Set(["place", "kind", "parent", "grid", "standing", "retired", "adrift"]);
313
+ /** The same, for a strain: what it is and came from is fixed when it is added. */
314
+ const STRAIN_RESERVED = new Set(["strain", "host", "carries", "parent", "from"]);
282
315
 
283
316
  /** The most positions a box may have along one side, and the farthest a place may stand or reach, in millimetres. */
284
317
  const MOST_SIDE = 100;
@@ -318,8 +351,19 @@ const MOST_PIECES = 100;
318
351
  * @returns The molecule's length, checksum and ends.
319
352
  * @throws If that is not a sequence, or the ends are not ones a linear molecule of that length can have.
320
353
  */
321
- function moleculeOf(sequence: string, circular: boolean, ends: unknown): { length: number; checksum: string; ends: PartEnds } {
354
+ function moleculeOf(sequence: string, circular: boolean, ends: unknown, kind: PartKind = "dna"): { length: number; checksum: string; ends: PartEnds } {
322
355
  const blunt = { left: 0, right: 0 };
356
+ if (kind === "protein") {
357
+ // A protein has no strands, so no ends and no circle, and its checksum is counted over the
358
+ // amino acids. The same letters as DNA must never give the same checksum.
359
+ if (circular || (ends !== undefined && ends !== null && (ends as PartEnds).left !== 0)) throw new Error("protein");
360
+ // A stop is not an amino acid and a part is a molecule somebody holds: there is no tube of a
361
+ // chain with a stop in the middle of it. It was refused before this said so, because the
362
+ // checksum underneath has no letter for it, but it was refused by an exception from two layers
363
+ // down rather than by a rule that can be read.
364
+ if (!/^[ACDEFGHIKLMNPQRSTVWYBXZJUO]+$/i.test(sequence)) throw new Error("protein");
365
+ return { length: sequence.length, checksum: String(seguid(sequence.toUpperCase(), "{protein}")), ends: blunt };
366
+ }
323
367
  if (ends === undefined) { const record = new Dseqrecord(sequence, circular); return { length: record.length, checksum: record.seguid(), ends: blunt }; }
324
368
  const given = ends as Partial<PartEnds> | null;
325
369
  if (typeof given !== "object" || given === null || !amountOf(given.left) || !amountOf(given.right)) throw new Error("ends");
@@ -330,6 +374,32 @@ function moleculeOf(sequence: string, circular: boolean, ends: unknown): { lengt
330
374
  return { length: sequence.length, checksum: record.seguid(), ends: { left: given.left, right: given.right } };
331
375
  }
332
376
 
377
+ /**
378
+ * The checksum a part would have: what its identity will be once it is in the log.
379
+ *
380
+ * It is here because a tool sometimes has to name a molecule before the lab holds it — to say in a
381
+ * run's settings which protein the run is expected to make, or to look for a part the lab may
382
+ * already have. The alternative is each tool counting a checksum its own way, and a part named by a
383
+ * checksum nobody else arrives at is a part nobody else will ever match. So the rule lives in one
384
+ * place and this is the way to it.
385
+ *
386
+ * @param part - Its bases or amino acids, whether it is a circle, what ends it has, and what it is
387
+ * made of. DNA if nothing says.
388
+ * @returns The checksum.
389
+ * @throws If that is not a sequence of what it says it is, or a linear molecule of that length
390
+ * cannot have those ends, or it is a protein said to be a circle.
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * import { partChecksum } from "@biolibs/bionet";
395
+ *
396
+ * partChecksum({ sequence: "MKVLILACLVALALA", kind: "protein" }); // the protein's identity
397
+ * ```
398
+ */
399
+ export function partChecksum(part: { sequence: string; circular?: boolean; ends?: PartEnds; kind?: PartKind }): string {
400
+ return moleculeOf(part.sequence.replace(/\s+/g, ""), part.circular === true, part.ends, part.kind ?? "dna").checksum;
401
+ }
402
+
333
403
  /** Whether something is a list of features that lie within a part of a given length. */
334
404
  function areFeatures(value: unknown, length: number): value is PartFeature[] {
335
405
  if (!Array.isArray(value) || value.length > MOST_FEATURES) return false;
@@ -365,10 +435,11 @@ const KNOWN: Readonly<Record<string, Readonly<Record<string, Known>>>> = {
365
435
  "roster.add": { key: true, person: true, role: true },
366
436
  "roster.remove": { key: true, cutoff: true },
367
437
  "roster.role": { key: true, role: true },
368
- "part.add": { sequence: true, circular: true, name: true, ends: { left: true, right: true } },
438
+ "part.add": { sequence: true, circular: true, name: true, kind: true, ends: { left: true, right: true } },
369
439
  "part.annotate": { part: true, features: [{ type: true, label: true, strand: true, parts: [{ start: true, end: true }] }] },
370
440
  "part.offer": { part: true, available: true },
371
- "item.add": { item: true, part: true, amount: true, unit: true },
441
+ "item.add": { item: true, part: true, strain: true, amount: true, unit: true },
442
+ "strain.add": { strain: true, name: true, host: true, carries: true, parent: true, from: true },
372
443
  "item.adjust": { item: true, by: true },
373
444
  "item.recount": { item: true, amount: true },
374
445
  "item.retire": { item: true },
@@ -550,7 +621,7 @@ const hadSeen = (later: Node, earlier: Node): boolean => (later.vc.get(earlier.a
550
621
  * ```
551
622
  */
552
623
  export async function mergeLog(entries: readonly unknown[], options: { lab?: string } = {}): Promise<LabState> {
553
- const state: LabState = { lab: options.lab ?? null, name: null, roster: [], parts: [], items: [], places: [], crowded: [], runs: [], plans: [], entries: [],
624
+ const state: LabState = { lab: options.lab ?? null, name: null, roster: [], parts: [], items: [], places: [], crowded: [], runs: [], plans: [], strains: [], entries: [],
554
625
  waiting: [], discarded: [], overlaps: [], heads: {}, knows: {} };
555
626
 
556
627
  // Read and check every entry on its own, before any of them is believed about the others.
@@ -814,6 +885,7 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
814
885
  };
815
886
 
816
887
  const places = new Map<string, { place: PlaceState; set: Map<string, Register> }>();
888
+ const strains = new Map<string, { strain: StrainState; set: Map<string, Register> }>();
817
889
  /** Each plan, with the entry that settled it, if one has. */
818
890
  const plans = new Map<string, { plan: PlanState; settled: Node | null }>();
819
891
  /** Where each item was last put. */
@@ -833,17 +905,20 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
833
905
  }
834
906
  // Both the molecule and its checksum are worked out inside the guard: an entry from another
835
907
  // machine must never be able to stop the merge, only to be refused by it.
908
+ const kind = op["kind"] === undefined ? "dna" : op["kind"];
909
+ if (kind !== "dna" && kind !== "protein") { refuse("A part is made of dna or of protein."); continue; }
836
910
  let molecule: ReturnType<typeof moleculeOf>;
837
911
  try {
838
- molecule = moleculeOf(op["sequence"], op["circular"], op["ends"]);
912
+ molecule = moleculeOf(op["sequence"], op["circular"], op["ends"], kind);
839
913
  } catch {
840
- refuse("What it carries is not a sequence, with ends a molecule of that length can have.");
914
+ refuse(kind === "protein" ? "What it carries is not a protein: a protein is written in amino acids, is not a circle and has no ends."
915
+ : "What it carries is not a sequence, with ends a molecule of that length can have.");
841
916
  continue;
842
917
  }
843
918
  const checksum = molecule.checksum;
844
919
  if (!parts.has(checksum)) {
845
920
  parts.set(checksum, {
846
- part: { checksum, sequence: op["sequence"], circular: op["circular"], length: molecule.length,
921
+ part: { checksum, kind, sequence: op["sequence"], circular: op["circular"], length: molecule.length,
847
922
  name: op["name"], offered: false, features: [], ends: molecule.ends, fields: {}, added: node.id },
848
923
  set: new Map([["name", { node, value: op["name"] }]]),
849
924
  });
@@ -870,11 +945,16 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
870
945
  refuse("It does not carry an item ID, a whole starting amount and a unit.");
871
946
  } else if (items.has(op["item"])) {
872
947
  refuse("An item with that ID already exists.");
873
- } else if (typeof op["part"] !== "string" || !parts.has(op["part"])) {
948
+ } else if ((op["part"] === undefined) === (op["strain"] === undefined)) {
949
+ refuse("An item is of a part or a culture of a strain, and not both.");
950
+ } else if (op["part"] !== undefined && (typeof op["part"] !== "string" || !parts.has(op["part"]))) {
874
951
  refuse("The part it is an item of is not one the lab has.");
952
+ } else if (op["strain"] !== undefined && (typeof op["strain"] !== "string" || !strains.has(op["strain"]))) {
953
+ refuse("The strain it is a culture of is not one the lab has.");
875
954
  } else {
876
955
  items.set(op["item"], {
877
- item: { item: op["item"], part: op["part"], unit: op["unit"], amount: 0, retired: false, needsRecount: false, from: null, where: null, fields: {}, added: node.id },
956
+ item: { item: op["item"], part: (op["part"] as string | undefined) ?? null, strain: (op["strain"] as string | undefined) ?? null,
957
+ unit: op["unit"], amount: 0, retired: false, needsRecount: false, from: null, where: null, fields: {}, added: node.id },
878
958
  set: new Map(), base: { node, amount: op["amount"], recount: false }, adjusted: [], overlapped: false,
879
959
  });
880
960
  }
@@ -969,12 +1049,12 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
969
1049
  for (const { output, record, checksum, ends } of made) {
970
1050
  if (!parts.has(checksum)) {
971
1051
  parts.set(checksum, {
972
- part: { checksum, sequence: output.sequence, circular: output.circular, length: record.length, name: output.name, offered: false, features: [], ends, fields: {}, added: node.id },
1052
+ part: { checksum, kind: "dna", sequence: output.sequence, circular: output.circular, length: record.length, name: output.name, offered: false, features: [], ends, fields: {}, added: node.id },
973
1053
  set: new Map([["name", { node, value: output.name }]]),
974
1054
  });
975
1055
  }
976
1056
  items.set(output.item, {
977
- item: { item: output.item, part: checksum, unit: output.unit, amount: 0, retired: false, needsRecount: false, from: op["run"] as string,
1057
+ item: { item: output.item, part: checksum, strain: null, unit: output.unit, amount: 0, retired: false, needsRecount: false, from: op["run"] as string,
978
1058
  where: null, fields: {}, added: node.id },
979
1059
  set: new Map(), base: { node, amount: output.amount, recount: false }, adjusted: [], overlapped: false,
980
1060
  });
@@ -986,6 +1066,25 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
986
1066
  settings: { ...(op["settings"] as Record<string, string | number>) }, outcome: op["outcome"] as "worked" | "failed",
987
1067
  note: op["note"] as string | null, added: node.id,
988
1068
  });
1069
+ } else if (op.type === "strain.add") {
1070
+ const carries = op["carries"];
1071
+ if (!(typeof op["strain"] === "string" && ITEM_ID.test(op["strain"])) || !text(op["name"], 200) || !text(op["host"], 200)) {
1072
+ refuse("It does not carry a strain ID, what to call it and what organism it is.");
1073
+ } else if (strains.has(op["strain"])) {
1074
+ refuse("A strain with that ID already exists.");
1075
+ } else if (!Array.isArray(carries) || carries.length > MOST_IN_A_RUN || !carries.every((one) => typeof one === "string" && parts.has(one))) {
1076
+ refuse("What it says the strain carries is not a list of parts the lab has.");
1077
+ } else if (!(op["parent"] === null || (typeof op["parent"] === "string" && strains.has(op["parent"])))) {
1078
+ refuse("The strain it says this one came from is not one the lab has.");
1079
+ } else if (!(op["from"] === null || (typeof op["from"] === "string" && state.runs.some((one) => one.run === op["from"])))) {
1080
+ refuse("The run it says made this strain is not one the lab has.");
1081
+ } else {
1082
+ strains.set(op["strain"], {
1083
+ strain: { strain: op["strain"], name: op["name"], host: op["host"], carries: [...new Set(carries as string[])],
1084
+ parent: op["parent"] as string | null, from: op["from"] as string | null, fields: {}, added: node.id },
1085
+ set: new Map([["name", { node, value: op["name"] }]]),
1086
+ });
1087
+ }
989
1088
  } else if (op.type === "plan.add") {
990
1089
  const problem = planProblem(op, items, parts, places, plans);
991
1090
  if (problem !== null) { refuse(problem); continue; }
@@ -1029,10 +1128,12 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
1029
1128
  const value = op["value"];
1030
1129
  const target = op["on"] === "part" && typeof op["id"] === "string" ? parts.get(op["id"])
1031
1130
  : op["on"] === "item" && typeof op["id"] === "string" ? items.get(op["id"])
1032
- : op["on"] === "place" && typeof op["id"] === "string" ? places.get(op["id"]) : undefined;
1033
- if (target === undefined) { refuse("It does not name a part, an item or a place the lab has."); continue; }
1131
+ : op["on"] === "place" && typeof op["id"] === "string" ? places.get(op["id"])
1132
+ : op["on"] === "strain" && typeof op["id"] === "string" ? strains.get(op["id"]) : undefined;
1133
+ if (target === undefined) { refuse("It does not name a part, an item, a place or a strain the lab has."); continue; }
1034
1134
  if (op["on"] === "place" && typeof field === "string" && PLACE_RESERVED.has(field)) { refuse("It does not name a field that can be set."); continue; }
1035
- if (field === "name" && op["on"] === "place" && !text(value, 200)) { refuse("A place's name has to be some text."); continue; }
1135
+ if (op["on"] === "strain" && typeof field === "string" && STRAIN_RESERVED.has(field)) { refuse("It does not name a field that can be set."); continue; }
1136
+ if (field === "name" && (op["on"] === "place" || op["on"] === "strain") && !text(value, 200)) { refuse("A name has to be some text."); continue; }
1036
1137
  if (typeof field !== "string" || !FIELD.test(field) || RESERVED.has(field)) { refuse("It does not name a field that can be set."); continue; }
1037
1138
  if (!(value === null || amountOf(value) || (typeof value === "string" && value.length <= 2_000))) { refuse("Its value is not text, a whole number or nothing."); continue; }
1038
1139
  if (field === "name" && op["on"] === "part" && !text(value, 200)) { refuse("A part's name has to be some text."); continue; }
@@ -1052,6 +1153,13 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
1052
1153
  }
1053
1154
  state.parts.push(part);
1054
1155
  }
1156
+ for (const { strain, set } of strains.values()) {
1157
+ for (const [field, held] of set) {
1158
+ if (field === "name") strain.name = held.value as string;
1159
+ else strain.fields[field] = held.value as string | number | null;
1160
+ }
1161
+ state.strains.push(strain);
1162
+ }
1055
1163
  for (const { item, set, base, adjusted, overlapped } of items.values()) {
1056
1164
  // A recount replaces the adjustments its author had seen. Everything else still counts.
1057
1165
  const since = adjusted.filter((one) => !hadSeen(base.node, one.node)).reduce((sum, one) => sum + one.by, 0);