dsh-molbio-tools 0.27.1 → 0.28.0

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/sequencing.mjs ADDED
@@ -0,0 +1,517 @@
1
+ /**
2
+ * dsh-molbio-tools/sequencing.mjs
3
+ *
4
+ * Read-set interpretation for Sanger work:
5
+ * - assemble several reads into one quality-aware consensus contig
6
+ * (greedy overlap-layout, both orientations, exact-overlap circular closure
7
+ * when asked);
8
+ * - collapse reads aligned to a reference into allele clusters and classify
9
+ * each cluster's protein effect inside an optional CDS.
10
+ *
11
+ * Both are read-level methods. They do NOT deconvolve mixed Sanger peaks: the
12
+ * editing tool groups reads by the variants each read carries, and its
13
+ * frequencies are fractions of the aligned reads — not TIDE's peak model.
14
+ */
15
+
16
+ import { CODON_TABLE, MolbioInputError, normalizeSequence, reverseComplement } from './lib.mjs';
17
+ import { alignToReference } from './align.mjs';
18
+
19
+ export const SEQUENCING_LIMITS = {
20
+ maxReads: 24,
21
+ maxReadLength: 5000,
22
+ minReadLength: 15,
23
+ };
24
+
25
+ const DEFAULT_QUALITY = 30;
26
+
27
+ function validateReads(reads, label) {
28
+ if (!Array.isArray(reads) || reads.length === 0) throw new MolbioInputError(`${label} needs at least one read`);
29
+ if (reads.length > SEQUENCING_LIMITS.maxReads) throw new MolbioInputError(`${reads.length} ${label} exceeds the limit of ${SEQUENCING_LIMITS.maxReads}`);
30
+ return reads.map((read, index) => {
31
+ if (read === null || typeof read !== 'object') throw new MolbioInputError(`read ${index + 1} must be an object with a sequence`);
32
+ const sequence = normalizeSequence(read.sequence, `read ${index + 1}`);
33
+ if (sequence.length > SEQUENCING_LIMITS.maxReadLength) throw new MolbioInputError(`read ${index + 1} is ${sequence.length} bases; the limit is ${SEQUENCING_LIMITS.maxReadLength}`);
34
+ let qualities;
35
+ if (read.qualities !== undefined) {
36
+ if (!Array.isArray(read.qualities) || read.qualities.length !== sequence.length) throw new MolbioInputError(`read ${index + 1} qualities must be an array with one value per base`);
37
+ qualities = read.qualities.map((q) => Number(q));
38
+ if (qualities.some((q) => !Number.isFinite(q) || q < 0 || q > 100)) throw new MolbioInputError(`read ${index + 1} qualities must be numbers between 0 and 100`);
39
+ }
40
+ return { name: String(read.name ?? `read${index + 1}`), sequence, qualities };
41
+ });
42
+ }
43
+
44
+ function trimByQuality(sequence, qualities, minQuality) {
45
+ if (qualities === undefined || !(minQuality > 0)) return { sequence, qualities, trimmedStart: 0, trimmedEnd: 0 };
46
+ let start = 0;
47
+ let end = sequence.length;
48
+ while (start < end && qualities[start] < minQuality) start++;
49
+ while (end > start && qualities[end - 1] < minQuality) end--;
50
+ return {
51
+ sequence: sequence.slice(start, end),
52
+ qualities: qualities.slice(start, end),
53
+ trimmedStart: start,
54
+ trimmedEnd: sequence.length - end,
55
+ };
56
+ }
57
+
58
+ /** Longest acceptable suffix(a)/prefix(b) overlap, or null. */
59
+ function rightOverlap(a, b, { minOverlap, maxOverlap, maxMismatchFraction }) {
60
+ const max = Math.min(maxOverlap, a.length, b.length);
61
+ for (let overlap = max; overlap >= minOverlap; overlap--) {
62
+ const allowed = Math.floor(overlap * maxMismatchFraction);
63
+ let mismatches = 0;
64
+ let ok = true;
65
+ for (let i = 0; i < overlap; i++) {
66
+ if (a[a.length - overlap + i] !== b[i]) {
67
+ mismatches++;
68
+ if (mismatches > allowed) { ok = false; break; }
69
+ }
70
+ }
71
+ if (ok) return { overlap, mismatches };
72
+ }
73
+ return null;
74
+ }
75
+
76
+ function consensusOf(placed) {
77
+ let minOffset = Infinity;
78
+ let maxEnd = -Infinity;
79
+ for (const read of placed) {
80
+ minOffset = Math.min(minOffset, read.offset);
81
+ maxEnd = Math.max(maxEnd, read.offset + read.sequence.length);
82
+ }
83
+ const length = maxEnd - minOffset;
84
+ const bases = [];
85
+ const scores = [];
86
+ for (let column = 0; column < length; column++) {
87
+ const totals = new Map();
88
+ let depth = 0;
89
+ for (const read of placed) {
90
+ const index = column - read.offset;
91
+ if (index < 0 || index >= read.sequence.length) continue;
92
+ depth++;
93
+ const base = read.sequence[index];
94
+ const quality = read.qualities?.[index] ?? DEFAULT_QUALITY;
95
+ totals.set(base, (totals.get(base) ?? 0) + quality);
96
+ }
97
+ let bestBase = null;
98
+ let bestScore = -Infinity;
99
+ for (const [base, score] of totals) {
100
+ if (score > bestScore || (score === bestScore && bestBase !== null && base < bestBase)) {
101
+ bestBase = base;
102
+ bestScore = score;
103
+ }
104
+ }
105
+ bases.push(bestBase);
106
+ scores.push(depth);
107
+ }
108
+ return {
109
+ sequence: bases.join(''),
110
+ placed: placed.map((read) => ({ ...read, offset: read.offset - minOffset })),
111
+ columnCounts: scores,
112
+ };
113
+ }
114
+
115
+ function overlapsOf(contig, read, options) {
116
+ const right = rightOverlap(contig, read, options);
117
+ const left = rightOverlap(read, contig, options);
118
+ return {
119
+ right: right === null ? null : { ...right, side: 'right' },
120
+ left: left === null ? null : { ...left, side: 'left' },
121
+ };
122
+ }
123
+
124
+ function circularClosure(contig, options) {
125
+ const max = Math.min(options.maxOverlap, Math.floor(contig.length / 3));
126
+ for (let overlap = max; overlap >= options.minOverlap; overlap--) {
127
+ const allowed = Math.floor(overlap * options.maxMismatchFraction);
128
+ let mismatches = 0;
129
+ for (let i = 0; i < overlap; i++) {
130
+ if (contig[contig.length - overlap + i] !== contig[i]) mismatches++;
131
+ }
132
+ if (mismatches <= allowed) return { overlap, mismatches };
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /**
138
+ * Greedy overlap-layout assembly of a handful of Sanger reads.
139
+ *
140
+ * Reads are tried in both orientations; the longest acceptable overlap wins,
141
+ * ties are broken by fewer mismatches, then by read name so the result is
142
+ * deterministic. After every placement the contig is rebuilt from the quality-
143
+ * weighted consensus, so a low-quality miscall cannot silently propagate.
144
+ */
145
+ export function assembleReads(reads, options = {}) {
146
+ const input = validateReads(reads, 'assembly');
147
+ const minOverlap = options.minOverlap ?? 20;
148
+ if (!Number.isInteger(minOverlap) || minOverlap < 5 || minOverlap > 500) throw new MolbioInputError('min_overlap must be an integer between 5 and 500');
149
+ const maxOverlap = options.maxOverlap ?? 250;
150
+ if (!Number.isInteger(maxOverlap) || maxOverlap < minOverlap || maxOverlap > 2000) throw new MolbioInputError('max_overlap must be an integer between min_overlap and 2000');
151
+ const maxMismatchFraction = options.maxMismatchFraction ?? 0.1;
152
+ if (!(typeof maxMismatchFraction === 'number') || maxMismatchFraction < 0 || maxMismatchFraction > 0.5) throw new MolbioInputError('max_mismatch_fraction must be a number between 0 and 0.5');
153
+ const trimQuality = options.trimQuality ?? 20;
154
+ if (!(typeof trimQuality === 'number') || trimQuality < 0 || trimQuality > 60) throw new MolbioInputError('trim_quality must be a number between 0 (off) and 60');
155
+ const circular = options.circular === true;
156
+
157
+ const prepared = [];
158
+ const dropped = [];
159
+ for (const read of input) {
160
+ const trimmed = trimByQuality(read.sequence, read.qualities, trimQuality);
161
+ if (trimmed.sequence.length < SEQUENCING_LIMITS.minReadLength) {
162
+ dropped.push({ name: read.name, reason: `only ${trimmed.sequence.length} bases left after quality trimming` });
163
+ continue;
164
+ }
165
+ prepared.push({ ...read, ...trimmed, originalLength: read.sequence.length });
166
+ }
167
+ if (prepared.length === 0) throw new MolbioInputError('every read was shorter than the minimum after quality trimming');
168
+
169
+ const optionsForOverlap = { minOverlap, maxOverlap, maxMismatchFraction };
170
+ prepared.sort((a, b) => b.sequence.length - a.sequence.length || a.name.localeCompare(b.name));
171
+ const placed = [{ ...prepared[0], offset: 0, orientation: 'forward', overlapLeft: 0, overlapRight: 0, mismatchesLeft: 0, mismatchesRight: 0 }];
172
+ let contig = prepared[0].sequence;
173
+ const remaining = prepared.slice(1);
174
+
175
+ while (remaining.length > 0) {
176
+ let best = null;
177
+ for (const read of remaining) {
178
+ for (const orientation of ['forward', 'reverse']) {
179
+ const sequence = orientation === 'forward' ? read.sequence : reverseComplement(read.sequence);
180
+ const qualities = orientation === 'forward' ? read.qualities : read.qualities === undefined ? undefined : [...read.qualities].reverse();
181
+ for (const [side, overlap] of Object.entries(overlapsOf(contig, sequence, optionsForOverlap))) {
182
+ if (overlap === null) continue;
183
+ const score = overlap.overlap - 2 * overlap.mismatches;
184
+ const candidate = { read, sequence, qualities, orientation, side, ...overlap, score };
185
+ if (best === null || candidate.score > best.score
186
+ || (candidate.score === best.score && candidate.overlap > best.overlap)
187
+ || (candidate.score === best.score && candidate.overlap === best.overlap && candidate.read.name < best.read.name)) {
188
+ best = candidate;
189
+ }
190
+ }
191
+ }
192
+ }
193
+ if (best === null) break;
194
+ const offset = best.side === 'right' ? contig.length - best.overlap : -best.overlap;
195
+ placed.push({
196
+ name: best.read.name,
197
+ sequence: best.sequence,
198
+ qualities: best.qualities,
199
+ trimmedStart: best.read.trimmedStart,
200
+ trimmedEnd: best.read.trimmedEnd,
201
+ originalLength: best.read.originalLength,
202
+ offset,
203
+ orientation: best.orientation,
204
+ overlapLeft: best.side === 'left' ? best.overlap : 0,
205
+ overlapRight: best.side === 'right' ? best.overlap : 0,
206
+ mismatchesLeft: best.side === 'left' ? best.mismatches : 0,
207
+ mismatchesRight: best.side === 'right' ? best.mismatches : 0,
208
+ });
209
+ remaining.splice(remaining.indexOf(best.read), 1);
210
+ const rebuilt = consensusOf(placed);
211
+ contig = rebuilt.sequence;
212
+ placed.length = 0;
213
+ placed.push(...rebuilt.placed);
214
+ }
215
+
216
+ const rebuilt = consensusOf(placed);
217
+ contig = rebuilt.sequence;
218
+ const finalPlaced = rebuilt.placed;
219
+
220
+ let conflicts = 0;
221
+ const conflictPositions = [];
222
+ for (const read of finalPlaced) {
223
+ for (let i = 0; i < read.sequence.length; i++) {
224
+ const column = read.offset + i;
225
+ if (column >= 0 && column < contig.length && read.sequence[i] !== contig[column]) {
226
+ conflicts++;
227
+ if (conflictPositions.length < 50) conflictPositions.push(column + 1);
228
+ }
229
+ }
230
+ }
231
+
232
+ let circularClosureResult = null;
233
+ if (circular) {
234
+ circularClosureResult = circularClosure(contig, { minOverlap, maxOverlap, maxMismatchFraction });
235
+ if (circularClosureResult !== null) contig = contig.slice(0, contig.length - circularClosureResult.overlap);
236
+ }
237
+
238
+ const coverage = rebuilt.columnCounts;
239
+ const coverageMean = coverage.reduce((sum, n) => sum + n, 0) / coverage.length;
240
+ const coverageMin = coverage.reduce((min, n) => Math.min(min, n), Infinity);
241
+ const readsOut = finalPlaced.map((read) => ({
242
+ name: read.name,
243
+ orientation: read.orientation,
244
+ start: read.offset + 1,
245
+ end: read.offset + read.sequence.length,
246
+ length: read.sequence.length,
247
+ trimmed_bases: read.trimmedStart + read.trimmedEnd,
248
+ overlap_left: read.overlapLeft,
249
+ overlap_right: read.overlapRight,
250
+ mismatches: read.mismatchesLeft + read.mismatchesRight,
251
+ })).sort((a, b) => a.start - b.start || a.name.localeCompare(b.name));
252
+
253
+ const unplaced = remaining.map((read) => ({ name: read.name, reason: 'no acceptable overlap with the growing contig' }));
254
+ const notes = [
255
+ 'Consensus is quality-weighted (Phred from .ab1; 30 where a plain sequence carries no qualities).',
256
+ 'This is a greedy overlap-layout consensus for a handful of Sanger reads, not a genome assembler; repeats longer than min_overlap can collapse.',
257
+ ];
258
+ if (circular && circularClosureResult === null) notes.push('circular closure was requested but no acceptable end overlap was found; the contig is linear');
259
+ if (circularClosureResult !== null) notes.push('coverage and read offsets describe the assembled linear contig before the closing overlap was removed');
260
+ if (dropped.length > 0) notes.push(`${dropped.length} read(s) were dropped before assembly (see unplaced)`);
261
+
262
+ return {
263
+ name: options.name ?? 'contig',
264
+ sequence: contig,
265
+ length: contig.length,
266
+ read_count: input.length,
267
+ placed_count: finalPlaced.length,
268
+ coverage_mean: Math.round(coverageMean * 100) / 100,
269
+ coverage_min: Number.isFinite(coverageMin) ? coverageMin : 0,
270
+ conflicts,
271
+ conflict_positions: conflictPositions,
272
+ circular_requested: circular,
273
+ circularized: circularClosureResult !== null,
274
+ circular_overlap: circularClosureResult === null ? 0 : circularClosureResult.overlap,
275
+ reads: readsOut,
276
+ unplaced: [...dropped, ...unplaced],
277
+ notes,
278
+ };
279
+ }
280
+
281
+ // ── editing outcome clustering (#31) ───────────────────────────────────────
282
+
283
+ /** Collapse consecutive differences into variant records. */
284
+ function describeVariants(differences) {
285
+ const sorted = [...differences].sort((a, b) => a.ref_pos - b.ref_pos || (a.trace_pos ?? 0) - (b.trace_pos ?? 0));
286
+ const variants = [];
287
+ let i = 0;
288
+ while (i < sorted.length) {
289
+ const current = sorted[i];
290
+ if (current.kind === 'mismatch') {
291
+ variants.push({ kind: 'mismatch', position: current.ref_pos, ref: current.ref_base, alt: current.trace_base, length: 1 });
292
+ i++;
293
+ } else if (current.kind === 'deletion') {
294
+ let end = current.ref_pos;
295
+ let ref = current.ref_base;
296
+ let j = i + 1;
297
+ while (j < sorted.length && sorted[j].kind === 'deletion' && sorted[j].ref_pos === end + 1) {
298
+ end = sorted[j].ref_pos;
299
+ ref += sorted[j].ref_base;
300
+ j++;
301
+ }
302
+ variants.push({ kind: 'deletion', position: current.ref_pos, end, ref, alt: '', length: end - current.ref_pos + 1 });
303
+ i = j;
304
+ } else {
305
+ let alt = current.trace_base;
306
+ let j = i + 1;
307
+ while (j < sorted.length && sorted[j].kind === 'insertion' && sorted[j].ref_pos === current.ref_pos
308
+ && sorted[j].trace_pos === sorted[j - 1].trace_pos + 1) {
309
+ alt += sorted[j].trace_base;
310
+ j++;
311
+ }
312
+ variants.push({ kind: 'insertion', position: current.ref_pos, ref: '', alt, length: alt.length });
313
+ i = j;
314
+ }
315
+ }
316
+ return variants;
317
+ }
318
+
319
+ function labelOf(variants) {
320
+ if (variants.length === 0) return 'wild type';
321
+ return variants.map((variant) => variant.kind === 'mismatch'
322
+ ? `${variant.ref}${variant.position}${variant.alt}`
323
+ : variant.kind === 'deletion'
324
+ ? (variant.length === 1 ? `del ${variant.position}` : `del ${variant.position}-${variant.end}`)
325
+ : `ins ${variant.alt} at ${variant.position}`).join(' + ');
326
+ }
327
+
328
+ function signatureOf(variants) {
329
+ if (variants.length === 0) return 'wild_type';
330
+ return variants.map((v) => v.kind === 'insertion'
331
+ ? `ins:${v.position}:${v.alt}`
332
+ : v.kind === 'deletion'
333
+ ? `del:${v.position}:${v.end}`
334
+ : `sub:${v.position}:${v.ref}>${v.alt}`).join('|');
335
+ }
336
+
337
+ function translateCds(cds) {
338
+ let protein = '';
339
+ const table = CODON_TABLE.standard;
340
+ for (let i = 0; i + 3 <= cds.length; i += 3) protein += table[cds.slice(i, i + 3)] ?? 'X';
341
+ return protein;
342
+ }
343
+
344
+ /** Apply variants (positions relative to the CDS, 1-based) to a CDS. */
345
+ function mutateCds(cds, variants) {
346
+ let out = '';
347
+ let cursor = 1;
348
+ for (const variant of [...variants].sort((a, b) => a.position - b.position)) {
349
+ if (variant.position < cursor) continue;
350
+ if (variant.kind === 'mismatch') {
351
+ out += cds.slice(cursor - 1, variant.position - 1) + variant.alt;
352
+ cursor = variant.position + 1;
353
+ } else if (variant.kind === 'deletion') {
354
+ out += cds.slice(cursor - 1, variant.position - 1);
355
+ cursor = variant.end + 1;
356
+ } else {
357
+ out += cds.slice(cursor - 1, variant.position - 1) + variant.alt;
358
+ cursor = variant.position;
359
+ }
360
+ }
361
+ out += cds.slice(cursor - 1);
362
+ return out;
363
+ }
364
+
365
+ function classifyEffect(reference, cdsStart, cdsEnd, variants) {
366
+ if (cdsStart === undefined || cdsEnd === undefined) return { effect: 'not_evaluated', protein_change: '' };
367
+ const inCds = variants.filter((variant) => {
368
+ const end = variant.kind === 'deletion' ? variant.end : variant.position;
369
+ return variant.position <= cdsEnd && end >= cdsStart;
370
+ });
371
+ if (inCds.length === 0) return { effect: 'outside_cds', protein_change: '' };
372
+ const relative = inCds.map((variant) => ({
373
+ ...variant,
374
+ position: variant.position - cdsStart + 1,
375
+ ...variant.kind === 'deletion' ? { end: variant.end - cdsStart + 1 } : {},
376
+ }));
377
+ const referenceCds = reference.slice(cdsStart - 1, cdsEnd);
378
+ const mutatedCds = mutateCds(referenceCds, relative);
379
+ const referenceProtein = translateCds(referenceCds);
380
+ const mutatedProtein = translateCds(mutatedCds);
381
+ // Net length change, not the per-variant lengths: a deletion can be split
382
+ // across two alignment gaps without changing what it does to the frame.
383
+ if ((mutatedCds.length - referenceCds.length) % 3 !== 0) return { effect: 'frameshift', protein_change: '' };
384
+ // A length change that is a multiple of 3 is the event itself; whether the
385
+ // shifted stop looks 'early' is a consequence, not a second mutation.
386
+ if (mutatedCds.length !== referenceCds.length) return { effect: 'in_frame_indel', protein_change: '' };
387
+ if (mutatedProtein === referenceProtein) return { effect: 'silent', protein_change: '' };
388
+ const firstDifference = [...referenceProtein].findIndex((aa, index) => aa !== mutatedProtein[index]);
389
+ const change = firstDifference === -1 ? '' : `${referenceProtein[firstDifference]}${firstDifference + 1}${mutatedProtein[firstDifference] ?? '*'}`;
390
+ const referenceStop = referenceProtein.indexOf('*');
391
+ const mutatedStop = mutatedProtein.indexOf('*');
392
+ if (mutatedStop !== -1 && (referenceStop === -1 || mutatedStop < referenceStop)) return { effect: 'nonsense', protein_change: change };
393
+ return { effect: 'missense', protein_change: change };
394
+ }
395
+
396
+ /**
397
+ * Collapse a read set into allele clusters against a reference.
398
+ *
399
+ * Each read is aligned in both orientations and the better one is kept; reads
400
+ * below `identity_threshold` are counted as unaligned rather than forced into
401
+ * an allele. Clusters are exact variant signatures, so two reads with the same
402
+ * edit group together; the reported frequency is a fraction of the ALIGNED
403
+ * reads. This is a read-fraction method, not TIDE's mixed-peak decomposition.
404
+ */
405
+ export function callEditingOutcomes(reads, reference, options = {}) {
406
+ const ref = normalizeSequence(reference, 'reference');
407
+ const input = validateReads(reads, 'editing-outcome analysis');
408
+ const circular = options.circular !== false;
409
+ const minFrequency = options.minFrequency ?? 0.01;
410
+ if (!(typeof minFrequency === 'number') || minFrequency < 0 || minFrequency > 1) throw new MolbioInputError('min_frequency must be a number between 0 and 1');
411
+ const identityThreshold = options.identityThreshold ?? 0.6;
412
+ if (!(typeof identityThreshold === 'number') || identityThreshold < 0 || identityThreshold > 1) throw new MolbioInputError('identity_threshold must be a number between 0 and 1');
413
+ const cdsStart = options.cdsStart;
414
+ const cdsEnd = options.cdsEnd;
415
+ if ((cdsStart === undefined) !== (cdsEnd === undefined)) throw new MolbioInputError('give both cds_start and cds_end, or neither');
416
+ if (cdsStart !== undefined) {
417
+ if (!Number.isInteger(cdsStart) || !Number.isInteger(cdsEnd) || cdsStart < 1 || cdsEnd > ref.length || cdsStart > cdsEnd) {
418
+ throw new MolbioInputError(`invalid CDS span ${cdsStart}-${cdsEnd} (reference length ${ref.length})`);
419
+ }
420
+ }
421
+
422
+ const aligned = [];
423
+ const unaligned = [];
424
+ for (const read of input) {
425
+ let best = null;
426
+ for (const orientation of ['forward', 'reverse']) {
427
+ const sequence = orientation === 'forward' ? read.sequence : reverseComplement(read.sequence);
428
+ try {
429
+ const result = alignToReference(sequence, ref, circular);
430
+ if (best === null || result.identity_percent > best.result.identity_percent) {
431
+ best = { orientation, sequence, result };
432
+ }
433
+ } catch {
434
+ /* try the other orientation; a read with no local alignment is unaligned */
435
+ }
436
+ }
437
+ const minimumSpan = Math.min(read.sequence.length, Math.max(20, Math.floor(read.sequence.length * 0.5)));
438
+ if (best === null || best.result.identity_percent < identityThreshold * 100 || best.result.aligned_columns < minimumSpan) {
439
+ unaligned.push({ name: read.name, identity: best === null ? 0 : best.result.identity_percent });
440
+ continue;
441
+ }
442
+ const variants = describeVariants(best.result.differences);
443
+ aligned.push({ name: read.name, orientation: best.orientation, identity: best.result.identity_percent, variants, signature: signatureOf(variants) });
444
+ }
445
+ if (aligned.length === 0) throw new MolbioInputError('no read aligned to the reference; check that the reference is the right molecule');
446
+
447
+ const groups = new Map();
448
+ for (const read of aligned) {
449
+ const group = groups.get(read.signature) ?? { signature: read.signature, variants: read.variants, count: 0, identities: [], representative: read.name };
450
+ group.count++;
451
+ group.identities.push(read.identity);
452
+ groups.set(read.signature, group);
453
+ }
454
+
455
+ const alleles = [];
456
+ for (const group of groups.values()) {
457
+ const frequency = group.count / aligned.length;
458
+ const effect = group.signature === 'wild_type'
459
+ ? { effect: 'wild_type', protein_change: '' }
460
+ : classifyEffect(ref, cdsStart, cdsEnd, group.variants);
461
+ let from = null;
462
+ let to = null;
463
+ for (const variant of group.variants) {
464
+ const start = variant.position;
465
+ const end = variant.kind === 'deletion' ? variant.end : variant.position;
466
+ from = from === null ? start : Math.min(from, start);
467
+ to = to === null ? end : Math.max(to, end);
468
+ }
469
+ const meanIdentity = group.identities.reduce((sum, value) => sum + value, 0) / group.identities.length;
470
+ alleles.push({
471
+ signature: group.signature,
472
+ label: labelOf(group.variants),
473
+ count: group.count,
474
+ frequency: Math.round(frequency * 10000) / 10000,
475
+ variants: group.variants,
476
+ variant_count: group.variants.length,
477
+ edited_from: from ?? 0,
478
+ edited_to: to ?? 0,
479
+ effect: effect.effect,
480
+ protein_change: effect.protein_change,
481
+ representative: group.representative,
482
+ mean_identity: Math.round(meanIdentity * 100) / 100,
483
+ });
484
+ }
485
+ alleles.sort((a, b) => b.count - a.count || a.signature.localeCompare(b.signature));
486
+ const reported = alleles.filter((allele) => allele.frequency >= minFrequency);
487
+ const notes = [
488
+ 'Alleles are exact variant signatures over the aligned read span; frequencies are fractions of the aligned reads.',
489
+ 'This is read-fraction clustering, not TIDE: mixed Sanger peaks inside one trace are not decomposed.',
490
+ 'A read must align over at least half its length (minimum 20 bases) as well as pass the identity threshold, so a short spurious local match cannot become an allele.',
491
+ 'Variants are called only inside each read\'s aligned span; a read end that fails to align is not reported as an edit.',
492
+ ];
493
+ if (circular) notes.push('the reference is treated as circular (reads spanning the origin align against a doubled reference)');
494
+ if (cdsStart !== undefined) notes.push('effect is classified inside the given CDS; variants outside it are reported but do not change the call');
495
+ if (reported.length < alleles.length) notes.push(`${alleles.length - reported.length} allele(s) below min_frequency were omitted`);
496
+ // The failure this catches: a hand-copied reference that is actually one of the
497
+ // reads (or a trimmed copy of it) makes every read look edited. A fully edited
498
+ // sample legitimately has no wild-type read too, so the note is phrased as a
499
+ // check, not as an error.
500
+ if (!alleles.some((allele) => allele.signature === 'wild_type')) {
501
+ notes.push('no read matches the reference exactly; this is expected for a fully edited sample, but if you expected wild-type reads, check that `reference` is the COMPLETE molecule and not one of the reads or a trimmed copy');
502
+ }
503
+
504
+ return {
505
+ reference_length: ref.length,
506
+ circular,
507
+ total_reads: input.length,
508
+ aligned_reads: aligned.length,
509
+ unaligned_reads: unaligned.length,
510
+ unaligned,
511
+ alleles: reported,
512
+ allele_count: reported.length,
513
+ cds_start: cdsStart ?? 0,
514
+ cds_end: cdsEnd ?? 0,
515
+ notes,
516
+ };
517
+ }
package/test/contract.mjs CHANGED
@@ -767,8 +767,8 @@ check('a tool may show the model a picture the way read_image does', () => {
767
767
  // The count is deliberate: it is what catches a NEW picture tool that forgets
768
768
  // the hand-off (or a report tool that quietly grows it).
769
769
  const index = readFileSync(join(packageRoot, 'index.mjs'), 'utf8');
770
- assert.equal((index.match(/image: ATTACHED_IMAGE_SCHEMA/g) ?? []).length, 17, 'all 17 picture tools declare the image output field');
771
- assert.equal((index.match(/\.\.\.ATTACH_IMAGE_PARAM/g) ?? []).length, 17, 'and offer the opt-in attach_image parameter');
770
+ assert.equal((index.match(/image: ATTACHED_IMAGE_SCHEMA/g) ?? []).length, 18, 'all 18 picture tools declare the image output field');
771
+ assert.equal((index.match(/\.\.\.ATTACH_IMAGE_PARAM/g) ?? []).length, 18, 'and offer the opt-in attach_image parameter');
772
772
  assert.ok(/output\.render/.test(index) || index.includes('imageBlockFor(value)'), 'the block builder is wired into define()');
773
773
  });
774
774