primer3 0.1.0

Safe Rust bindings to the primer3 primer design library
Documentation
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Per-sequence arguments for primer design.
//!
//! [`SequenceArgs`] describes the template sequence and regions of interest,
//! equivalent to the `seq_args` dictionary in primer3-py.

use crate::error::{Primer3Error, Result};

/// A genomic interval as (start, length), both 0-based.
///
/// `start` is a 0-based offset into the sequence. `length` is the number
/// of bases in the interval. The interval covers positions
/// `[start, start + length)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Interval {
    /// 0-based start position.
    pub start: usize,
    /// Length in bases.
    pub length: usize,
}

impl Interval {
    /// Creates a new interval from a start position and length.
    ///
    /// # Arguments
    ///
    /// * `start` - 0-based start position in the sequence
    /// * `length` - number of bases in the interval
    pub fn new(start: usize, length: usize) -> Self {
        Self { start, length }
    }

    /// Returns the exclusive end position (`start + length`).
    pub fn end(&self) -> usize {
        self.start + self.length
    }
}

impl From<(usize, usize)> for Interval {
    fn from((start, length): (usize, usize)) -> Self {
        Self { start, length }
    }
}

impl From<Interval> for std::ops::Range<usize> {
    fn from(interval: Interval) -> Self {
        interval.start..interval.end()
    }
}

/// A pair of OK regions for left and right primers.
///
/// Each element is `Some(Interval)` for a constrained region, or
/// `None` for "any position is OK".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OkRegionPair {
    /// Acceptable region for the left primer, or `None` for any.
    pub left: Option<Interval>,
    /// Acceptable region for the right primer, or `None` for any.
    pub right: Option<Interval>,
}

/// Per-sequence arguments for primer design.
///
/// Contains the template sequence and optional annotations like target regions,
/// excluded regions, quality scores, and pre-specified primers.
///
/// Construct with [`SequenceArgs::builder()`].
///
/// # Example
///
/// ```no_run
/// use primer3::SequenceArgs;
///
/// let args = SequenceArgs::builder()
///     .sequence_id("my_gene")
///     .sequence("ATCGATCGATCG...")
///     .target(100, 200)  // start=100, length=200 bases
///     .excluded_region(50, 20)  // start=50, length=20 bases
///     .included_region(0, 500)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SequenceArgs {
    /// An identifier for this sequence.
    pub sequence_id: Option<String>,
    /// The template DNA sequence.
    pub sequence: String,

    /// Target regions: primers must flank at least one of these.
    pub targets: Vec<Interval>,
    /// Excluded regions: primers must not overlap these.
    pub excluded_regions: Vec<Interval>,
    /// Excluded regions for internal oligos.
    pub internal_excluded_regions: Vec<Interval>,
    /// Acceptable region pairs for primer placement.
    pub ok_regions: Vec<OkRegionPair>,

    /// Positions where a primer must overlap (junction overlap).
    pub primer_overlap_junctions: Vec<usize>,
    /// Positions where an internal oligo must overlap.
    pub internal_overlap_junctions: Vec<usize>,

    /// Start of the included region (0-based, default: 0).
    pub included_region_start: usize,
    /// Length of the included region (default: entire sequence).
    pub included_region_length: Option<usize>,

    /// Per-base quality scores (signed; the C library uses `int`).
    pub quality: Option<Vec<i32>>,

    /// A pre-specified left primer sequence to check or design around.
    pub left_primer: Option<String>,
    /// A pre-specified right primer sequence to check or design around.
    pub right_primer: Option<String>,
    /// A pre-specified internal oligo sequence to check or design around.
    pub internal_oligo: Option<String>,

    /// Forced 5' start position for left primer.
    pub force_left_start: Option<usize>,
    /// Forced 3' end position for left primer.
    pub force_left_end: Option<usize>,
    /// Forced 5' start position for right primer.
    /// For right primers, this is the 5' (rightmost) position.
    pub force_right_start: Option<usize>,
    /// Forced 3' end position for right primer.
    /// For right primers, this is the 3' (leftmost) position.
    pub force_right_end: Option<usize>,

    /// Overhang sequence added to the 5' end of the left primer.
    pub overhang_left: Option<String>,
    /// Overhang sequence added to the 5' end of the right primer.
    pub overhang_right: Option<String>,
}

impl SequenceArgs {
    /// Creates a new builder.
    pub fn builder() -> SequenceArgsBuilder {
        SequenceArgsBuilder {
            args: SequenceArgs {
                sequence_id: None,
                sequence: String::new(),
                targets: Vec::new(),
                excluded_regions: Vec::new(),
                internal_excluded_regions: Vec::new(),
                ok_regions: Vec::new(),
                primer_overlap_junctions: Vec::new(),
                internal_overlap_junctions: Vec::new(),
                included_region_start: 0,
                included_region_length: None,
                quality: None,
                left_primer: None,
                right_primer: None,
                internal_oligo: None,
                force_left_start: None,
                force_left_end: None,
                force_right_start: None,
                force_right_end: None,
                overhang_left: None,
                overhang_right: None,
            },
        }
    }
}

/// Builder for [`SequenceArgs`].
#[derive(Debug, Clone)]
pub struct SequenceArgsBuilder {
    args: SequenceArgs,
}

impl SequenceArgsBuilder {
    /// Sets the sequence identifier.
    pub fn sequence_id(mut self, id: impl Into<String>) -> Self {
        self.args.sequence_id = Some(id.into());
        self
    }

    /// Sets the template DNA sequence.
    pub fn sequence(mut self, seq: impl Into<String>) -> Self {
        self.args.sequence = seq.into();
        self
    }

    /// Adds a target region.
    ///
    /// # Arguments
    ///
    /// * `start` - 0-based start position in the sequence
    /// * `length` - length of the target in bases
    pub fn target(mut self, start: usize, length: usize) -> Self {
        self.args.targets.push(Interval::new(start, length));
        self
    }

    /// Adds an excluded region.
    ///
    /// # Arguments
    ///
    /// * `start` - 0-based start position
    /// * `length` - length of the excluded region in bases
    pub fn excluded_region(mut self, start: usize, length: usize) -> Self {
        self.args.excluded_regions.push(Interval::new(start, length));
        self
    }

    /// Adds an excluded region for internal oligos.
    pub fn internal_excluded_region(mut self, start: usize, length: usize) -> Self {
        self.args.internal_excluded_regions.push(Interval::new(start, length));
        self
    }

    /// Adds an OK region pair for primer placement.
    pub fn ok_region(
        mut self,
        left: Option<(usize, usize)>,
        right: Option<(usize, usize)>,
    ) -> Self {
        self.args.ok_regions.push(OkRegionPair {
            left: left.map(|(s, l)| Interval::new(s, l)),
            right: right.map(|(s, l)| Interval::new(s, l)),
        });
        self
    }

    /// Sets the included region (start, length).
    pub fn included_region(mut self, start: usize, length: usize) -> Self {
        self.args.included_region_start = start;
        self.args.included_region_length = Some(length);
        self
    }

    /// Sets per-base quality scores (signed integers).
    pub fn quality(mut self, quality: Vec<i32>) -> Self {
        self.args.quality = Some(quality);
        self
    }

    /// Sets a pre-specified left primer to check or design around.
    pub fn left_primer(mut self, seq: impl Into<String>) -> Self {
        self.args.left_primer = Some(seq.into());
        self
    }

    /// Sets a pre-specified right primer to check or design around.
    pub fn right_primer(mut self, seq: impl Into<String>) -> Self {
        self.args.right_primer = Some(seq.into());
        self
    }

    /// Sets a pre-specified internal oligo to check or design around.
    pub fn internal_oligo(mut self, seq: impl Into<String>) -> Self {
        self.args.internal_oligo = Some(seq.into());
        self
    }

    /// Adds a primer overlap junction position.
    pub fn primer_overlap_junction(mut self, pos: usize) -> Self {
        self.args.primer_overlap_junctions.push(pos);
        self
    }

    /// Sets the overhang sequence for the left primer.
    pub fn overhang_left(mut self, seq: impl Into<String>) -> Self {
        self.args.overhang_left = Some(seq.into());
        self
    }

    /// Sets the overhang sequence for the right primer.
    pub fn overhang_right(mut self, seq: impl Into<String>) -> Self {
        self.args.overhang_right = Some(seq.into());
        self
    }

    /// Validates and returns the sequence arguments.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `sequence` is empty
    /// - `quality` length does not match `sequence` length
    /// - `included_region` exceeds the sequence length
    /// - Any `target` is outside the sequence bounds
    /// - Any `excluded_region` is outside the sequence bounds
    pub fn build(self) -> Result<SequenceArgs> {
        if self.args.sequence.is_empty() {
            return Err(Primer3Error::InvalidSequence("template sequence is empty".into()));
        }
        let seq_len = self.args.sequence.len();
        if let Some(ref quality) = self.args.quality {
            if quality.len() != seq_len {
                return Err(Primer3Error::InvalidSetting(format!(
                    "quality length ({}) does not match sequence length ({})",
                    quality.len(),
                    seq_len,
                )));
            }
        }
        if let Some(inc_len) = self.args.included_region_length {
            if self.args.included_region_start + inc_len > seq_len {
                return Err(Primer3Error::InvalidSetting(format!(
                    "included_region (start={}, length={}) exceeds sequence length ({})",
                    self.args.included_region_start, inc_len, seq_len,
                )));
            }
        }
        for target in &self.args.targets {
            if target.end() > seq_len {
                return Err(Primer3Error::InvalidSetting(format!(
                    "target (start={}, length={}) exceeds sequence length ({})",
                    target.start, target.length, seq_len,
                )));
            }
        }
        for excluded in &self.args.excluded_regions {
            if excluded.end() > seq_len {
                return Err(Primer3Error::InvalidSetting(format!(
                    "excluded_region (start={}, length={}) exceeds sequence length ({})",
                    excluded.start, excluded.length, seq_len,
                )));
            }
        }
        for excluded in &self.args.internal_excluded_regions {
            if excluded.end() > seq_len {
                return Err(Primer3Error::InvalidSetting(format!(
                    "internal_excluded_region (start={}, length={}) exceeds sequence length ({})",
                    excluded.start, excluded.length, seq_len,
                )));
            }
        }
        Ok(self.args)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_interval_new_and_end() {
        let iv = Interval::new(10, 20);
        assert_eq!(iv.start, 10);
        assert_eq!(iv.length, 20);
        assert_eq!(iv.end(), 30);
    }

    #[test]
    fn test_builder_minimal() {
        let args = SequenceArgs::builder().sequence("ATCGATCG").build().unwrap();
        assert_eq!(args.sequence, "ATCGATCG");
        assert!(args.targets.is_empty());
    }

    #[test]
    fn test_builder_empty_sequence_fails() {
        let result = SequenceArgs::builder().sequence("").build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_target_in_bounds() {
        let args =
            SequenceArgs::builder().sequence("ATCGATCGATCGATCG").target(4, 8).build().unwrap();
        assert_eq!(args.targets.len(), 1);
        assert_eq!(args.targets[0].start, 4);
        assert_eq!(args.targets[0].length, 8);
    }

    #[test]
    fn test_builder_target_out_of_bounds_fails() {
        let result = SequenceArgs::builder().sequence("ATCG").target(2, 5).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_excluded_region_out_of_bounds_fails() {
        let result = SequenceArgs::builder().sequence("ATCGATCG").excluded_region(5, 10).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_internal_excluded_out_of_bounds_fails() {
        let result =
            SequenceArgs::builder().sequence("ATCGATCG").internal_excluded_region(5, 10).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_included_region_out_of_bounds_fails() {
        let result = SequenceArgs::builder().sequence("ATCGATCG").included_region(4, 10).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_quality_length_mismatch_fails() {
        let result = SequenceArgs::builder().sequence("ATCG").quality(vec![40, 40, 40]).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_quality_correct_length() {
        let args =
            SequenceArgs::builder().sequence("ATCG").quality(vec![40, 40, 40, 40]).build().unwrap();
        assert_eq!(args.quality.as_ref().unwrap().len(), 4);
    }

    #[test]
    fn test_builder_multiple_targets() {
        let args = SequenceArgs::builder()
            .sequence("ATCGATCGATCGATCGATCG")
            .target(2, 3)
            .target(10, 3)
            .build()
            .unwrap();
        assert_eq!(args.targets.len(), 2);
    }

    #[test]
    fn test_builder_with_primers() {
        let args = SequenceArgs::builder()
            .sequence("ATCGATCGATCG")
            .left_primer("ATCG")
            .right_primer("CGAT")
            .build()
            .unwrap();
        assert_eq!(args.left_primer.as_deref(), Some("ATCG"));
        assert_eq!(args.right_primer.as_deref(), Some("CGAT"));
    }
}