@biolibs/bionet-tools 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +146 -4
  2. package/dist/digest-bench.d.ts +76 -0
  3. package/dist/digest-bench.d.ts.map +1 -0
  4. package/dist/digest-bench.js +127 -0
  5. package/dist/digest-bench.js.map +1 -0
  6. package/dist/digest-working.d.ts +155 -0
  7. package/dist/digest-working.d.ts.map +1 -0
  8. package/dist/digest-working.js +216 -0
  9. package/dist/digest-working.js.map +1 -0
  10. package/dist/index.d.ts +20 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +20 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/ligate-bench.d.ts +92 -0
  15. package/dist/ligate-bench.d.ts.map +1 -0
  16. package/dist/ligate-bench.js +139 -0
  17. package/dist/ligate-bench.js.map +1 -0
  18. package/dist/ligate-working.d.ts +96 -0
  19. package/dist/ligate-working.d.ts.map +1 -0
  20. package/dist/ligate-working.js +145 -0
  21. package/dist/ligate-working.js.map +1 -0
  22. package/dist/ligate.d.ts +152 -0
  23. package/dist/ligate.d.ts.map +1 -0
  24. package/dist/ligate.js +161 -0
  25. package/dist/ligate.js.map +1 -0
  26. package/dist/map.d.ts +69 -0
  27. package/dist/map.d.ts.map +1 -0
  28. package/dist/map.js +80 -0
  29. package/dist/map.js.map +1 -0
  30. package/dist/pcr-bench.d.ts +9 -0
  31. package/dist/pcr-bench.d.ts.map +1 -1
  32. package/dist/pcr-bench.js +26 -2
  33. package/dist/pcr-bench.js.map +1 -1
  34. package/dist/pcr-scene.d.ts +2 -0
  35. package/dist/pcr-scene.d.ts.map +1 -1
  36. package/dist/pcr-scene.js +8 -8
  37. package/dist/pcr-scene.js.map +1 -1
  38. package/dist/pcr-working.d.ts +126 -0
  39. package/dist/pcr-working.d.ts.map +1 -0
  40. package/dist/pcr-working.js +175 -0
  41. package/dist/pcr-working.js.map +1 -0
  42. package/dist/run.d.ts +101 -6
  43. package/dist/run.d.ts.map +1 -1
  44. package/dist/run.js +127 -11
  45. package/dist/run.js.map +1 -1
  46. package/dist/sequence-file.d.ts +108 -0
  47. package/dist/sequence-file.d.ts.map +1 -0
  48. package/dist/sequence-file.js +145 -0
  49. package/dist/sequence-file.js.map +1 -0
  50. package/dist/sequences-tool.d.ts +13 -0
  51. package/dist/sequences-tool.d.ts.map +1 -0
  52. package/dist/sequences-tool.js +61 -0
  53. package/dist/sequences-tool.js.map +1 -0
  54. package/dist/tools.d.ts +2 -2
  55. package/dist/tools.d.ts.map +1 -1
  56. package/dist/tools.js +9 -4
  57. package/dist/tools.js.map +1 -1
  58. package/dist/working.d.ts +58 -0
  59. package/dist/working.d.ts.map +1 -0
  60. package/dist/working.js +55 -0
  61. package/dist/working.js.map +1 -0
  62. package/package.json +5 -2
  63. package/src/digest-bench.tsx +307 -0
  64. package/src/digest-working.ts +288 -0
  65. package/src/index.ts +20 -0
  66. package/src/ligate-bench.tsx +293 -0
  67. package/src/ligate-working.ts +182 -0
  68. package/src/ligate.ts +243 -0
  69. package/src/map.tsx +170 -0
  70. package/src/pcr-bench.tsx +54 -1
  71. package/src/pcr-scene.ts +10 -8
  72. package/src/pcr-working.ts +228 -0
  73. package/src/run.ts +179 -14
  74. package/src/sequence-file.ts +172 -0
  75. package/src/sequences-tool.tsx +109 -0
  76. package/src/tools.tsx +13 -8
  77. package/src/working.tsx +96 -0
  78. package/tools.css +54 -0
@@ -0,0 +1,182 @@
1
+ /**
2
+ * A ligation's working: what each join is made of, where the product's length comes from, how much
3
+ * of each piece to put in, and what a careful person would ask before setting one up.
4
+ *
5
+ * Which ends fit is exact, and shown down to the bases. How much of each piece to use is arithmetic
6
+ * on a convention. Whether it will work at all is neither: it is what the checks are for.
7
+ */
8
+ import type { LigationPiece, LigationPlan, LigationProduct, PieceEndBases } from "./ligate.js";
9
+ import { endBases, endsFit } from "./ligate.js";
10
+ import type { Working } from "./pcr-working.js";
11
+
12
+ const count = (value: number): string => value.toLocaleString("en-US");
13
+ const PAIR: Readonly<Record<string, string>> = { A: "T", T: "A", G: "C", C: "G", N: "N" };
14
+
15
+ /** Two ends written one over the other, to show that they pair. */
16
+ export interface JoinOverhangs {
17
+ /** The piece on the left of the join, and the one on the right. */
18
+ from: string;
19
+ to: string;
20
+ /** The overhang on the left-hand piece, 5′ to 3′ on the strand that carries it. */
21
+ left: string;
22
+ /** The right-hand piece's, written under it so each base sits beneath the one it pairs with. */
23
+ right: string;
24
+ /** Whether it is a 5′ overhang, a 3′ one, or two blunt ends. */
25
+ kind: "5′" | "3′" | "blunt";
26
+ }
27
+
28
+ /**
29
+ * One join, said as steps that can be checked against the bases.
30
+ *
31
+ * @param from - The piece on the left of the join, and which of its ends this is.
32
+ * @param to - The piece on the right, and which of its ends.
33
+ * @returns The working, with the two overhangs written one over the other.
34
+ */
35
+ export function joinWorking(from: { name: string; end: PieceEndBases }, to: { name: string; end: PieceEndBases }): Working & { bases: JoinOverhangs } {
36
+ const fit = endsFit(from.end, to.end);
37
+ const under = [...from.end.bases].map((base) => PAIR[base] ?? "N").join("");
38
+ const bases: JoinOverhangs = { from: from.name, to: to.name, left: from.end.bases, right: [...to.end.bases].reverse().join(""), kind: fit?.kind ?? from.end.kind };
39
+ if (fit === null) {
40
+ return {
41
+ of: `${from.name} to ${to.name}`, comes: "they do not fit", kind: "exact", bases,
42
+ steps: [
43
+ `${from.name}'s end is ${from.end.kind === "blunt" ? "blunt" : `a ${from.end.kind} overhang, ${from.end.bases}`}.`,
44
+ `${to.name}'s is ${to.end.kind === "blunt" ? "blunt" : `a ${to.end.kind} overhang, ${to.end.bases}`}.`,
45
+ from.end.kind !== to.end.kind ? "A sticky end and a blunt one have nothing to pair, so ligase cannot join them."
46
+ : from.end.bases.length !== to.end.bases.length ? `One overhang is ${from.end.bases.length} bases and the other ${to.end.bases.length}. They have to be the same length.`
47
+ : `${from.end.bases} would have to meet ${under} to pair, and it meets ${[...to.end.bases].reverse().join("")}.`,
48
+ ],
49
+ };
50
+ }
51
+ if (fit.kind === "blunt") {
52
+ return {
53
+ of: `${from.name} to ${to.name}`, comes: "a blunt join", kind: "exact", bases,
54
+ steps: ["Both ends are blunt: every base is already paired with one opposite.",
55
+ "Ligase seals the backbone without anything having to find anything, so these two ends join, and so would any other two blunt ends in the tube."],
56
+ };
57
+ }
58
+ return {
59
+ of: `${from.name} to ${to.name}`, comes: `${fit.bases.length} bases, ${fit.bases}`, kind: "exact", bases,
60
+ steps: [
61
+ `${from.name} ends in a ${fit.kind} overhang of ${fit.bases.length} unpaired bases, ${fit.bases}.`,
62
+ `${to.name} begins with ${[...to.end.bases].reverse().join("")} read the other way, which is ${under}: each base is the partner of the one above it.`,
63
+ "So the two ends hold together while ligase seals the backbone on each strand.",
64
+ ],
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Where a product's length comes from: the pieces, less the overhangs they share.
70
+ *
71
+ * @param product - The product.
72
+ * @param pieces - The pieces that went in, for their full lengths.
73
+ * @returns The working.
74
+ */
75
+ export function ligationLengthWorking(product: LigationProduct, pieces: readonly LigationPiece[]): Working {
76
+ const lengthOf = (id: string): number => pieces.find((piece) => piece.id === id)?.sequence.replace(/\s+/g, "").length ?? 0;
77
+ const total = product.pieces.reduce((sum, piece) => sum + lengthOf(piece.id), 0);
78
+ const shared = product.joins.reduce((sum, join) => sum + join.bases.length, 0);
79
+ return {
80
+ of: "the product's length", comes: `${count(product.length)} bp`, kind: "exact",
81
+ steps: [
82
+ `The pieces are ${product.pieces.map((piece) => `${piece.name} ${count(lengthOf(piece.id))}`).join(", ")}: ${count(total)} bases in all.`,
83
+ shared === 0 ? "They are joined blunt, so nothing is shared between them."
84
+ : `Each join's overhang belongs to both pieces at once, so it is counted once: ${product.joins.map((join) => String(join.bases.length)).join(" + ")} = ${shared}.`,
85
+ `${count(total)} − ${count(shared)} = ${count(product.length)}${product.circular ? ", closed into a circle." : "."}`,
86
+ ],
87
+ };
88
+ }
89
+
90
+ /**
91
+ * How much of each piece to put in the tube.
92
+ *
93
+ * @param vector - The piece being cloned into, by name and length.
94
+ * @param insert - The piece going in.
95
+ * @param options - `ratio` is how many times more insert than vector, by molecule, and `ng` how
96
+ * much of the vector is used.
97
+ * @returns The working.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import { ratioWorking } from "@biolibs/bionet-tools";
102
+ *
103
+ * ratioWorking({ name: "vector", length: 3000 }, { name: "insert", length: 600 }).comes; // "30 ng of insert"
104
+ * ```
105
+ */
106
+ export function ratioWorking(vector: { name: string; length: number }, insert: { name: string; length: number },
107
+ options: { ratio?: number; ng?: number } = {}): Working {
108
+ const ratio = options.ratio === undefined || options.ratio <= 0 ? 3 : options.ratio;
109
+ const ng = options.ng === undefined || options.ng <= 0 ? 50 : options.ng;
110
+ const wanted = ng * (insert.length / vector.length) * ratio;
111
+ const round = (value: number): string => String(Math.round(value * 100) / 100);
112
+ return {
113
+ of: `how much ${insert.name} to put in`, comes: `${round(wanted)} ng of insert`, kind: "estimate",
114
+ steps: [
115
+ `A molecule of ${insert.name} is ${count(insert.length)} bases and one of ${vector.name} is ${count(vector.length)}, so the same weight holds ${round(vector.length / insert.length)} times as many molecules of the insert.`,
116
+ `For ${ratio} molecules of insert to each of vector: ${ng} ng × ${count(insert.length)} ÷ ${count(vector.length)} × ${ratio} = ${round(wanted)} ng.`,
117
+ ],
118
+ rests: "Three insert molecules to one of vector is the usual starting point, and the weight is worked out from length because a longer molecule weighs more. It assumes both preparations are what they say they are and that nothing has degraded, so it is where to start rather than a measurement.",
119
+ };
120
+ }
121
+
122
+ /** Something a careful person would ask before setting a ligation up. */
123
+ export interface LigationCheck {
124
+ /** `stop` if what is hoped for is unlikely as set up, `look` if it is only worth a second glance. */
125
+ weight: "stop" | "look";
126
+ /** What to ask, said for a person. */
127
+ says: string;
128
+ /** What raised it, so it can be checked. */
129
+ because: string;
130
+ }
131
+
132
+ /**
133
+ * What a careful person would ask of a ligation.
134
+ *
135
+ * These are the ways a ligation gives something other than what was wanted: a vector that closes on
136
+ * itself, an insert that can go in either way round, pieces that can join each other instead, a
137
+ * blunt join that will mostly not happen, and a PCR product whose ends ligase cannot seal.
138
+ *
139
+ * @param pieces - The pieces in the tube.
140
+ * @param plan - What they would make.
141
+ * @param options - `fromPcr` names pieces that came out of a PCR, which have no phosphate at their 5′ ends.
142
+ * @returns The checks that apply, the ones most likely to matter first.
143
+ */
144
+ export function ligationChecks(pieces: readonly LigationPiece[], plan: LigationPlan,
145
+ options: { fromPcr?: readonly string[] } = {}): LigationCheck[] {
146
+ const checks: LigationCheck[] = [];
147
+ const wanted = plan.products.filter((product) => product.circular);
148
+ for (const piece of pieces) {
149
+ const ends = endBases(piece);
150
+ const fit = endsFit(ends.right, ends.left);
151
+ if (fit !== null && pieces.length > 1) {
152
+ checks.push({ weight: "stop", says: `${piece.name}'s two ends fit each other, so it can close on itself and give a colony with nothing in it. Cut with two different enzymes, or take the phosphate off its ends so only the insert can seal them.`,
153
+ because: fit.kind === "blunt" ? "both ends blunt" : `${ends.right.bases} meets ${ends.left.bases}` });
154
+ }
155
+ }
156
+ // The same pieces in the same order, differing only in which way round one went, is the thing a
157
+ // bench cannot tell apart without cutting the result.
158
+ const byShape = new Map<string, LigationProduct[]>();
159
+ for (const product of wanted) {
160
+ const shape = [...product.pieces].map((piece) => piece.id).sort().join("+");
161
+ byShape.set(shape, [...(byShape.get(shape) ?? []), product]);
162
+ }
163
+ for (const [, together] of byShape) {
164
+ if (together.length < 2) continue;
165
+ const turned = together.flatMap((product) => product.pieces.filter((piece) => piece.flipped).map((piece) => piece.name));
166
+ checks.push({ weight: "look", says: `These pieces make ${together.length} products that hold the same things${turned.length === 0 ? "" : `, with ${[...new Set(turned)].join(" and ")} the other way round`}. Both will be in the tube, and a check digest is what tells one from the other.`,
167
+ because: `${together.length} circles of ${together[0]!.pieces.length} pieces` });
168
+ }
169
+ if (wanted.some((product) => product.joins.some((join) => join.kind === "blunt"))) {
170
+ checks.push({ weight: "look", says: "A blunt join has nothing holding the two ends together while ligase works, so it happens far less often than a sticky one. Allow more ligase, more DNA and longer, and expect fewer colonies.", because: "a blunt join" });
171
+ }
172
+ const pcr = (options.fromPcr ?? []).filter((id) => pieces.some((piece) => piece.id === id));
173
+ if (pcr.length > 0) {
174
+ const named = pcr.map((id) => pieces.find((piece) => piece.id === id)!.name);
175
+ checks.push({ weight: "stop", says: `${named.join(" and ")} came out of a PCR, and a PCR product has no phosphate at its 5′ ends. Ligase seals a backbone by joining a phosphate to a hydroxyl, so there is nothing for it to join until the ends are phosphorylated.`,
176
+ because: "made by pcr" });
177
+ }
178
+ if (wanted.length === 0 && plan.products.length > 0) {
179
+ checks.push({ weight: "stop", says: "Nothing here closes into a circle. The pieces join end to end and stop, which is not something that can be grown.", because: "no circular product" });
180
+ }
181
+ return checks.sort((a, b) => Number(b.weight === "stop") - Number(a.weight === "stop"));
182
+ }
package/src/ligate.ts ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * A ligation: pieces that have already been cut, joined where their ends fit.
3
+ *
4
+ * This is the step after a digest. Each piece carries a few unpaired bases at each end, and ligase
5
+ * joins two ends only where those bases pair. Which pieces can go together, in what order and which
6
+ * way round, follows from the ends alone — so it is worked out here, from sequences, knowing nothing
7
+ * of the lab.
8
+ *
9
+ * The joining itself is `@biolibs/assembly2`'s. What this adds is what a bench needs to read: where
10
+ * each piece sits in the product, which way round it went, what each join is made of, and what the
11
+ * product carries from the pieces that made it.
12
+ */
13
+ import type { PartFeature } from "@biolibs/bionet";
14
+ import { ligationAssembly } from "@biolibs/assembly2";
15
+ import { Dseq } from "@biolibs/dseq";
16
+ import { Dseqrecord } from "@biolibs/dseqrecord";
17
+
18
+ /** What one end of a piece is like. */
19
+ export interface PieceEndBases {
20
+ /** `5′` or `3′` for an overhang, `blunt` for an end with no unpaired bases. */
21
+ kind: "5′" | "3′" | "blunt";
22
+ /** The unpaired bases, as the strand carrying them reads 5′ to 3′. Empty for a blunt end. */
23
+ bases: string;
24
+ }
25
+
26
+ /** A piece going into a ligation: a part the lab holds, as this needs it. */
27
+ export interface LigationPiece {
28
+ /** What tells it apart from the others here, such as an item's ID. */
29
+ id: string;
30
+ /** What it is called. */
31
+ name: string;
32
+ /** Every base either strand has, read along the top strand. */
33
+ sequence: string;
34
+ /** How many bases at each end are on one strand only: positive for a 5′ overhang, negative for a 3′ one. */
35
+ ends: { left: number; right: number };
36
+ /** What is marked on it. */
37
+ features?: readonly PartFeature[];
38
+ }
39
+
40
+ /** Where one piece sits in a product. */
41
+ export interface PlacedPiece {
42
+ /** Which piece. */
43
+ id: string;
44
+ name: string;
45
+ /** Whether it went in the other way round. */
46
+ flipped: boolean;
47
+ /** Where its first base is in the product. */
48
+ at: number;
49
+ /** How many of the product's bases are its own, not shared with the piece before it. */
50
+ length: number;
51
+ }
52
+
53
+ /** One join in a product: two ends that fitted. */
54
+ export interface LigationJoin {
55
+ /** The piece whose right-hand end this is, and the piece whose left-hand end it is. */
56
+ from: string;
57
+ to: string;
58
+ /** What kind of ends they were. */
59
+ kind: "5′" | "3′" | "blunt";
60
+ /** The bases the two ends shared. Empty for a blunt join. */
61
+ bases: string;
62
+ /** Where the join falls in the product: the number of bases before it. */
63
+ at: number;
64
+ }
65
+
66
+ /** One thing a ligation would make. */
67
+ export interface LigationProduct {
68
+ /** Its bases. */
69
+ sequence: string;
70
+ /** Whether it is a circle. */
71
+ circular: boolean;
72
+ /** How long it is. */
73
+ length: number;
74
+ /** The pieces, in the order they go round or along it. */
75
+ pieces: PlacedPiece[];
76
+ /** The joins, in the same order. A circle has one for each piece; a line has one fewer. */
77
+ joins: LigationJoin[];
78
+ /** What is marked on it: each piece's features, moved to where that piece now is. */
79
+ features: PartFeature[];
80
+ }
81
+
82
+ /** What a ligation would make. */
83
+ export interface LigationPlan {
84
+ /** What it would make, the circles first and the shortest first within that. */
85
+ products: LigationProduct[];
86
+ /** Why there is nothing to look at, said for a person, or `null` if there is something. */
87
+ problem: string | null;
88
+ }
89
+
90
+ const clean = (bases: string): string => bases.replace(/\s+/g, "").toUpperCase();
91
+ const PAIR: Readonly<Record<string, string>> = { A: "T", T: "A", G: "C", C: "G", N: "N" };
92
+ const flipBases = (bases: string): string => [...bases].reverse().map((base) => PAIR[base] ?? "N").join("");
93
+
94
+ /**
95
+ * A piece as a molecule with its ends.
96
+ *
97
+ * @param piece - The piece.
98
+ * @returns The molecule, with the unpaired bases at each end left unpaired.
99
+ * @throws If that is not a sequence, or the ends are longer than the piece.
100
+ */
101
+ export function pieceRecord(piece: LigationPiece): Dseqrecord {
102
+ const bases = clean(piece.sequence);
103
+ const { left, right } = piece.ends;
104
+ if (Math.abs(left) + Math.abs(right) >= bases.length) throw new Error("The ends are longer than the piece.");
105
+ return new Dseqrecord(Dseq.fromFullSequenceAndOverhangs(bases, -left, -right), false, undefined, piece.id, piece.name);
106
+ }
107
+
108
+ /**
109
+ * What a piece's two ends are made of.
110
+ *
111
+ * The number on a part says how many bases at that end are on one strand only. Which strand carries
112
+ * them is what makes it a 5′ or a 3′ overhang: at the left-hand end a 5′ overhang is on the top
113
+ * strand, and at the right-hand end it is on the bottom one.
114
+ *
115
+ * @param piece - The piece.
116
+ * @returns Its left and right ends, each with the unpaired bases as the strand carrying them reads them.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * import { endBases } from "@biolibs/bionet-tools";
121
+ *
122
+ * endBases({ id: "1", name: "insert", sequence: "AATTCGGGGGGGGGGGATC", ends: { left: 4, right: 4 } });
123
+ * // { left: { kind: "5′", bases: "AATT" }, right: { kind: "5′", bases: "GATC" } }
124
+ * ```
125
+ */
126
+ export function endBases(piece: LigationPiece): { left: PieceEndBases; right: PieceEndBases } {
127
+ const bases = clean(piece.sequence);
128
+ const { left, right } = piece.ends;
129
+ const blunt: PieceEndBases = { kind: "blunt", bases: "" };
130
+ return {
131
+ // A 5′ overhang on the left is the top strand's own first bases; a 3′ one is the bottom strand's,
132
+ // which read 5′ to 3′ the other way.
133
+ left: left === 0 ? blunt : left > 0 ? { kind: "5′", bases: bases.slice(0, left) } : { kind: "3′", bases: flipBases(bases.slice(0, -left)) },
134
+ // At the right-hand end it is the other way about: a 5′ overhang is the bottom strand's, read back.
135
+ right: right === 0 ? blunt : right > 0 ? { kind: "5′", bases: flipBases(bases.slice(-right)) } : { kind: "3′", bases: bases.slice(right) },
136
+ };
137
+ }
138
+
139
+ /**
140
+ * Whether one piece's right-hand end joins another's left-hand end.
141
+ *
142
+ * Ligase joins two ends when the unpaired bases of one pair with those of the other, which means
143
+ * the same kind of overhang, the same length, and bases that are each other's partners. Two blunt
144
+ * ends join with nothing in common, which is why a blunt ligation needs no matching at all and is
145
+ * the harder one to get.
146
+ *
147
+ * @param from - The end on the left of the join.
148
+ * @param to - The end on the right of it.
149
+ * @returns What the two share, or `null` if they do not fit.
150
+ */
151
+ export function endsFit(from: PieceEndBases, to: PieceEndBases): { kind: "5′" | "3′" | "blunt"; bases: string } | null {
152
+ if (from.kind === "blunt" && to.kind === "blunt") return { kind: "blunt", bases: "" };
153
+ if (from.kind === "blunt" || to.kind === "blunt" || from.kind !== to.kind) return null;
154
+ // Both overhangs are written 5′ to 3′ on their own strand, so they fit when one is the other's partner.
155
+ return from.bases.length === to.bases.length && flipBases(from.bases) === to.bases ? { kind: from.kind, bases: from.bases } : null;
156
+ }
157
+
158
+ /** A feature turned round, for a piece that went in the other way. */
159
+ const flipFeature = (feature: PartFeature, length: number): PartFeature => ({
160
+ ...feature, strand: (feature.strand === 0 ? 0 : -feature.strand) as -1 | 0 | 1,
161
+ parts: feature.parts.map((piece) => ({ start: length - piece.end, end: length - piece.start })).reverse(),
162
+ });
163
+
164
+ /**
165
+ * Work out what a ligation would make.
166
+ *
167
+ * @param pieces - The pieces in the tube.
168
+ * @param options - `blunt` allows two blunt ends to be joined; `linear` keeps the products that did
169
+ * not close into a circle, which are the background a bench usually ignores.
170
+ * @returns What it would make, and what is wrong if it would make nothing.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * import { planLigation } from "@biolibs/bionet-tools";
175
+ *
176
+ * const plan = planLigation([vector, insert]);
177
+ * plan.products[0].circular; // true
178
+ * plan.products[0].pieces.length; // 2
179
+ * plan.products[0].joins[0].bases; // "GATC"
180
+ * ```
181
+ */
182
+ export function planLigation(pieces: readonly LigationPiece[], options: { blunt?: boolean; linear?: boolean } = {}): LigationPlan {
183
+ const empty = { products: [] };
184
+ if (pieces.length === 0) return { ...empty, problem: "Choose the pieces to join." };
185
+ let records: Dseqrecord[];
186
+ try {
187
+ records = pieces.map((piece) => pieceRecord(piece));
188
+ } catch {
189
+ return { ...empty, problem: "One of those is not a piece with ends a molecule of that length could have." };
190
+ }
191
+ let made: Dseqrecord[] = [];
192
+ try {
193
+ made = ligationAssembly(records, options.blunt === true, false, options.linear !== true);
194
+ } catch {
195
+ return { ...empty, problem: "Those pieces could not be joined." };
196
+ }
197
+ const byId = new Map(pieces.map((piece) => [piece.id, piece]));
198
+ const products = made.flatMap((product): LigationProduct[] => {
199
+ const input = (product.source as { input?: { sequence?: { id?: string | null }; reverseComplemented?: boolean }[] } | undefined)?.input ?? [];
200
+ const order = input.map((one) => ({ piece: byId.get(String(one.sequence?.id ?? "")), flipped: one.reverseComplemented === true }));
201
+ if (order.some((one) => one.piece === undefined)) return [];
202
+ const sequence = String(product.seq).toUpperCase();
203
+ const length = product.length;
204
+ // Each piece keeps all of its bases except the ones it shares with the piece before it, which
205
+ // belong to the join. Walking that gives where each piece sits and where each join falls.
206
+ const joined: LigationJoin[] = [];
207
+ const placed: PlacedPiece[] = [];
208
+ // Each piece keeps all of its bases except the ones it shares with the piece before it, which
209
+ // belong to the join. So a piece's own bases start where the piece before it ended, and the
210
+ // piece itself starts the length of the shared overhang earlier.
211
+ let ends = 0;
212
+ for (const [index, { piece, flipped }] of order.entries()) {
213
+ const bases = clean(piece!.sequence);
214
+ const here = flipped ? { left: endBases(piece!).right, right: endBases(piece!).left } : endBases(piece!);
215
+ const before = order[(index - 1 + order.length) % order.length]!;
216
+ const beforeEnds = endBases(before.piece!);
217
+ const out = before.flipped ? beforeEnds.left : beforeEnds.right;
218
+ const fit = index === 0 && !product.circular ? null : endsFit(out, here.left);
219
+ const shared = index === 0 ? 0 : fit?.bases.length ?? 0;
220
+ const at = (((ends - shared) % length) + length) % length;
221
+ placed.push({ id: piece!.id, name: piece!.name, flipped, at, length: bases.length - shared });
222
+ if (fit !== null) joined.push({ from: before.piece!.id, to: piece!.id, kind: fit.kind, bases: fit.bases, at });
223
+ ends += bases.length - shared;
224
+ }
225
+ const features = order.flatMap(({ piece, flipped }, index) => {
226
+ const bases = clean(piece!.sequence);
227
+ const start = placed[index]!.at;
228
+ return (piece!.features ?? []).map((feature) => (flipped ? flipFeature(feature, bases.length) : feature))
229
+ .map((feature): PartFeature => ({
230
+ ...feature,
231
+ parts: feature.parts.map((part) => ({ start: (start + part.start) % length, end: ((start + part.end - 1) % length) + 1 })),
232
+ }))
233
+ .filter((feature) => feature.parts.every((part) => part.end > part.start && part.end <= length));
234
+ });
235
+ return [{ sequence, circular: product.circular, length, pieces: placed, joins: joined, features }];
236
+ });
237
+ products.sort((a, b) => Number(b.circular) - Number(a.circular) || a.length - b.length || a.sequence.localeCompare(b.sequence));
238
+ if (products.length === 0) {
239
+ return { ...empty, problem: pieces.length === 1 ? `${pieces[0]!.name}'s two ends do not fit each other, so it cannot close on itself.`
240
+ : "No two of those ends fit each other, so nothing would be joined." };
241
+ }
242
+ return { products, problem: null };
243
+ }
package/src/map.tsx ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * A map of a sequence: a circle for a plasmid, a line for anything else, with what is marked on it.
3
+ *
4
+ * This is the picture a lab reads a construct by. Features are drawn as arrows in lanes so that
5
+ * ones that overlap can both be seen, places where something happens (an enzyme cuts, a primer's 3′
6
+ * end sits) are marked and named, and stretches worth pointing at, such as where a primer binds, are
7
+ * drawn on the backbone. The geometry is `@biolibs/seqmap`'s; this draws it.
8
+ */
9
+ import type { PartFeature } from "@biolibs/bionet";
10
+ import { angleAt, blockPath, fractionAt, packLanes, polar, ringPath, splitAtOrigin, spreadApart, spreadAround, tickLabel, tickPositions, tickStep } from "@biolibs/seqmap";
11
+ import { featureTone } from "./sequence-file.js";
12
+
13
+ /** A place on a sequence where something happens, with what to call it. */
14
+ export interface MapMark {
15
+ /** Where: the number of bases before it. */
16
+ at: number;
17
+ /** What to write beside it. */
18
+ label: string;
19
+ }
20
+
21
+ /** A stretch of a sequence to point at, such as where a primer binds. */
22
+ export interface MapSpan {
23
+ start: number;
24
+ end: number;
25
+ /** What to call it. */
26
+ label: string;
27
+ /** Which way it points, if it points: 1 rightwards or clockwise, -1 the other way. */
28
+ strand?: -1 | 0 | 1;
29
+ }
30
+
31
+ /** One drawable piece of a feature, with the lane it sits in. */
32
+ export interface MapPiece {
33
+ /** Which feature it is a piece of, by its place in the list. */
34
+ index: number;
35
+ feature: PartFeature;
36
+ start: number;
37
+ end: number;
38
+ /** Which end carries the arrowhead, if this piece is the feature's leading end. */
39
+ arrow: "start" | "end" | undefined;
40
+ /** The lane it is drawn in, 0 nearest the backbone. */
41
+ lane: number;
42
+ }
43
+
44
+ /**
45
+ * Every drawable piece of every feature, each in a lane where it overlaps nothing.
46
+ *
47
+ * @param features - What is marked on the sequence.
48
+ * @param length - How long the sequence is.
49
+ * @param circular - Whether it is a circle, in which case a piece that crosses the origin is drawn as two.
50
+ * @returns The pieces. At most five lanes are used; anything deeper shares the fifth.
51
+ */
52
+ export function mapPieces(features: readonly PartFeature[], length: number, circular: boolean): MapPiece[] {
53
+ const pieces = features.flatMap((feature, index) => feature.parts
54
+ .filter((part) => part.end > part.start && part.end <= length)
55
+ .flatMap((part) => (circular ? splitAtOrigin(part, length) : [part]))
56
+ .map((part, at, all) => ({
57
+ index, feature, start: part.start, end: part.end,
58
+ // Only the piece at the feature's leading end carries the arrowhead.
59
+ arrow: feature.strand === 1 && at === all.length - 1 ? ("end" as const) : feature.strand === -1 && at === 0 ? ("start" as const) : undefined,
60
+ })));
61
+ const lanes = packLanes(pieces, Math.max(1, Math.round(length / 300)));
62
+ return pieces.map((piece, at) => ({ ...piece, lane: Math.min(lanes[at]!, 4) }));
63
+ }
64
+
65
+ const count = (value: number): string => value.toLocaleString("en-US");
66
+
67
+ /**
68
+ * A sequence's map.
69
+ *
70
+ * @param props - `name`, `length` and `circular` say what it is a map of; `features` is what is
71
+ * marked on it; `marks` are places to name, such as where an enzyme cuts; `spans` are stretches to
72
+ * point at, such as where a primer binds.
73
+ *
74
+ * @example
75
+ * ```tsx
76
+ * import { SequenceMap } from "@biolibs/bionet-tools";
77
+ *
78
+ * <SequenceMap name="pUC19" length={2686} circular features={part.features} marks={[{ at: 396, label: "EcoRI" }]} />
79
+ * ```
80
+ */
81
+ export function SequenceMap({ name, length, circular, features, marks = [], spans = [] }: {
82
+ name: string; length: number; circular: boolean; features: readonly PartFeature[]; marks?: readonly MapMark[]; spans?: readonly MapSpan[];
83
+ }) {
84
+ const pieces = mapPieces(features, length, circular);
85
+ const says = `${circular ? "Circular" : "Linear"} map of ${name}, ${count(length)} base pairs. ${features.length === 0 ? "Nothing is marked on it." : `Marked on it: ${features.map((one) => one.label).join(", ")}.`}`
86
+ + `${marks.length === 0 ? "" : ` Marked places: ${marks.map((one) => `${one.label} at ${count(one.at)}`).join(", ")}.`}${spans.length === 0 ? "" : ` ${spans.map((one) => `${one.label} at ${count(one.start + 1)} to ${count(one.end)}`).join("; ")}.`}`;
87
+ const title = (piece: MapPiece): string => `${piece.feature.label} (${piece.feature.type}), ${piece.feature.parts.map((part) => `${count(part.start + 1)}..${count(part.end)}`).join(", ")}`;
88
+
89
+ if (circular) {
90
+ const [size, radius] = [360, 118];
91
+ const c = size / 2;
92
+ const step = tickStep(length, 12);
93
+ // Names are pushed apart round the circle so that neighbouring places stay readable.
94
+ const angles = spreadAround(marks.map((mark) => angleAt(mark.at, length)), 0.14);
95
+ return (
96
+ <svg className="seqmap" viewBox={`0 0 ${size} ${size}`} role="img" aria-label={says}>
97
+ <circle cx={c} cy={c} r={radius} className="backbone" />
98
+ {tickPositions(length, step, true).map((position) => {
99
+ const [inner, outer] = [polar(c, c, radius - 4, angleAt(position, length)), polar(c, c, radius, angleAt(position, length))];
100
+ return <line key={position} x1={inner.x} y1={inner.y} x2={outer.x} y2={outer.y} className="tick" />;
101
+ })}
102
+ {pieces.map((piece, at) => {
103
+ const outer = radius - 8 - piece.lane * 13;
104
+ return <path key={at} d={ringPath(c, c, outer - 10, outer, angleAt(piece.start, length), angleAt(piece.end, length), piece.arrow ?? null)} className={`feature tone-${featureTone(piece.feature.type)}`}><title>{title(piece)}</title></path>;
105
+ })}
106
+ {spans.map((span, at) => {
107
+ const wide = span.end - span.start > length / 40;
108
+ const label = polar(c, c, radius + (wide ? 21 : 19), angleAt((span.start + span.end) / 2, length));
109
+ const side = Math.sin(angleAt((span.start + span.end) / 2, length));
110
+ return (
111
+ <g key={at}>
112
+ <path d={ringPath(c, c, radius + 3, radius + (wide ? 6 : 10), angleAt(span.start, length), angleAt(span.end, length), span.strand === 1 ? "end" : span.strand === -1 ? "start" : null)} className={wide ? "span wide" : "span"}><title>{span.label}</title></path>
113
+ <text x={label.x} y={label.y + 3.5} textAnchor={side > 0.25 ? "start" : side < -0.25 ? "end" : "middle"} className="spanned">{span.label}</text>
114
+ </g>
115
+ );
116
+ })}
117
+ {marks.map((mark, at) => {
118
+ const angle = angleAt(mark.at, length);
119
+ const [from, to, elbow, label] = [polar(c, c, radius - 3, angle), polar(c, c, radius + 12, angle), polar(c, c, radius + 22, angles[at]!), polar(c, c, radius + 27, angles[at]!)];
120
+ const side = Math.sin(angles[at]!);
121
+ return (
122
+ <g key={at}>
123
+ <polyline points={`${from.x},${from.y} ${to.x},${to.y} ${elbow.x},${elbow.y}`} className="mark" />
124
+ <text x={label.x} y={label.y + 3.5} textAnchor={side > 0.25 ? "start" : side < -0.25 ? "end" : "middle"} className="marked">{mark.label}</text>
125
+ </g>
126
+ );
127
+ })}
128
+ <text x={c} y={c - 3} textAnchor="middle" className="name">{name.length > 22 ? `${name.slice(0, 21)}…` : name}</text>
129
+ <text x={c} y={c + 14} textAnchor="middle" className="length">{count(length)} bp</text>
130
+ </svg>
131
+ );
132
+ }
133
+
134
+ const [width, left] = [640, 24];
135
+ const across = width - 2 * left;
136
+ const lanes = Math.max(1, ...pieces.map((piece) => piece.lane + 1));
137
+ const axis = 30 + lanes * 16;
138
+ const x = (position: number): number => left + fractionAt(position, length) * across;
139
+ const step = tickStep(length, 8);
140
+ const named = spreadApart(marks.map((mark) => x(mark.at)), 34, left, left + across);
141
+ return (
142
+ <svg className="seqmap linear" viewBox={`0 0 ${width} ${axis + 46}`} role="img" aria-label={says}>
143
+ {pieces.map((piece, at) => {
144
+ const bottom = axis - 8 - piece.lane * 16;
145
+ return <path key={at} d={blockPath(x(piece.start), x(piece.end), bottom - 11, bottom, piece.arrow ?? null)} className={`feature tone-${featureTone(piece.feature.type)}`}><title>{title(piece)}</title></path>;
146
+ })}
147
+ <line x1={left} x2={left + across} y1={axis} y2={axis} className="backbone" />
148
+ {spans.map((span, at) => (
149
+ <g key={at}>
150
+ <path d={blockPath(x(span.start), x(span.end), axis - 4, axis + 4, span.strand === 1 ? "end" : span.strand === -1 ? "start" : null)} className="span"><title>{span.label}</title></path>
151
+ <text x={(x(span.start) + x(span.end)) / 2} y={axis + 30} textAnchor="middle" className="spanned">{span.label}</text>
152
+ </g>
153
+ ))}
154
+ {tickPositions(length, step, false).map((position) => (
155
+ <g key={position}>
156
+ <line x1={x(position)} x2={x(position)} y1={axis} y2={axis + 5} className="tick" />
157
+ <text x={x(position)} y={axis + 17} textAnchor="middle" className="length">{tickLabel(position, step)}</text>
158
+ </g>
159
+ ))}
160
+ {marks.map((mark, at) => (
161
+ <g key={at}>
162
+ <polyline points={`${x(mark.at)},${axis - 2} ${x(mark.at)},${axis + 22} ${named[at]},${axis + 30}`} className="mark" />
163
+ <text x={named[at]!} y={axis + 41} textAnchor="middle" className="marked">{mark.label}</text>
164
+ </g>
165
+ ))}
166
+ <text x={left} y={12} className="name">{name}</text>
167
+ <text x={left + across} y={12} textAnchor="end" className="length">{count(length)} bp</text>
168
+ </svg>
169
+ );
170
+ }