@jbrowse/cigar-utils 4.1.14

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 (47) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +167 -0
  3. package/esm/bamSeqDecoder.d.ts +3 -0
  4. package/esm/bamSeqDecoder.js +10 -0
  5. package/esm/bamSeqEncoder.d.ts +8 -0
  6. package/esm/bamSeqEncoder.js +33 -0
  7. package/esm/buildReadVsRefFeatures.d.ts +57 -0
  8. package/esm/buildReadVsRefFeatures.js +66 -0
  9. package/esm/cigarConstants.d.ts +11 -0
  10. package/esm/cigarConstants.js +15 -0
  11. package/esm/cigarRenderedSegments.d.ts +13 -0
  12. package/esm/cigarRenderedSegments.js +84 -0
  13. package/esm/cigarReorient.d.ts +2 -0
  14. package/esm/cigarReorient.js +29 -0
  15. package/esm/cigarToMismatches2.d.ts +2 -0
  16. package/esm/cigarToMismatches2.js +90 -0
  17. package/esm/cigarWalkStart.d.ts +4 -0
  18. package/esm/cigarWalkStart.js +54 -0
  19. package/esm/csOps.d.ts +47 -0
  20. package/esm/csOps.js +152 -0
  21. package/esm/csToCigar.d.ts +1 -0
  22. package/esm/csToCigar.js +43 -0
  23. package/esm/getNextRefPos.d.ts +31 -0
  24. package/esm/getNextRefPos.js +69 -0
  25. package/esm/index.d.ts +24 -0
  26. package/esm/index.js +24 -0
  27. package/esm/mdToMismatches2.d.ts +2 -0
  28. package/esm/mdToMismatches2.js +108 -0
  29. package/esm/mismatchCallback.d.ts +29 -0
  30. package/esm/mismatchCallback.js +20 -0
  31. package/esm/mismatchParser.d.ts +79 -0
  32. package/esm/mismatchParser.js +238 -0
  33. package/esm/mismatchTypes.d.ts +27 -0
  34. package/esm/mismatchTypes.js +1 -0
  35. package/esm/numericCigarHasSkip.d.ts +1 -0
  36. package/esm/numericCigarHasSkip.js +11 -0
  37. package/esm/numericCigarToString.d.ts +1 -0
  38. package/esm/numericCigarToString.js +13 -0
  39. package/esm/orientAlignment.d.ts +9 -0
  40. package/esm/orientAlignment.js +26 -0
  41. package/esm/pafIdentity.d.ts +20 -0
  42. package/esm/pafIdentity.js +31 -0
  43. package/esm/readEndpoints.d.ts +18 -0
  44. package/esm/readEndpoints.js +69 -0
  45. package/esm/samFlags.d.ts +50 -0
  46. package/esm/samFlags.js +89 -0
  47. package/package.json +42 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2020] [Evolutionary Software Foundation]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,167 @@
1
+ # @jbrowse/cigar-utils
2
+
3
+ Pure CIGAR / MD / mismatch parsers and types — no rendering or framework deps
4
+
5
+ <!-- API_DOCS_START -->
6
+
7
+ ## API
8
+
9
+ Auto-generated from `#api` JSDoc tags in this package. Do not edit by hand.
10
+
11
+ ### buildReadVsRefFeatures
12
+
13
+ Decompose one alignment record plus its SA tag into the segments of the split
14
+ read, ordered along the read. The layer above `featurizeSA`: it folds the record
15
+ itself in as one more segment, in the same normalized read coordinate space the
16
+ SA entries are put in, and pairs each segment with a `mate` describing its span
17
+ on the read.
18
+
19
+ This is what the "read vs ref" launchers (linear synteny + dotplot) draw against
20
+ a synthetic read assembly, and what the alignments feature-detail widget lists
21
+ split-read junctions from.
22
+
23
+ `getCanonicalRefName` resolves each segment's refName against the reference
24
+ assembly's aliases: a BAM whose header says `chr1` against a FASTA whose refName
25
+ is `1` otherwise yields regions no track can be opened on. Optional only because
26
+ a caller may not have the assembly in hand; pass it when you do.
27
+
28
+ ```js
29
+ // type signature
30
+ (feature: ReadVsRefInput, getCanonicalRefName?: ((refName: string) => string | undefined) | undefined) => ReadVsRefFeatures
31
+ ```
32
+
33
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/buildReadVsRefFeatures.ts)
34
+
35
+ ### featurizeSAEntries
36
+
37
+ featurizeSA over pre-split entries (see splitSA). Lets a caller filter the
38
+ entries first — e.g. deduplicating the records repeated across a split read's
39
+ segments — without paying to split and rejoin the tag around the filter.
40
+
41
+ ```js
42
+ // type signature
43
+ (entries: string[], id: string, strand: number | undefined, readName: string | undefined, normalize?: boolean | undefined) => {…}[]
44
+ ```
45
+
46
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
47
+
48
+ ### getLength
49
+
50
+ Length of the read sequence (sum of all ops except D/N).
51
+
52
+ ```js
53
+ // type signature
54
+ (cigar: string) => number
55
+ ```
56
+
57
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
58
+
59
+ ### getLengthOnRef
60
+
61
+ Length the read spans on the reference (sum of M/=/X/D/N ops).
62
+
63
+ ```js
64
+ // type signature
65
+ (cigar: string) => number
66
+ ```
67
+
68
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
69
+
70
+ ### getMismatches
71
+
72
+ Computes the list of mismatches (SNVs, indels, clips, skips) for a read from its
73
+ CIGAR, optional MD tag, sequence, reference, and quality.
74
+
75
+ ```js
76
+ // type signature
77
+ (cigar?: string | undefined, md?: string | undefined, seq?: string | undefined, ref?: string | undefined, qual?: Uint8Array<ArrayBufferLike> | undefined) => Mismatch[]
78
+ ```
79
+
80
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
81
+
82
+ ### getNextRefPos
83
+
84
+ Maps read-sequence positions to reference-sequence positions via the CIGAR,
85
+ invoking the callback for each. Handles both packed Uint32Array and unpacked
86
+ number[] CIGAR formats.
87
+
88
+ **Driven by the POSITIONS, not by the read bases.** This used to run an inner
89
+ loop over every base an op spans, testing `positions[currPos] === readPos + j` —
90
+ so it was O(read length) to find something O(positions) in size. On the full
91
+ extent of `200x.longread.mod.bam` that is 43.7 Mbp of read sequence scanned to
92
+ place 0.84M modification calls. Within one op the read-to-reference offset is a
93
+ constant, so each position's answer is one addition and the ops only have to be
94
+ walked once: O(positions + ops).
95
+ `plugins/alignments/benches/cigarWalkShape.bench.ts` prices it at **1.17x on the
96
+ whole per-read modification pipeline**, of which this walk is 45%.
97
+
98
+ **1.17x is the whole of it, and does not grow on a cleaner alignment.** The
99
+ first reading of that gap was that the op loop caps it — these reads carry 7,000
100
+ ops apiece, and neither shape avoids the op loop. `cigarOpDensity.bench.ts`
101
+ sweeps op density over a 5,000x range and the ratio stays between 1.10x and
102
+ 1.18x, so that reading was wrong: what this phase is bound by is the per-CALL
103
+ work both shapes share — the callback, the ML lookup, the compare, the write —
104
+ not the traversal that differs. Changing how the scan is shaped therefore has a
105
+ low ceiling here, however lopsided the iteration counts look.
106
+
107
+ `positions` must be ASCENDING, which every caller's producer guarantees. The one
108
+ behaviour that changed with the shape: a REPEATED position used to be dropped
109
+ and to block every position after it (the per-base loop could match at most one
110
+ position per base offset), and now emits once per occurrence.
111
+
112
+ ```js
113
+ // type signature
114
+ (cigarOps: ArrayLike<number>, positions: number[], callback: (ref: number, idx: number) => void) => void
115
+ ```
116
+
117
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/getNextRefPos.ts)
118
+
119
+ ### parseCigar
120
+
121
+ Parses a CIGAR string to an alternating `[length, op, ...]` string array.
122
+
123
+ ```js
124
+ // type signature
125
+ (s?: string) => string[]
126
+ ```
127
+
128
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
129
+
130
+ ### parseCigar2
131
+
132
+ Parses a CIGAR string to a packed number array where each value is
133
+ `(length << 4) | opIndex`.
134
+
135
+ ```js
136
+ // type signature
137
+ (s?: string) => number[]
138
+ ```
139
+
140
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
141
+
142
+ ### parseCigar2Typed
143
+
144
+ Same encoding as `parseCigar2` but writes into a packed `Uint32Array` — matches
145
+ the NUMERIC_CIGAR format that BAM/CRAM adapters emit, so consumers can use a
146
+ single typed-array code path.
147
+
148
+ ```js
149
+ // type signature
150
+ (s?: string) => Uint32Array<ArrayBuffer>
151
+ ```
152
+
153
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
154
+
155
+ ### splitSA
156
+
157
+ The `;`-separated alignment records of an SA tag, empties dropped — the input
158
+ `featurizeSAEntries` expects.
159
+
160
+ ```js
161
+ // type signature
162
+ (SA: string) => string[]
163
+ ```
164
+
165
+ [Source code](https://github.com/GMOD/jbrowse-components/blob/main/packages/cigar-utils/src/mismatchParser.ts)
166
+
167
+ <!-- API_DOCS_END -->
@@ -0,0 +1,3 @@
1
+ export declare const SEQRET = "=ACMGRSVTWYHKDBN";
2
+ export declare const SEQRET_NUMERIC_DECODER: Uint8Array<ArrayBuffer>;
3
+ export declare const CHAR_FROM_CODE: string[];
@@ -0,0 +1,10 @@
1
+ // BAM 4-bit encoded sequence lookup table
2
+ export const SEQRET = '=ACMGRSVTWYHKDBN';
3
+ // Numeric decoder - returns char codes directly (lowercase for case-insensitive comparison)
4
+ // '=' = 61, 'a' = 97, 'c' = 99, 'm' = 109, 'g' = 103, 'r' = 114, 's' = 115, 'v' = 118,
5
+ // 't' = 116, 'w' = 119, 'y' = 121, 'h' = 104, 'k' = 107, 'd' = 100, 'b' = 98, 'n' = 110
6
+ export const SEQRET_NUMERIC_DECODER = new Uint8Array([
7
+ 61, 97, 99, 109, 103, 114, 115, 118, 116, 119, 121, 104, 107, 100, 98, 110,
8
+ ]);
9
+ // Pre-computed char lookup for ASCII codes (avoids String.fromCharCode in hot loops)
10
+ export const CHAR_FROM_CODE = Array.from({ length: 128 }, (_, i) => String.fromCharCode(i));
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Pack a SEQ string into BAM's 4-bit-per-base encoding, two bases per byte with
3
+ * the first base in the high nibble — the layout `@gmod/bam`'s `forEachMismatchNumeric` reads
4
+ * via `(byte >> ((1 - (i & 1)) << 2)) & 0xf`. Lets a text source (SAM, a
5
+ * PSL-derived alignment) drive the same zero-allocation mismatch walk that
6
+ * BAM's own packed sequence does.
7
+ */
8
+ export declare function encodeSeqNumeric(seq: string): Uint8Array<ArrayBuffer>;
@@ -0,0 +1,33 @@
1
+ import { SEQRET } from './bamSeqDecoder.js';
2
+ // char code -> 4-bit nibble, the inverse of SEQRET. Unrecognized characters
3
+ // (including lowercase, IUPAC codes we don't list, and '.') land on 'N' (15),
4
+ // which the mismatch walk compares equal to nothing.
5
+ const NIBBLE_FROM_CHAR_CODE = (() => {
6
+ const table = new Uint8Array(128).fill(15);
7
+ for (let i = 0; i < SEQRET.length; i++) {
8
+ const code = SEQRET.charCodeAt(i);
9
+ table[code] = i;
10
+ table[code | 0x20] = i;
11
+ }
12
+ return table;
13
+ })();
14
+ /**
15
+ * Pack a SEQ string into BAM's 4-bit-per-base encoding, two bases per byte with
16
+ * the first base in the high nibble — the layout `@gmod/bam`'s `forEachMismatchNumeric` reads
17
+ * via `(byte >> ((1 - (i & 1)) << 2)) & 0xf`. Lets a text source (SAM, a
18
+ * PSL-derived alignment) drive the same zero-allocation mismatch walk that
19
+ * BAM's own packed sequence does.
20
+ */
21
+ export function encodeSeqNumeric(seq) {
22
+ const out = new Uint8Array((seq.length + 1) >> 1);
23
+ for (let i = 0; i < seq.length; i += 2) {
24
+ const hiCode = seq.charCodeAt(i);
25
+ const hi = hiCode < 128 ? NIBBLE_FROM_CHAR_CODE[hiCode] : 15;
26
+ // the odd base of a final unpaired byte reads as '=' (0), which is what a
27
+ // BAM's own trailing nibble holds
28
+ const loCode = i + 1 < seq.length ? seq.charCodeAt(i + 1) : -1;
29
+ const lo = loCode < 0 ? 0 : loCode < 128 ? NIBBLE_FROM_CHAR_CODE[loCode] : 15;
30
+ out[i >> 1] = (hi << 4) | lo;
31
+ }
32
+ return out;
33
+ }
@@ -0,0 +1,57 @@
1
+ export interface ReadVsRefMate {
2
+ refName: string;
3
+ start: number;
4
+ end: number;
5
+ syntenyId: number;
6
+ uniqueId: string;
7
+ }
8
+ export interface ReadVsRefFeature {
9
+ refName: string;
10
+ start: number;
11
+ end: number;
12
+ strand: number;
13
+ CIGAR: string;
14
+ clipLengthAtStartOfRead: number;
15
+ uniqueId: string;
16
+ seqLength?: number;
17
+ syntenyId: number;
18
+ mate: ReadVsRefMate;
19
+ [key: string]: unknown;
20
+ }
21
+ export interface ReadVsRefInput {
22
+ uniqueId: string;
23
+ refName: string;
24
+ start: number;
25
+ end: number;
26
+ CIGAR?: string;
27
+ flags?: number;
28
+ strand?: number;
29
+ name?: string;
30
+ seq?: string;
31
+ tags?: Record<string, unknown>;
32
+ [key: string]: unknown;
33
+ }
34
+ export interface ReadVsRefFeatures {
35
+ features: ReadVsRefFeature[];
36
+ totalLength: number;
37
+ readName: string;
38
+ seq: string | undefined;
39
+ }
40
+ /**
41
+ * #api
42
+ * Decompose one alignment record plus its SA tag into the segments of the split
43
+ * read, ordered along the read. The layer above `featurizeSA`: it folds the
44
+ * record itself in as one more segment, in the same normalized read coordinate
45
+ * space the SA entries are put in, and pairs each segment with a `mate`
46
+ * describing its span on the read.
47
+ *
48
+ * This is what the "read vs ref" launchers (linear synteny + dotplot) draw
49
+ * against a synthetic read assembly, and what the alignments feature-detail
50
+ * widget lists split-read junctions from.
51
+ *
52
+ * `getCanonicalRefName` resolves each segment's refName against the reference
53
+ * assembly's aliases: a BAM whose header says `chr1` against a FASTA whose
54
+ * refName is `1` otherwise yields regions no track can be opened on. Optional
55
+ * only because a caller may not have the assembly in hand; pass it when you do.
56
+ */
57
+ export declare function buildReadVsRefFeatures(feature: ReadVsRefInput, getCanonicalRefName?: (refName: string) => string | undefined): ReadVsRefFeatures;
@@ -0,0 +1,66 @@
1
+ import { featurizeSA, getClip, getLength, getLengthSansClipping, } from './mismatchParser.js';
2
+ import { SAM_FLAG_SUPPLEMENTARY } from './samFlags.js';
3
+ /**
4
+ * #api
5
+ * Decompose one alignment record plus its SA tag into the segments of the split
6
+ * read, ordered along the read. The layer above `featurizeSA`: it folds the
7
+ * record itself in as one more segment, in the same normalized read coordinate
8
+ * space the SA entries are put in, and pairs each segment with a `mate`
9
+ * describing its span on the read.
10
+ *
11
+ * This is what the "read vs ref" launchers (linear synteny + dotplot) draw
12
+ * against a synthetic read assembly, and what the alignments feature-detail
13
+ * widget lists split-read junctions from.
14
+ *
15
+ * `getCanonicalRefName` resolves each segment's refName against the reference
16
+ * assembly's aliases: a BAM whose header says `chr1` against a FASTA whose
17
+ * refName is `1` otherwise yields regions no track can be opened on. Optional
18
+ * only because a caller may not have the assembly in hand; pass it when you do.
19
+ */
20
+ export function buildReadVsRefFeatures(feature, getCanonicalRefName) {
21
+ const { CIGAR: cigar = '', flags = 0, strand, name: readName = '', seq, tags, uniqueId, } = feature;
22
+ const SA = tags?.SA;
23
+ const suppAlns = featurizeSA(typeof SA === 'string' ? SA : undefined, uniqueId, strand, readName, true);
24
+ // getClip(cigar, 1), not getClip(cigar, strand): `normalize` puts every SA
25
+ // entry in the *query's reference orientation*, so the record itself has to be
26
+ // measured in that frame too. Measuring it in the read's own 5'->3' frame
27
+ // reads the clip off the far end of a reverse-strand CIGAR, which drops the
28
+ // primary into the wrong place along the read and mis-sorts the segments.
29
+ const clipLengthAtStartOfRead = getClip(cigar, 1);
30
+ const primary = {
31
+ ...feature,
32
+ clipLengthAtStartOfRead,
33
+ strand: 1,
34
+ mate: {
35
+ refName: readName,
36
+ start: clipLengthAtStartOfRead,
37
+ end: clipLengthAtStartOfRead + getLengthSansClipping(cigar),
38
+ },
39
+ };
40
+ // A supplementary CIGAR covers only its own slice of the read, so its own
41
+ // length is the read length only when the aligner emitted the clipping ops.
42
+ // SA[0] is the primary by convention. `?? cigar` covers a supplementary with
43
+ // no SA tag at all, which has nothing better to measure against.
44
+ const totalLength = getLength((flags & SAM_FLAG_SUPPLEMENTARY ? suppAlns[0]?.CIGAR : undefined) ?? cigar);
45
+ const features = [primary, ...suppAlns]
46
+ .sort((a, b) => a.clipLengthAtStartOfRead - b.clipLengthAtStartOfRead)
47
+ // syntenyId is assigned after the sort so it also reads as the segment's
48
+ // index along the read; the mate shares it, which is how the synteny
49
+ // renderer pairs the two sides of one alignment.
50
+ .map((f, idx) => ({
51
+ ...f,
52
+ refName: getCanonicalRefName?.(f.refName) ?? f.refName,
53
+ syntenyId: idx,
54
+ mate: { ...f.mate, syntenyId: idx, uniqueId: `${f.uniqueId}_mate` },
55
+ }));
56
+ return {
57
+ features,
58
+ totalLength,
59
+ readName,
60
+ // Only hand back bases that line up with the read coordinate system the
61
+ // synthetic assembly is built in. A hard-clipped supplementary's SEQ is its
62
+ // own slice, and the sequence track would show it at the wrong offset with
63
+ // nothing marking it as partial; no sequence beats a wrong one.
64
+ seq: seq && seq.length >= totalLength ? seq : undefined,
65
+ };
66
+ }
@@ -0,0 +1,11 @@
1
+ export declare const CIGAR_M = 0;
2
+ export declare const CIGAR_I = 1;
3
+ export declare const CIGAR_D = 2;
4
+ export declare const CIGAR_N = 3;
5
+ export declare const CIGAR_S = 4;
6
+ export declare const CIGAR_H = 5;
7
+ export declare const CIGAR_P = 6;
8
+ export declare const CIGAR_EQ = 7;
9
+ export declare const CIGAR_X = 8;
10
+ export declare const CIGAR_M_EQ_MASK = 129;
11
+ export declare const CIGAR_INDEL_MASK = 14;
@@ -0,0 +1,15 @@
1
+ // CIGAR operation indices from BAM spec (used in packed Uint32Array format: len<<4|op)
2
+ export const CIGAR_M = 0;
3
+ export const CIGAR_I = 1;
4
+ export const CIGAR_D = 2;
5
+ export const CIGAR_N = 3;
6
+ export const CIGAR_S = 4;
7
+ export const CIGAR_H = 5;
8
+ export const CIGAR_P = 6;
9
+ export const CIGAR_EQ = 7;
10
+ export const CIGAR_X = 8;
11
+ // Bitmask for CIGAR operation categories (use with: (1 << op) & MASK)
12
+ // Alignment match ops (M=0, ==7) — may contain mismatches, need MD tag
13
+ export const CIGAR_M_EQ_MASK = 0b10000001; // (1<<0)|(1<<7) = 129
14
+ // Indel ops (I=1, D=2, N=3) — each consumes only one axis (a gap on the other)
15
+ export const CIGAR_INDEL_MASK = 0b00001110; // (1<<1)|(1<<2)|(1<<3) = 14
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Walks pre-parsed (packed int) CIGAR ops in bp-space and fires a callback
3
+ * for each rendered segment. Small indels (width < MIN_INDEL_PX) are merged
4
+ * into surrounding context; tiny M segments (both accumulators advance <
5
+ * bpPerPx) are accumulated before emitting.
6
+ *
7
+ * Used by synteny and dotplot GPU renderers so both stay in sync.
8
+ * Re-exported via @jbrowse/synteny-core for consistent import paths.
9
+ *
10
+ * Callback receives bp-space segment boundaries (cumBp, no inter-region
11
+ * padding). Callers convert to screen positions with hp-math.
12
+ */
13
+ export declare function visitCigarRenderedSegments(cigar: ArrayLike<number>, startBp1: number, startBp2: number, bpPerPx0: number, bpPerPx1: number, rev1: number, rev2: number, callback: (op: number, segBp1Start: number, segBp1End: number, segBp2Start: number, segBp2End: number) => void): void;