Skip to main content

cyanea_align/gpu/
common.rs

1//! Shared host-side logic for GPU alignment: sequence encoding, traceback
2//! reconstruction, and partitioning.
3
4use crate::scoring::ScoringScheme;
5use crate::types::{AlignmentMode, AlignmentResult, CigarOp};
6
7/// Index entry for one sequence pair on the GPU.
8#[derive(Debug, Clone, Copy)]
9pub struct SeqIndex {
10    pub query_offset: u32,
11    pub query_len: u32,
12    pub target_offset: u32,
13    pub target_len: u32,
14}
15
16/// Configuration for GPU batch alignment.
17#[derive(Debug, Clone)]
18pub struct GpuAlignConfig {
19    /// Maximum DP band width (default: 128). Pairs where `|m - n| > max_bandwidth`
20    /// fall back to CPU.
21    pub max_bandwidth: usize,
22    /// Minimum number of pairs before GPU dispatch is worthwhile (default: 64).
23    pub min_pairs_for_gpu: usize,
24}
25
26impl Default for GpuAlignConfig {
27    fn default() -> Self {
28        Self {
29            max_bandwidth: 128,
30            min_pairs_for_gpu: 64,
31        }
32    }
33}
34
35/// Traceback direction encoding (4 bits per cell):
36/// - Bits `[1:0]`: H direction (diag=0, up=1, left=2, stop=3)
37/// - Bit `[2]`: E from H+gap_open (1) vs E+gap_extend (0)
38/// - Bit `[3]`: F from H+gap_open (1) vs F+gap_extend (0)
39pub const TB_DIAG: u8 = 0;
40pub const TB_UP: u8 = 1;
41pub const TB_LEFT: u8 = 2;
42pub const TB_STOP: u8 = 3;
43pub const TB_H_MASK: u8 = 0x03;
44pub const TB_E_OPEN: u8 = 0x04;
45pub const TB_F_OPEN: u8 = 0x08;
46
47/// Encode a nucleotide as a 2-bit value: A=0, C=1, G=2, T/U=3, other=0.
48pub fn encode_base(b: u8) -> u8 {
49    match b.to_ascii_uppercase() {
50        b'A' => 0,
51        b'C' => 1,
52        b'G' => 2,
53        b'T' | b'U' => 3,
54        _ => 0,
55    }
56}
57
58/// Pack sequences into a contiguous buffer for GPU transfer.
59/// Returns (packed bytes, index entries).
60pub fn encode_pairs(pairs: &[(&[u8], &[u8])]) -> (Vec<u8>, Vec<SeqIndex>) {
61    let total_len: usize = pairs.iter().map(|(q, t)| q.len() + t.len()).sum();
62    let mut packed = Vec::with_capacity(total_len);
63    let mut index = Vec::with_capacity(pairs.len());
64
65    for (query, target) in pairs {
66        let q_off = packed.len() as u32;
67        packed.extend_from_slice(query);
68        let t_off = packed.len() as u32;
69        packed.extend_from_slice(target);
70
71        index.push(SeqIndex {
72            query_offset: q_off,
73            query_len: query.len() as u32,
74            target_offset: t_off,
75            target_len: target.len() as u32,
76        });
77    }
78
79    (packed, index)
80}
81
82/// Partition pairs into those suitable for GPU (within bandwidth) and those
83/// that need CPU fallback.
84pub fn partition_pairs<'a>(
85    pairs: &[(&'a [u8], &'a [u8])],
86    max_bandwidth: usize,
87) -> (
88    Vec<(usize, &'a [u8], &'a [u8])>,
89    Vec<(usize, &'a [u8], &'a [u8])>,
90) {
91    let mut gpu_pairs = Vec::new();
92    let mut cpu_pairs = Vec::new();
93
94    for (i, (q, t)) in pairs.iter().enumerate() {
95        let len_diff = if q.len() > t.len() {
96            q.len() - t.len()
97        } else {
98            t.len() - q.len()
99        };
100        if len_diff > max_bandwidth || q.is_empty() || t.is_empty() {
101            cpu_pairs.push((i, *q, *t));
102        } else {
103            gpu_pairs.push((i, *q, *t));
104        }
105    }
106
107    (gpu_pairs, cpu_pairs)
108}
109
110/// Reconstruct an AlignmentResult from GPU traceback data for a single pair.
111///
112/// `traceback` is a flat array of traceback cells for the banded DP matrix.
113/// `score` and `end_pos` come from the GPU output.
114pub fn reconstruct_alignment(
115    query: &[u8],
116    target: &[u8],
117    score: i32,
118    end_i: usize,
119    end_j: usize,
120    traceback: &[u8],
121    bandwidth: usize,
122    mode: AlignmentMode,
123    _scoring: &ScoringScheme,
124) -> AlignmentResult {
125    let m = query.len();
126    let _n = target.len();
127
128    if score == 0 && mode == AlignmentMode::Local {
129        return AlignmentResult {
130            score: 0,
131            aligned_query: Vec::new(),
132            aligned_target: Vec::new(),
133            query_start: 0,
134            query_end: 0,
135            target_start: 0,
136            target_end: 0,
137            cigar: Vec::new(),
138        };
139    }
140
141    let mut aligned_query = Vec::new();
142    let mut aligned_target = Vec::new();
143    let mut cigar_ops: Vec<CigarOp> = Vec::new();
144
145    let mut i = end_i;
146    let mut j = end_j;
147
148    // Walk traceback
149    while i > 0 || j > 0 {
150        if i == 0 && j == 0 {
151            break;
152        }
153
154        // Get band-relative position
155        let band_center = (i as isize * _n as isize) / (m.max(1) as isize);
156        let band_offset = j as isize - band_center + (bandwidth as isize / 2);
157        if band_offset < 0 || band_offset >= bandwidth as isize {
158            break;
159        }
160
161        let tb_idx = i * bandwidth + band_offset as usize;
162        if tb_idx >= traceback.len() {
163            break;
164        }
165
166        let tb = traceback[tb_idx];
167        let h_dir = tb & TB_H_MASK;
168
169        match h_dir {
170            TB_STOP => break,
171            TB_DIAG if i > 0 && j > 0 => {
172                let op = if query[i - 1].to_ascii_uppercase() == target[j - 1].to_ascii_uppercase()
173                {
174                    CigarOp::Match(1)
175                } else {
176                    CigarOp::Mismatch(1)
177                };
178                aligned_query.push(query[i - 1]);
179                aligned_target.push(target[j - 1]);
180                push_cigar(&mut cigar_ops, op);
181                i -= 1;
182                j -= 1;
183            }
184            TB_UP if i > 0 => {
185                aligned_query.push(query[i - 1]);
186                aligned_target.push(b'-');
187                push_cigar(&mut cigar_ops, CigarOp::Deletion(1));
188                i -= 1;
189            }
190            TB_LEFT if j > 0 => {
191                aligned_query.push(b'-');
192                aligned_target.push(target[j - 1]);
193                push_cigar(&mut cigar_ops, CigarOp::Insertion(1));
194                j -= 1;
195            }
196            _ => break,
197        }
198
199        if mode == AlignmentMode::Local {
200            // Check if we've reached a zero-score cell
201            let at_zero = h_dir == TB_STOP;
202            if at_zero {
203                break;
204            }
205        }
206    }
207
208    aligned_query.reverse();
209    aligned_target.reverse();
210    cigar_ops.reverse();
211
212    AlignmentResult {
213        score,
214        aligned_query,
215        aligned_target,
216        query_start: i,
217        query_end: end_i,
218        target_start: j,
219        target_end: end_j,
220        cigar: cigar_ops,
221    }
222}
223
224/// Merge a 1-length CIGAR op with the last op if same variant.
225fn push_cigar(ops: &mut Vec<CigarOp>, op: CigarOp) {
226    if let Some(last) = ops.last_mut() {
227        match (last, &op) {
228            (CigarOp::Match(ref mut n), CigarOp::Match(1)) => {
229                *n += 1;
230                return;
231            }
232            (CigarOp::Mismatch(ref mut n), CigarOp::Mismatch(1)) => {
233                *n += 1;
234                return;
235            }
236            (CigarOp::Insertion(ref mut n), CigarOp::Insertion(1)) => {
237                *n += 1;
238                return;
239            }
240            (CigarOp::Deletion(ref mut n), CigarOp::Deletion(1)) => {
241                *n += 1;
242                return;
243            }
244            _ => {}
245        }
246    }
247    ops.push(op);
248}
249
250/// Extract scoring parameters for GPU transfer (simple nucleotide mode).
251pub fn extract_scoring_params(scoring: &ScoringScheme) -> (i32, i32, i32, i32) {
252    match scoring {
253        ScoringScheme::Simple(m) => (m.match_score, m.mismatch_score, m.gap_open, m.gap_extend),
254        ScoringScheme::Substitution(m) => {
255            // For protein scoring, use gap params; match/mismatch are in the matrix
256            (0, 0, m.gap_open, m.gap_extend)
257        }
258    }
259}
260
261/// Extract the 24x24 substitution matrix as a flat i32 array, or None for simple scoring.
262pub fn extract_substitution_matrix(scoring: &ScoringScheme) -> Option<Vec<i32>> {
263    match scoring {
264        ScoringScheme::Simple(_) => None,
265        ScoringScheme::Substitution(m) => {
266            // Score all pairs to build the matrix
267            let aa_chars = b"ARNDCQEGHILKMFPSTWYVBZX*";
268            let mut matrix = vec![0i32; 24 * 24];
269            for (i, &a) in aa_chars.iter().enumerate() {
270                for (j, &b) in aa_chars.iter().enumerate() {
271                    matrix[i * 24 + j] = m.score_pair(a, b);
272                }
273            }
274            Some(matrix)
275        }
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use crate::scoring::ScoringMatrix;
283
284    #[test]
285    fn encode_base_values() {
286        assert_eq!(encode_base(b'A'), 0);
287        assert_eq!(encode_base(b'C'), 1);
288        assert_eq!(encode_base(b'G'), 2);
289        assert_eq!(encode_base(b'T'), 3);
290        assert_eq!(encode_base(b'a'), 0);
291    }
292
293    #[test]
294    fn encode_pairs_round_trip() {
295        let pairs: Vec<(&[u8], &[u8])> = vec![(b"ACGT", b"TGCA"), (b"AA", b"CC")];
296        let (packed, index) = encode_pairs(&pairs);
297        assert_eq!(packed.len(), 4 + 4 + 2 + 2);
298        assert_eq!(index.len(), 2);
299        assert_eq!(index[0].query_len, 4);
300        assert_eq!(index[0].target_len, 4);
301        assert_eq!(index[1].query_len, 2);
302        assert_eq!(index[1].target_len, 2);
303    }
304
305    #[test]
306    fn partition_within_bandwidth() {
307        let pairs: Vec<(&[u8], &[u8])> = vec![
308            (b"ACGT", b"ACGT"),      // same length, within band
309            (b"A", b"ACGTACGTACGT"), // diff > 8
310        ];
311        let (gpu, cpu) = partition_pairs(&pairs, 8);
312        assert_eq!(gpu.len(), 1);
313        assert_eq!(cpu.len(), 1);
314        assert_eq!(gpu[0].0, 0);
315        assert_eq!(cpu[0].0, 1);
316    }
317
318    #[test]
319    fn extract_dna_scoring() {
320        let scoring = ScoringScheme::Simple(ScoringMatrix::dna_default());
321        let (m, mm, go, ge) = extract_scoring_params(&scoring);
322        assert_eq!(m, 2);
323        assert_eq!(mm, -1);
324        assert_eq!(go, -5);
325        assert_eq!(ge, -2);
326    }
327
328    #[test]
329    fn extract_no_substitution_for_simple() {
330        let scoring = ScoringScheme::Simple(ScoringMatrix::dna_default());
331        assert!(extract_substitution_matrix(&scoring).is_none());
332    }
333}