@biolibs/gel 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthew Stewart
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,366 @@
1
- # Temporary Holding Version
1
+ # @biolibs/gel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A virtual gel: where a molecule of a given size would run, and which sizes a gel would tell apart.
4
+ Agarose for DNA, sorted by length in base pairs; polyacrylamide for protein, sorted by mass in
5
+ kilodaltons. This is the data behind the gel photograph that a tool such as SnapGene or Benchling draws
6
+ beside a digest.
7
+
8
+ - **`bandPosition`** — log-linear migration over the range a gel resolves, 0 at the wells and 1 at the
9
+ front
10
+ - **`bandsOf`** — fragment sizes to visible bands, merging what the eye could not separate, with an
11
+ intensity from the DNA in each band
12
+ - **`GELS`** — four agarose concentrations (0.8, 1.0, 1.5, 2.0%) and the range each one resolves
13
+ - **`LADDERS`** — the generic 1 kb and 100 bp size markers, and `ladderBands` to run them
14
+ - **`fragmentSizes`** — cut positions to fragment lengths, linear or circular, with no enzyme library
15
+ needed
16
+ - **`PROTEIN_GELS`** — four acrylamide concentrations (7.5, 10, 12, 15%) and the kilodalton range each
17
+ one resolves, with `PROTEIN_LADDERS`, `proteinBands` and `proteinBandPosition`
18
+ - **One dependency**, `@biolibs/core`, for the error class
19
+
20
+ ## What is verified
21
+
22
+ This is not a port of anything, and there is nothing to be a port *of* — Biopython has no gel. So there
23
+ is no parity checklist, and no reference implementation to compare with. What there is instead:
24
+
25
+ - **41 unit tests** against the model's own invariants, which is what can honestly be checked here: that
26
+ every fragment loaded appears in exactly one band, that a larger fragment never runs further than a
27
+ smaller one, that the band positions of a ladder increase monotonically, that merging is anchored so a
28
+ run of near-neighbours cannot chain into one band, and that both ends of the resolving range behave
29
+ the same way.
30
+ - **The arithmetic is checked at its fixed points**: the gel's `largest` is at 0, its `smallest` at 1,
31
+ and their geometric mean at 0.5.
32
+
33
+ Where the claim stops — and here it is the whole package, so it is worth being blunt:
34
+
35
+ - **The figures are conventional working values, not measurements.** The four concentrations and their
36
+ ranges are what supplier guides print for agarose in TAE. A real gel depends on buffer, voltage, run
37
+ time, comb and dye, none of which appear here.
38
+ - **Log-linear is a first approximation.** Migration is very nearly linear in `log10(size)` over the
39
+ range a gel separates, which is why gel photographs are read against a log scale — but it is an
40
+ approximation, and it is applied only inside that range. Outside it, sizes clamp.
41
+ - **`position` is a fraction of the lane, not a distance.** There is no mm, no run time and no voltage.
42
+ Two gels' positions are comparable only as fractions.
43
+ - **`intensity` is a share of the lane's base pairs**, scaled so the heaviest band is 1. That is mass,
44
+ not fluorescence: no dye binding, no saturation, no background.
45
+ - **Nothing here is drawn.** This is the numbers; rendering a lane is the caller's.
46
+
47
+ If you need to predict where a band will actually be on a particular rig, this is the wrong tool. If you
48
+ need to know whether your digest will be readable before you pour the gel, it is the right one.
49
+
50
+ ## Install
51
+
52
+ ```bash
53
+ npm install @biolibs/gel
54
+ ```
55
+
56
+ - ESM only, Node 20 or later, TypeScript declarations included
57
+
58
+ ```mermaid
59
+ graph BT
60
+ gel["@biolibs/gel"] --> core["@biolibs/core<br/><i>ValueError</i>"]
61
+ ```
62
+
63
+ ## Gels and ladders
64
+
65
+ ```ts
66
+ import { GELS, LADDERS, gelById, ladderById } from "@biolibs/gel";
67
+
68
+ GELS.map((g) => [g.percent, g.largest, g.smallest]);
69
+ // [[0.8, 15000, 500], [1, 10000, 250], [1.5, 4000, 100], [2, 2000, 50]]
70
+
71
+ gelById("1.0"); // { id: "1.0", percent: 1, largest: 10000, smallest: 250 }
72
+ gelById("2.0").smallest; // 50 — a stiffer gel resolves smaller fragments
73
+
74
+ LADDERS.map((l) => [l.id, l.sizes.length]); // [["1kb", 10], ["100bp", 11]]
75
+ ladderById("1kb").sizes[0]; // 10000
76
+
77
+ gelById("3.0");
78
+ // ValueError: unknown gel '3.0'; known gels are 0.8, 1.0, 1.5, 2.0
79
+ ```
80
+
81
+ A low-percentage gel spreads large fragments out and runs small ones off the bottom together; a
82
+ high-percentage gel does the reverse. `largest` and `smallest` bracket the range over which the gel
83
+ actually separates things, and are the two numbers everything else is built on.
84
+
85
+ ## Where a fragment runs
86
+
87
+ ```ts
88
+ import { bandPosition, gelById, resolves } from "@biolibs/gel";
89
+
90
+ const gel = gelById("1.0"); // resolves 250–10,000 bp
91
+
92
+ bandPosition(10000, gel); // 0 — at the wells
93
+ bandPosition(250, gel); // 1 — at the running front
94
+ bandPosition(1581, gel); // 0.5 — the geometric mean of the two ends, by definition of a log scale
95
+
96
+ bandPosition(2000, gel).toFixed(4); // "0.4363"
97
+ bandPosition(1000, gel).toFixed(4); // "0.6242"
98
+ bandPosition(500, gel).toFixed(4); // "0.8121"
99
+ ```
100
+
101
+ That the midpoint is the *geometric* mean rather than the arithmetic one is the whole model in one line:
102
+ `√(10000 × 250) = 1581`, and a 1581 bp fragment sits halfway down the lane.
103
+
104
+ Outside the range the gel does not separate, so sizes clamp rather than extrapolate:
105
+
106
+ ```ts
107
+ import { bandPosition, gelById, resolves } from "@biolibs/gel";
108
+
109
+ const gel = gelById("1.0");
110
+
111
+ bandPosition(50000, gel); // 0 — bunched at the wells with everything else that big
112
+ bandPosition(10, gel); // 1 — run off the bottom
113
+
114
+ resolves(1000, gel); // true
115
+ resolves(10000, gel); // true — the range is inclusive at both ends
116
+ resolves(20000, gel); // false
117
+ resolves(100, gel); // false
118
+ ```
119
+
120
+ ## Fragment sizes from cut positions
121
+
122
+ `fragmentSizes` turns cut positions into fragment lengths without pulling in an enzyme library, so a
123
+ digest from any source can be loaded.
124
+
125
+ ```ts
126
+ import { fragmentSizes } from "@biolibs/gel";
127
+
128
+ // pUC19 is 2686 bp; cutting a circle at two places gives two pieces.
129
+ fragmentSizes(2686, "circular", [395, 1230]); // [1851, 835]
130
+ fragmentSizes(2686, "circular", [395]); // [2686] — one cut on a circle opens it, nothing more
131
+ fragmentSizes(2686, "circular", []); // [2686] — an uncut circle stays whole
132
+
133
+ // A line with n cuts falls into n + 1 pieces, counting the two uncut ends.
134
+ fragmentSizes(1000, "linear", [100, 400]); // [600, 300, 100]
135
+ fragmentSizes(1000, "circular", [100, 400]); // [700, 300]
136
+ ```
137
+
138
+ Cuts are **0-based boundaries**: a cut at `n` separates the base at index `n - 1` from the base at index
139
+ `n`. `@biolibs/restriction` reports cuts 1-based, as Biopython does, so subtract one from each —
140
+ `@biolibs/cloning`'s `cutsIn` does that conversion for you.
141
+
142
+ ```ts
143
+ import { fragmentSizes } from "@biolibs/gel";
144
+
145
+ // Cuts at the ends of a line are the ends it already had, and add no piece.
146
+ fragmentSizes(1000, "linear", [0, 400, 1000]); // [600, 400]
147
+ // Two enzymes cutting the same bond make one break.
148
+ fragmentSizes(1000, "linear", [400, 400]); // [600, 400]
149
+ // Order does not matter.
150
+ fragmentSizes(1000, "linear", [400, 100]); // [600, 300, 100]
151
+
152
+ fragmentSizes(1000, "linear", [1001]);
153
+ // ValueError: cut position 1001 is outside a sequence of 1000 bases
154
+ ```
155
+
156
+ ## Reading a lane
157
+
158
+ ```ts
159
+ import { bandsOf, fragmentSizes, gelById } from "@biolibs/gel";
160
+
161
+ const gel = gelById("1.0");
162
+ const bands = bandsOf(fragmentSizes(2686, "circular", [395, 1230]), gel);
163
+
164
+ bands.map((b) => [b.size, b.position.toFixed(4), b.totalBases, b.intensity.toFixed(4)]);
165
+ // [[1851, "0.4573", 1851, "1.0000"],
166
+ // [ 835, "0.6731", 835, "0.4511"]]
167
+ bands.every((b) => !b.unresolved); // true — a readable digest on this gel
168
+ ```
169
+
170
+ `intensity` is the band's share of the lane's DNA, scaled so the heaviest is 1: the 835 bp band holds
171
+ 835/1851 of the base pairs of the 1851 bp one, so it stains less brightly. Merged fragments add up:
172
+
173
+ ```ts
174
+ import { bandsOf, gelById } from "@biolibs/gel";
175
+
176
+ const gel = gelById("1.0");
177
+
178
+ // Two 1000 bp fragments carry as much DNA as one 2000 bp fragment.
179
+ bandsOf([1000, 1000, 2000], gel).map((b) => [b.size, b.totalBases, b.intensity]);
180
+ // [[2000, 2000, 1], [1000, 2000, 1]] — equally bright
181
+ ```
182
+
183
+ ### Merging
184
+
185
+ Two fragments of nearly the same size cannot be told apart by eye, so they are reported as one band —
186
+ 3% apart by default.
187
+
188
+ ```ts
189
+ import { bandsOf, DEFAULT_TOLERANCE, gelById } from "@biolibs/gel";
190
+
191
+ const gel = gelById("1.0");
192
+ DEFAULT_TOLERANCE; // 0.03
193
+
194
+ bandsOf([2000, 2010, 500], gel).map((b) => [b.size, [...b.sizes]]);
195
+ // [[2010, [2010, 2000]], [500, [500]]] — the band's size is its largest fragment
196
+ bandsOf([2000, 2010, 500], gel, 0).map((b) => b.size);
197
+ // [2010, 2000, 500] — nothing merges at zero tolerance
198
+ ```
199
+
200
+ Merging is anchored on the band's **representative** — its largest fragment — not on the previous
201
+ fragment, so a run of near-neighbours cannot chain into one unbounded band:
202
+
203
+ ```ts
204
+ import { bandsOf, gelById } from "@biolibs/gel";
205
+
206
+ const gel = gelById("1.0");
207
+
208
+ bandsOf([1000, 980, 960, 940], gel).map((b) => [...b.sizes]);
209
+ // [[1000, 980], [960, 940]]
210
+ // 980 is within 3% of 1000; 960 is not, so a second band starts there and takes 940 with it.
211
+ ```
212
+
213
+ ### Outside the range
214
+
215
+ Fragments the gel does not separate are merged whatever the tolerance, because they genuinely do run
216
+ together — small ones at the front, large ones at the wells. Both ends behave the same way:
217
+
218
+ ```ts
219
+ import { bandsOf, gelById } from "@biolibs/gel";
220
+
221
+ const gel = gelById("1.0"); // resolves 250–10,000 bp
222
+
223
+ // Below the range: one band at the front, however far apart the sizes.
224
+ bandsOf([3000, 200, 100, 60], gel).map((b) => [b.size, [...b.sizes], b.position, b.unresolved]);
225
+ // [[3000, [3000], 0.3264…, false], [200, [200, 100, 60], 1, true]]
226
+
227
+ // Above it: one band at the wells.
228
+ bandsOf([30000, 20000, 5000], gel).map((b) => [b.size, [...b.sizes], b.position, b.unresolved]);
229
+ // [[30000, [30000, 20000], 0, true], [5000, [5000], 0.1879…, false]]
230
+ ```
231
+
232
+ `unresolved` is the flag to show the user: it means the gel put those fragments in one place and cannot
233
+ tell you how many there were or how big they are. Every fragment loaded still appears in exactly one
234
+ band, which is one of the invariants the tests check.
235
+
236
+ ## Running a ladder
237
+
238
+ ```ts
239
+ import { gelById, ladderBands, ladderById } from "@biolibs/gel";
240
+
241
+ const gel = gelById("1.0");
242
+ const markers = ladderBands(ladderById("1kb").sizes, gel);
243
+
244
+ markers.map((b) => [b.size, b.position.toFixed(4)]);
245
+ // [[10000, "0.0000"], [8000, "0.0605"], [6000, "0.1385"], [5000, "0.1879"], [4000, "0.2484"],
246
+ // [3000, "0.3264"], [2000, "0.4363"], [1500, "0.5143"], [1000, "0.6242"], [500, "0.8121"]]
247
+ markers.every((b) => b.intensity === 1); // true — a ladder is drawn evenly, unlike a real one
248
+ ```
249
+
250
+ A ladder's bands are **never merged**, even where the gel would not separate them: they are known sizes
251
+ and worth showing individually. They are still flagged:
252
+
253
+ ```ts
254
+ import { gelById, ladderBands } from "@biolibs/gel";
255
+
256
+ ladderBands([1000, 200, 100], gelById("1.0")).map((b) => [b.size, b.unresolved]);
257
+ // [[1000, false], [200, true], [100, true]]
258
+ ```
259
+
260
+ ## Choosing a gel
261
+
262
+ The reason to have four concentrations is that the same digest is readable on one and not another.
263
+
264
+ ```ts
265
+ import { bandsOf, gelById } from "@biolibs/gel";
266
+
267
+ // Two small fragments: a 1% gel runs them off the bottom together...
268
+ bandsOf([150, 120], gelById("1.0")).map((b) => [b.size, [...b.sizes], b.unresolved]);
269
+ // [[150, [150, 120], true]]
270
+
271
+ // ...while a 2% gel separates them.
272
+ bandsOf([150, 120], gelById("2.0")).map((b) => [b.size, b.position.toFixed(4), b.unresolved]);
273
+ // [[150, "0.7022", false], [120, "0.7627", false]]
274
+ ```
275
+
276
+ And the other way round — a 2% gel squeezes two large fragments together near the wells, where a 1% gel
277
+ spreads them out:
278
+
279
+ ```ts
280
+ import { bandPosition, gelById } from "@biolibs/gel";
281
+
282
+ const apart = Math.abs(bandPosition(1851, gelById("1.0")) - bandPosition(835, gelById("1.0")));
283
+ const squeezed = Math.abs(bandPosition(1851, gelById("2.0")) - bandPosition(835, gelById("2.0")));
284
+
285
+ apart.toFixed(4); // "0.2158"
286
+ squeezed.toFixed(4); // "0.2158" — the same, because a log scale is a log scale
287
+ ```
288
+
289
+ That last line is worth knowing: within the resolving range, the *separation* of two sizes depends only
290
+ on their ratio and the width of the gel's range in logs — which for the 1.0% and 2.0% gels happens to be
291
+ the same (both span a factor of 40). Picking a gel is about which fragments fall **inside** the range,
292
+ not about stretching the ones that already do.
293
+
294
+ ## Protein on acrylamide
295
+
296
+ A protein gel is read the same way, and the functions are shared rather than copied: `bandPosition` and
297
+ `bandsOf` take a `Resolving` — a largest and a smallest — and not a kind of gel. What changes is the
298
+ unit. SDS coats a chain with much the same charge for every unit of mass and undoes its shape, so what
299
+ is left to sort proteins by is size, and over the range a gel resolves the distance run is again close
300
+ to a straight line against the logarithm of it.
301
+
302
+ ```ts
303
+ import { bandPosition, proteinBandPosition, proteinBands, proteinGelById, proteinLadderById } from "@biolibs/gel";
304
+
305
+ const gel = proteinGelById("12");
306
+ [gel.percent, gel.largest, gel.smallest]; // [12, 100, 10] — kilodaltons, not base pairs
307
+
308
+ proteinBandPosition(100, gel); // 0 — at the well
309
+ proteinBandPosition(10, gel); // 1 — at the front
310
+ proteinBandPosition(Math.sqrt(100 * 10), gel)
311
+ .toFixed(4); // "0.5000" — the geometric mean, halfway
312
+
313
+ // The same arithmetic, which is the point of sharing it.
314
+ proteinBandPosition(28, gel) === bandPosition(28, { largest: 100, smallest: 10 }); // true
315
+
316
+ proteinLadderById("broad").sizes; // [250, 150, 100, 75, 50, 37, 25, 20, 15, 10]
317
+ proteinBands([28, 28.5, 62], gel).length; // 2 — 28 and 28.5 run as one band
318
+ ```
319
+
320
+ Two things about a real protein gel that this model does not know, and that matter when a band is read
321
+ against it: a prestained marker's bands are themselves calibrated and run a little off their printed
322
+ weights, and a protein that is glycosylated or not fully reduced runs at a size that is not the mass its
323
+ sequence comes to.
324
+
325
+ ## Testing
326
+
327
+ ```bash
328
+ npm test # the whole workspace
329
+ npx vitest run packages/gel/test
330
+ ```
331
+
332
+ | File | What it checks |
333
+ |---|---|
334
+ | `test/gel.test.ts` | the 41 behaviour tests, including the model's invariants |
335
+ | `test/readme.test.ts` | every code block in this file |
336
+
337
+ Coverage from this package's own tests — `npx vitest run --coverage packages/gel/test`:
338
+
339
+ | | |
340
+ |---|---|
341
+ | Statements | **100.00%** (102 / 102) |
342
+ | Functions | **100.00%** (7 / 7) |
343
+ | Branches | **98.55%** (68 / 69) |
344
+
345
+ ## Things to know
346
+
347
+ - **These are conventional figures, not measurements.** Use them to judge whether a digest is readable,
348
+ not to predict a photograph.
349
+ - **`position` is a fraction of the lane**, 0 at the wells and 1 at the front. There is no distance,
350
+ voltage or run time in the model.
351
+ - **The midpoint is the geometric mean.** On a 1% gel, 1581 bp runs halfway, not 5125.
352
+ - **Both ends of the range clamp and merge.** Fragments the gel cannot separate are reported as one band
353
+ with `unresolved: true`, at the front or at the wells.
354
+ - **Merging anchors on the band's largest fragment**, so near-neighbours cannot chain.
355
+ - **A band's `size` is its largest fragment**, and `sizes` holds them all — read `sizes.length` before
356
+ telling a user how many fragments a band is.
357
+ - **`intensity` is mass, not brightness.** It is the band's share of the lane's base pairs.
358
+ - **Cuts are 0-based boundaries**, one less than Biopython reports. `@biolibs/cloning`'s `cutsIn`
359
+ converts for you.
360
+ - **A ladder is drawn evenly.** Every marker gets `intensity: 1`, which no real ladder does.
361
+ - **The unit is the caller's to remember.** A `Band`'s `size` is base pairs on agarose and kilodaltons on
362
+ acrylamide; nothing in the type says which, so say it when you print it.
363
+
364
+ ## License
365
+
366
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Turning a list of fragment sizes into the bands a gel would show.
3
+ *
4
+ * Over the range a gel separates, the distance a fragment migrates is very nearly a straight line in the logarithm
5
+ * of its length — the standard first approximation, and the reason a gel photograph is read against a log scale.
6
+ * So {@link bandPosition} interpolates in `log10(size)` between the gel's largest and smallest resolved fragment,
7
+ * giving 0 at the wells and 1 at the running front.
8
+ *
9
+ * Two fragments of nearly the same size cannot be told apart by eye, so {@link bandsOf} merges sizes that fall
10
+ * within a tolerance of each other into a single band and records how many fragments it holds. Fragments outside
11
+ * the gel's range are not separated at all, so they are merged regardless of tolerance: the small ones pile up
12
+ * together at the front, and the large ones stay bunched at the wells.
13
+ */
14
+ import type { Resolving } from "./gels.js";
15
+ /** Default band-merging tolerance: fragments within 3% of each other run as one band. */
16
+ export declare const DEFAULT_TOLERANCE = 0.03;
17
+ /**
18
+ * How far down the gel a fragment of `size` runs, as a fraction of the distance from the wells to the front.
19
+ *
20
+ * @param size - Fragment length in base pairs, or a protein's mass in kilodaltons.
21
+ * @param gel - The range the gel separates.
22
+ * @returns 0 at the wells, 1 at the front. Fragments larger than {@link Resolving.largest} clamp to 0 and ones
23
+ * smaller than {@link Resolving.smallest} clamp to 1, since the gel does not separate them.
24
+ * @throws {@link ValueError} for a size that is not a positive finite number.
25
+ * @example
26
+ * ```ts
27
+ * const gel = { id: "1.0", percent: 1, largest: 10000, smallest: 250 };
28
+ * bandPosition(10000, gel); // 0
29
+ * bandPosition(250, gel); // 1
30
+ * bandPosition(1581, gel); // ~0.5 (the geometric mean of the two ends)
31
+ * ```
32
+ */
33
+ export declare function bandPosition(size: number, gel: Resolving): number;
34
+ /**
35
+ * Whether a gel separates a fragment of this size from its neighbours, i.e. whether it falls inside the gel's
36
+ * resolving range.
37
+ *
38
+ * @param size - Fragment length in base pairs.
39
+ * @param gel - The gel being run.
40
+ * @returns `true` when `gel.smallest <= size <= gel.largest`.
41
+ */
42
+ export declare const resolves: (size: number, gel: Resolving) => boolean;
43
+ /** One visible band: the fragments that run together at a single place on the gel. */
44
+ export interface Band {
45
+ /** Representative size — the largest in the band, in whatever the gel sorts by: base pairs for DNA, kilodaltons for protein. */
46
+ size: number;
47
+ /** Every size merged into this band, largest first. */
48
+ sizes: readonly number[];
49
+ /** Distance from the wells, 0 to 1, as {@link bandPosition} gives it. */
50
+ position: number;
51
+ /** The sizes in the band added up; a band holding more of what is stained shows more brightly. */
52
+ totalBases: number;
53
+ /** Brightness from 0 to 1, the band's share of the lane's total, scaled so the heaviest band is 1. */
54
+ intensity: number;
55
+ /**
56
+ * True when every fragment in the band is outside the gel's resolving range, so the gel does not separate them:
57
+ * below it they sit together at the running front, above it they stay bunched at the wells.
58
+ */
59
+ unresolved: boolean;
60
+ }
61
+ /**
62
+ * The bands a lane would show, given the sizes of the fragments loaded into it.
63
+ *
64
+ * @param sizes - Fragment lengths in base pairs, in any order. Sizes of zero or less are rejected.
65
+ * @param gel - The gel being run.
66
+ * @param tolerance - Relative size difference below which two fragments run as one band. Defaults to
67
+ * {@link DEFAULT_TOLERANCE}; pass 0 to keep every distinct size apart.
68
+ * @returns The bands, largest fragment first. An empty lane gives an empty array.
69
+ * @throws {@link ValueError} for a non-positive size or a negative tolerance.
70
+ * @example
71
+ * ```ts
72
+ * const gel = gelById("1.0");
73
+ * bandsOf([2000, 2010, 500], gel).length; // 2 — 2000 and 2010 run together
74
+ * ```
75
+ */
76
+ export declare function bandsOf(sizes: readonly number[], gel: Resolving, tolerance?: number): Band[];
77
+ /**
78
+ * The bands a ladder would show on a gel, as a lane of single fragments.
79
+ *
80
+ * @param ladderSizes - The ladder's band sizes.
81
+ * @param gel - The gel being run.
82
+ * @returns One band per marker size, largest first, each of equal intensity. Markers the gel does not resolve are
83
+ * marked `unresolved` but, unlike a sample lane, are never merged: a ladder's bands are known sizes and worth
84
+ * showing individually even where the gel would not separate them.
85
+ */
86
+ export declare function ladderBands(ladderSizes: readonly number[], gel: Resolving): Band[];
87
+ //# sourceMappingURL=bands.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bands.d.ts","sourceRoot":"","sources":["../src/bands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAE3C,yFAAyF;AACzF,eAAO,MAAM,iBAAiB,OAAO,CAAC;AAEtC;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,GAAG,MAAM,CAQjE;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ,GAAI,MAAM,MAAM,EAAE,KAAK,SAAS,KAAG,OAAsD,CAAC;AAE/G,sFAAsF;AACtF,MAAM,WAAW,IAAI;IACnB,gIAAgI;IAChI,IAAI,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,yEAAyE;IACzE,QAAQ,EAAE,MAAM,CAAC;IACjB,kGAAkG;IAClG,UAAU,EAAE,MAAM,CAAC;IACnB,sGAAsG;IACtG,SAAS,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,UAAU,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS,SAAoB,GAAG,IAAI,EAAE,CAoCvG;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,EAAE,GAAG,EAAE,SAAS,GAAG,IAAI,EAAE,CAWlF"}
package/dist/bands.js ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Turning a list of fragment sizes into the bands a gel would show.
3
+ *
4
+ * Over the range a gel separates, the distance a fragment migrates is very nearly a straight line in the logarithm
5
+ * of its length — the standard first approximation, and the reason a gel photograph is read against a log scale.
6
+ * So {@link bandPosition} interpolates in `log10(size)` between the gel's largest and smallest resolved fragment,
7
+ * giving 0 at the wells and 1 at the running front.
8
+ *
9
+ * Two fragments of nearly the same size cannot be told apart by eye, so {@link bandsOf} merges sizes that fall
10
+ * within a tolerance of each other into a single band and records how many fragments it holds. Fragments outside
11
+ * the gel's range are not separated at all, so they are merged regardless of tolerance: the small ones pile up
12
+ * together at the front, and the large ones stay bunched at the wells.
13
+ */
14
+ import { ValueError } from "@biolibs/core";
15
+ /** Default band-merging tolerance: fragments within 3% of each other run as one band. */
16
+ export const DEFAULT_TOLERANCE = 0.03;
17
+ /**
18
+ * How far down the gel a fragment of `size` runs, as a fraction of the distance from the wells to the front.
19
+ *
20
+ * @param size - Fragment length in base pairs, or a protein's mass in kilodaltons.
21
+ * @param gel - The range the gel separates.
22
+ * @returns 0 at the wells, 1 at the front. Fragments larger than {@link Resolving.largest} clamp to 0 and ones
23
+ * smaller than {@link Resolving.smallest} clamp to 1, since the gel does not separate them.
24
+ * @throws {@link ValueError} for a size that is not a positive finite number.
25
+ * @example
26
+ * ```ts
27
+ * const gel = { id: "1.0", percent: 1, largest: 10000, smallest: 250 };
28
+ * bandPosition(10000, gel); // 0
29
+ * bandPosition(250, gel); // 1
30
+ * bandPosition(1581, gel); // ~0.5 (the geometric mean of the two ends)
31
+ * ```
32
+ */
33
+ export function bandPosition(size, gel) {
34
+ if (!Number.isFinite(size) || size <= 0)
35
+ throw new ValueError(`fragment size must be a positive number, got ${size}`);
36
+ const high = Math.log10(gel.largest);
37
+ const low = Math.log10(gel.smallest);
38
+ // A gel whose ends coincide separates nothing; put everything at the front rather than dividing by zero.
39
+ if (high <= low)
40
+ return 1;
41
+ const fraction = (high - Math.log10(size)) / (high - low);
42
+ return Math.min(1, Math.max(0, fraction));
43
+ }
44
+ /**
45
+ * Whether a gel separates a fragment of this size from its neighbours, i.e. whether it falls inside the gel's
46
+ * resolving range.
47
+ *
48
+ * @param size - Fragment length in base pairs.
49
+ * @param gel - The gel being run.
50
+ * @returns `true` when `gel.smallest <= size <= gel.largest`.
51
+ */
52
+ export const resolves = (size, gel) => size <= gel.largest && size >= gel.smallest;
53
+ /**
54
+ * The bands a lane would show, given the sizes of the fragments loaded into it.
55
+ *
56
+ * @param sizes - Fragment lengths in base pairs, in any order. Sizes of zero or less are rejected.
57
+ * @param gel - The gel being run.
58
+ * @param tolerance - Relative size difference below which two fragments run as one band. Defaults to
59
+ * {@link DEFAULT_TOLERANCE}; pass 0 to keep every distinct size apart.
60
+ * @returns The bands, largest fragment first. An empty lane gives an empty array.
61
+ * @throws {@link ValueError} for a non-positive size or a negative tolerance.
62
+ * @example
63
+ * ```ts
64
+ * const gel = gelById("1.0");
65
+ * bandsOf([2000, 2010, 500], gel).length; // 2 — 2000 and 2010 run together
66
+ * ```
67
+ */
68
+ export function bandsOf(sizes, gel, tolerance = DEFAULT_TOLERANCE) {
69
+ if (!Number.isFinite(tolerance) || tolerance < 0)
70
+ throw new ValueError(`tolerance must be zero or more, got ${tolerance}`);
71
+ for (const size of sizes) {
72
+ if (!Number.isFinite(size) || size <= 0)
73
+ throw new ValueError(`fragment size must be a positive number, got ${size}`);
74
+ }
75
+ if (sizes.length === 0)
76
+ return [];
77
+ const descending = [...sizes].sort((a, b) => b - a);
78
+ // Walk down the sizes, starting a new group whenever the next fragment is further than `tolerance` from the
79
+ // group's representative size. Comparing against the group's representative rather than the previous fragment is
80
+ // what stops a run of near-neighbours chaining into one unbounded band.
81
+ const groups = [];
82
+ for (const size of descending) {
83
+ const current = groups[groups.length - 1];
84
+ const representative = current?.[0];
85
+ // Fragments the gel does not separate belong in one band however far apart they are: everything above the
86
+ // range stays bunched at the wells, and everything below it runs off together at the front.
87
+ const bothUnresolved = representative !== undefined
88
+ && ((representative < gel.smallest && size < gel.smallest)
89
+ || (representative > gel.largest && size > gel.largest));
90
+ const closeEnough = representative !== undefined && representative - size <= representative * tolerance;
91
+ if (current && (bothUnresolved || closeEnough))
92
+ current.push(size);
93
+ else
94
+ groups.push([size]);
95
+ }
96
+ const weights = groups.map((group) => group.reduce((sum, size) => sum + size, 0));
97
+ const heaviest = Math.max(...weights);
98
+ return groups.map((group, i) => ({
99
+ size: group[0],
100
+ sizes: group,
101
+ position: bandPosition(group[0], gel),
102
+ totalBases: weights[i],
103
+ intensity: heaviest > 0 ? weights[i] / heaviest : 0,
104
+ unresolved: group.every((size) => !resolves(size, gel)),
105
+ }));
106
+ }
107
+ /**
108
+ * The bands a ladder would show on a gel, as a lane of single fragments.
109
+ *
110
+ * @param ladderSizes - The ladder's band sizes.
111
+ * @param gel - The gel being run.
112
+ * @returns One band per marker size, largest first, each of equal intensity. Markers the gel does not resolve are
113
+ * marked `unresolved` but, unlike a sample lane, are never merged: a ladder's bands are known sizes and worth
114
+ * showing individually even where the gel would not separate them.
115
+ */
116
+ export function ladderBands(ladderSizes, gel) {
117
+ return [...ladderSizes]
118
+ .sort((a, b) => b - a)
119
+ .map((size) => ({
120
+ size,
121
+ sizes: [size],
122
+ position: bandPosition(size, gel),
123
+ totalBases: size,
124
+ intensity: 1,
125
+ unresolved: !resolves(size, gel),
126
+ }));
127
+ }
128
+ //# sourceMappingURL=bands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bands.js","sourceRoot":"","sources":["../src/bands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAG3C,yFAAyF;AACzF,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAEtC;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,YAAY,CAAC,IAAY,EAAE,GAAc;IACvD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,gDAAgD,IAAI,EAAE,CAAC,CAAC;IACtH,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACrC,yGAAyG;IACzG,IAAI,IAAI,IAAI,GAAG;QAAE,OAAO,CAAC,CAAC;IAC1B,MAAM,QAAQ,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC;IAC1D,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,GAAc,EAAW,EAAE,CAAC,IAAI,IAAI,GAAG,CAAC,OAAO,IAAI,IAAI,IAAI,GAAG,CAAC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C,CAAC;SACrB,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACd,IAAI;QACJ,KAAK,EAAE,CAAC,IAAI,CAAC;QACb,QAAQ,EAAE,YAAY,CAAC,IAAI,EAAE,GAAG,CAAC;QACjC,UAAU,EAAE,IAAI;QAChB,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,GAAG,CAAC;KACjC,CAAC,CAAC,CAAC;AACR,CAAC"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Fragment sizes from cut positions, so a digest can be loaded onto a gel without pulling in an enzyme library.
3
+ *
4
+ * Positions are 0-based offsets into the sequence, counted as boundaries between bases: a cut at `n` separates the
5
+ * base at index `n - 1` from the base at index `n`. This is the half-open convention used across biolibs, so a cut
6
+ * list is directly usable as slice boundaries. (Biopython's `RestrictionType.search` returns 1-based positions;
7
+ * subtract one from each before passing them here.)
8
+ */
9
+ /** Whether a sequence is a line with two ends or a closed circle. */
10
+ export type Topology = "linear" | "circular";
11
+ /**
12
+ * The lengths of the pieces a set of cuts divides a sequence into.
13
+ *
14
+ * A linear sequence with `n` cuts falls into `n + 1` pieces, including the two uncut ends. A circular sequence with
15
+ * `n` cuts falls into `n` pieces, one of which spans the origin; an uncut circle stays whole.
16
+ *
17
+ * @param length - Sequence length in bases.
18
+ * @param topology - `"linear"` or `"circular"`.
19
+ * @param cuts - 0-based cut positions, in any order. Duplicates count once, since two enzymes cutting the same
20
+ * bond produce one break.
21
+ * @returns The piece lengths, largest first. Cuts at 0 or at `length` on a linear sequence are the existing ends and
22
+ * add no piece; zero-length pieces are never returned.
23
+ * @throws {@link ValueError} for a negative or non-integer length, or a cut outside `[0, length]`.
24
+ * @example
25
+ * ```ts
26
+ * fragmentSizes(1000, "linear", [100, 400]); // [600, 300, 100]
27
+ * fragmentSizes(1000, "circular", [100, 400]); // [700, 300]
28
+ * fragmentSizes(1000, "circular", []); // [1000]
29
+ * ```
30
+ */
31
+ export declare function fragmentSizes(length: number, topology: Topology, cuts: readonly number[]): number[];
32
+ //# sourceMappingURL=fragments.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fragments.d.ts","sourceRoot":"","sources":["../src/fragments.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,qEAAqE;AACrE,MAAM,MAAM,QAAQ,GAAG,QAAQ,GAAG,UAAU,CAAC;AAE7C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAyBnG"}