1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/// Contig data structures for assembled sequences.
///
/// Port of CContigSequence and related types from graphdigger.hpp.
///
/// A contig is a sequence of "chunks", where each chunk contains one or more
/// "variations" (alternative sequences at that position). Non-variable chunks
/// have exactly one variation; variable chunks have multiple (representing SNPs
/// or small indels discovered during assembly).
use crate::model;
/// A variation is a sequence of nucleotide characters
pub type Variation = Vec<char>;
/// Local variants at one position: a list of alternative sequences
pub type LocalVariants = Vec<Variation>;
/// Fork type flags
pub mod fork_type {
pub const NO_FORK: u8 = 0;
pub const LEFT_FORK: u8 = 1;
pub const RIGHT_FORK: u8 = 2;
pub const LEFT_BRANCH: u8 = 4;
pub const RIGHT_BRANCH: u8 = 8;
pub const SECONDARY_KMER: u8 = 16;
}
/// A contig sequence: vector of chunks, each chunk containing variant sequences.
#[derive(Clone, Debug)]
pub struct ContigSequence {
/// Chunks of the contig. Each chunk is a list of alternative sequences.
pub chunks: Vec<LocalVariants>,
/// Number of bases at the left end that could be in a repeat region
pub left_repeat: i32,
/// Number of bases at the right end that could be in a repeat region
pub right_repeat: i32,
/// Whether this contig is circular
pub circular: bool,
/// Canonical k-mer key of the denied node at the left end (where extension stopped)
/// None if extension reached a dead end (no successor)
pub left_endpoint: Option<Vec<u64>>,
/// Canonical k-mer key of the denied node at the right end
pub right_endpoint: Option<Vec<u64>>,
/// Seed-only oriented denied node key for the left end, matching C++
/// `m_next_left` semantics used by `ConnectFragments`.
pub left_endpoint_oriented: Option<Vec<u64>>,
/// Seed-only oriented denied node key for the right end, matching C++
/// `m_next_right` semantics used by `ConnectFragments`.
pub right_endpoint_oriented: Option<Vec<u64>>,
/// Number of newly assembled bases on the left end that could be clipped.
/// Mirrors C++ `SContig::m_left_extend` (graphdigger.hpp:54). Initialised
/// to the contig length on creation; ConnectAndExtendContigs / iteration
/// boundaries should clip these counts to bound trustless extensions.
pub left_extend: i32,
/// Same as `left_extend` but for the right end (`SContig::m_right_extend`).
pub right_extend: i32,
}
impl ContigSequence {
pub fn new() -> Self {
ContigSequence {
chunks: Vec::new(),
left_repeat: 0,
right_repeat: 0,
circular: false,
left_endpoint: None,
right_endpoint: None,
left_endpoint_oriented: None,
right_endpoint_oriented: None,
left_extend: 0,
right_extend: 0,
}
}
/// Number of chunks
pub fn len(&self) -> usize {
self.chunks.len()
}
pub fn is_empty(&self) -> bool {
self.chunks.is_empty()
}
/// Number of variants in a chunk
pub fn variants_number(&self, chunk: usize) -> usize {
self.chunks[chunk].len()
}
/// Whether a chunk has exactly one variant (unique/non-variable)
pub fn unique_chunk(&self, chunk: usize) -> bool {
self.chunks[chunk].len() == 1
}
/// Whether a chunk has multiple variants (variable/polymorphic)
pub fn variable_chunk(&self, chunk: usize) -> bool {
self.chunks[chunk].len() > 1
}
/// Maximum length of any variant in a chunk
pub fn chunk_len_max(&self, chunk: usize) -> usize {
self.chunks[chunk]
.iter()
.map(|v| v.len())
.max()
.unwrap_or(0)
}
/// Minimum length of any variant in a chunk
pub fn chunk_len_min(&self, chunk: usize) -> usize {
self.chunks[chunk]
.iter()
.map(|v| v.len())
.min()
.unwrap_or(0)
}
/// Maximum total length (sum of max chunk lengths)
pub fn len_max(&self) -> usize {
(0..self.chunks.len()).map(|i| self.chunk_len_max(i)).sum()
}
/// Minimum total length (sum of min chunk lengths)
pub fn len_min(&self) -> usize {
(0..self.chunks.len()).map(|i| self.chunk_len_min(i)).sum()
}
/// Insert a new empty chunk at the end
pub fn insert_new_chunk(&mut self) {
self.chunks.push(Vec::new());
}
/// Insert a new chunk with one variant
pub fn insert_new_chunk_with(&mut self, seq: Variation) {
self.chunks.push(vec![seq]);
}
/// Insert a new empty variant at the front of the last chunk
pub fn insert_new_variant(&mut self) {
if let Some(last) = self.chunks.last_mut() {
last.insert(0, Vec::new());
}
}
/// Insert a new single-char variant at the front of the last chunk
pub fn insert_new_variant_char(&mut self, c: char) {
if let Some(last) = self.chunks.last_mut() {
last.insert(0, vec![c]);
}
}
/// Insert a new variant from a slice at the front of the last chunk
pub fn insert_new_variant_slice(&mut self, seq: &[char]) {
if let Some(last) = self.chunks.last_mut() {
last.insert(0, seq.to_vec());
}
}
/// Extend the first variant of the last chunk with a character
pub fn extend_top_variant(&mut self, c: char) {
if let Some(last) = self.chunks.last_mut() {
if let Some(first) = last.first_mut() {
first.push(c);
}
}
}
/// Extend the first variant of the last chunk with a slice
pub fn extend_top_variant_slice(&mut self, seq: &[char]) {
if let Some(last) = self.chunks.last_mut() {
if let Some(first) = last.first_mut() {
first.extend_from_slice(seq);
}
}
}
/// Sort variants within each chunk for stable ordering
pub fn stabilize_variants_order(&mut self) {
for chunk in &mut self.chunks {
chunk.sort();
}
}
/// Reverse complement the entire contig
pub fn reverse_complement(&mut self) {
std::mem::swap(&mut self.left_repeat, &mut self.right_repeat);
self.chunks.reverse();
for chunk in &mut self.chunks {
for seq in chunk.iter_mut() {
model::reverse_complement_seq(seq);
}
}
self.stabilize_variants_order();
}
/// Get the primary (first variant of each chunk) sequence as a string
pub fn primary_sequence(&self) -> String {
let len = self
.chunks
.iter()
.filter_map(|chunk| chunk.first())
.map(|variant| variant.len())
.sum();
let mut result = String::with_capacity(len);
for chunk in &self.chunks {
if let Some(first) = chunk.first() {
result.extend(first.iter());
}
}
result
}
/// Access chunk variants
pub fn chunk(&self, idx: usize) -> &LocalVariants {
&self.chunks[idx]
}
/// Clip `n` bases from the left end of the contig.
/// Removes entire chunks if they fit within the clip, truncates the first remaining chunk.
pub fn clip_left(&mut self, n: usize) {
let mut remaining = n;
while remaining > 0 && !self.chunks.is_empty() {
let chunk_len = self.chunk_len_max(0);
if chunk_len <= remaining {
remaining -= chunk_len;
self.chunks.remove(0);
} else {
for variant in &mut self.chunks[0] {
let clip = remaining.min(variant.len());
variant.drain(..clip);
}
remaining = 0;
}
}
}
/// Clip `n` bases from the right end of the contig.
pub fn clip_right(&mut self, n: usize) {
let mut remaining = n;
while remaining > 0 && !self.chunks.is_empty() {
let last = self.chunks.len() - 1;
let chunk_len = self.chunk_len_max(last);
if chunk_len <= remaining {
remaining -= chunk_len;
self.chunks.pop();
} else {
for variant in &mut self.chunks[last] {
let clip = remaining.min(variant.len());
variant.truncate(variant.len() - clip);
}
remaining = 0;
}
}
}
}
impl Default for ContigSequence {
fn default() -> Self {
Self::new()
}
}
// Ordering by primary sequence length (descending) for sorting contigs
impl PartialEq for ContigSequence {
fn eq(&self, other: &Self) -> bool {
self.primary_sequence() == other.primary_sequence()
}
}
impl Eq for ContigSequence {}
impl PartialOrd for ContigSequence {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ContigSequence {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// Sort by length descending, then by sequence for stability
other
.len_min()
.cmp(&self.len_min())
.then_with(|| self.primary_sequence().cmp(&other.primary_sequence()))
}
}
/// A list of contigs (matches C++ TContigSequenceList = list<CContigSequence>)
pub type ContigSequenceList = Vec<ContigSequence>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_contig_basic() {
let mut contig = ContigSequence::new();
contig.insert_new_chunk_with("ACGT".chars().collect());
assert_eq!(contig.len(), 1);
assert_eq!(contig.len_max(), 4);
assert!(contig.unique_chunk(0));
assert!(!contig.variable_chunk(0));
}
#[test]
fn test_contig_variable_chunk() {
let mut contig = ContigSequence::new();
contig
.chunks
.push(vec!["ACGT".chars().collect(), "ACGA".chars().collect()]);
assert!(contig.variable_chunk(0));
assert_eq!(contig.variants_number(0), 2);
}
#[test]
fn test_contig_primary_sequence() {
let mut contig = ContigSequence::new();
contig.insert_new_chunk_with("ACGT".chars().collect());
contig.insert_new_chunk_with("TTGG".chars().collect());
assert_eq!(contig.primary_sequence(), "ACGTTTGG");
}
#[test]
fn test_contig_reverse_complement() {
let mut contig = ContigSequence::new();
contig.insert_new_chunk_with("ACGT".chars().collect());
contig.left_repeat = 5;
contig.right_repeat = 10;
contig.reverse_complement();
assert_eq!(contig.primary_sequence(), "ACGT"); // ACGT is its own revcomp
assert_eq!(contig.left_repeat, 10);
assert_eq!(contig.right_repeat, 5);
}
#[test]
fn test_contig_ordering() {
let mut c1 = ContigSequence::new();
c1.insert_new_chunk_with("ACGT".chars().collect());
let mut c2 = ContigSequence::new();
c2.insert_new_chunk_with("ACGTACGT".chars().collect());
// Longer contig should sort first (descending by length)
assert!(c2 < c1);
}
#[test]
fn test_extend_top_variant() {
let mut contig = ContigSequence::new();
contig.insert_new_chunk();
contig.insert_new_variant();
contig.extend_top_variant('A');
contig.extend_top_variant('C');
assert_eq!(contig.chunks[0][0], vec!['A', 'C']);
}
}