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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Results from primer design.
//!
//! Contains strongly typed results including individual primer records,
//! primer pairs, and design statistics.

use std::fmt;
use std::ops::Range;

/// Type of oligo (left primer, right primer, or internal probe).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum OligoType {
    Left,
    Right,
    Internal,
}

/// An individual primer or oligo record.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PrimerRecord {
    /// Which type of oligo this is.
    oligo_type: OligoType,
    /// The primer sequence (5' to 3').
    sequence: String,
    /// Position reported by primer3. For left primers, this is the 5' (leftmost)
    /// 0-based position. For right primers, this is the 3' (rightmost) 0-based
    /// position. For internal oligos, this is the 5' (leftmost) 0-based position.
    start: usize,
    /// Length of the primer in bases.
    length: usize,
    /// Melting temperature in Celsius.
    tm: f64,
    /// Fraction of primers bound at the annealing temperature.
    bound: f64,
    /// GC content as a percentage (0.0 to 100.0).
    gc_content: f64,
    /// Self-complementarity score (any alignment).
    self_any: f64,
    /// Self-complementarity score (3' end alignment).
    self_end: f64,
    /// Hairpin Tm in Celsius.
    hairpin_tm: f64,
    /// Delta G of disruption of 5 3' bases.
    end_stability: f64,
    /// Overall penalty score.
    penalty: f64,
    /// Problems/constraint violations, if any.
    problems: Option<String>,
}

impl PrimerRecord {
    /// Creates a new `PrimerRecord`. Used internally by the design engine.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        oligo_type: OligoType,
        sequence: String,
        start: usize,
        length: usize,
        tm: f64,
        bound: f64,
        gc_content: f64,
        self_any: f64,
        self_end: f64,
        hairpin_tm: f64,
        end_stability: f64,
        penalty: f64,
        problems: Option<String>,
    ) -> Self {
        Self {
            oligo_type,
            sequence,
            start,
            length,
            tm,
            bound,
            gc_content,
            self_any,
            self_end,
            hairpin_tm,
            end_stability,
            penalty,
            problems,
        }
    }

    /// Which type of oligo this is.
    pub fn oligo_type(&self) -> OligoType {
        self.oligo_type
    }

    /// The primer sequence (5' to 3').
    pub fn sequence(&self) -> &str {
        &self.sequence
    }

    /// The raw start position as reported by primer3.
    ///
    /// For left primers and internal oligos: the 0-based 5' (leftmost) position.
    /// For right primers: the 0-based 3' (rightmost) position.
    ///
    /// Use [`position_on_template()`](Self::position_on_template) for a
    /// consistent 5'-to-3' range on the template regardless of oligo type.
    pub fn start(&self) -> usize {
        self.start
    }

    /// Length of the primer in bases.
    pub fn length(&self) -> usize {
        self.length
    }

    /// Returns the 0-based half-open range `[left_pos, right_pos)` on the
    /// template, regardless of oligo type.
    ///
    /// For left primers: `start..start+length`
    /// For right primers: `start-length+1..start+1`
    /// For internal oligos: `start..start+length`
    #[allow(clippy::range_plus_one)]
    pub fn position_on_template(&self) -> Range<usize> {
        match self.oligo_type {
            OligoType::Left | OligoType::Internal => self.start..self.start + self.length,
            OligoType::Right => {
                let left = (self.start + 1).saturating_sub(self.length);
                left..self.start + 1
            }
        }
    }

    /// Melting temperature in Celsius.
    pub fn tm(&self) -> f64 {
        self.tm
    }

    /// Fraction of primers bound at the annealing temperature.
    pub fn bound(&self) -> f64 {
        self.bound
    }

    /// GC content as a percentage (0.0 to 100.0).
    pub fn gc_content(&self) -> f64 {
        self.gc_content
    }

    /// Self-complementarity score (any alignment).
    pub fn self_any(&self) -> f64 {
        self.self_any
    }

    /// Self-complementarity score (3' end alignment).
    pub fn self_end(&self) -> f64 {
        self.self_end
    }

    /// Hairpin Tm in Celsius.
    pub fn hairpin_tm(&self) -> f64 {
        self.hairpin_tm
    }

    /// Delta G of disruption of the 5 bases at the 3' end.
    pub fn end_stability(&self) -> f64 {
        self.end_stability
    }

    /// Overall penalty score (lower is better).
    pub fn penalty(&self) -> f64 {
        self.penalty
    }

    /// Descriptions of constraint violations, if any.
    pub fn problems(&self) -> Option<&str> {
        self.problems.as_deref()
    }
}

impl fmt::Display for PrimerRecord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let range = self.position_on_template();
        write!(
            f,
            "{} ({}..{}, Tm={:.1}C, GC={:.0}%, penalty={:.3})",
            self.sequence, range.start, range.end, self.tm, self.gc_content, self.penalty,
        )
    }
}

/// A primer pair (left + right + optional internal oligo).
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PrimerPair {
    /// Left primer.
    left: PrimerRecord,
    /// Right primer.
    right: PrimerRecord,
    /// Internal oligo, if designed.
    internal: Option<PrimerRecord>,
    /// Overall pair penalty (lower is better).
    pair_penalty: f64,
    /// Product size in bp.
    product_size: usize,
    /// Product melting temperature.
    product_tm: f64,
    /// Absolute Tm difference between left and right primers.
    tm_diff: f64,
    /// Pair complementarity score (any alignment).
    compl_any: f64,
    /// Pair complementarity score (3' end alignment).
    compl_end: f64,
}

impl PrimerPair {
    /// Creates a new `PrimerPair`. Used internally by the design engine.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        left: PrimerRecord,
        right: PrimerRecord,
        internal: Option<PrimerRecord>,
        pair_penalty: f64,
        product_size: usize,
        product_tm: f64,
        tm_diff: f64,
        compl_any: f64,
        compl_end: f64,
    ) -> Self {
        Self {
            left,
            right,
            internal,
            pair_penalty,
            product_size,
            product_tm,
            tm_diff,
            compl_any,
            compl_end,
        }
    }

    /// Left primer.
    pub fn left(&self) -> &PrimerRecord {
        &self.left
    }
    /// Right primer.
    pub fn right(&self) -> &PrimerRecord {
        &self.right
    }
    /// Internal oligo, if designed.
    pub fn internal(&self) -> Option<&PrimerRecord> {
        self.internal.as_ref()
    }
    /// Overall pair penalty (lower is better).
    pub fn pair_penalty(&self) -> f64 {
        self.pair_penalty
    }
    /// Product size in bp.
    pub fn product_size(&self) -> usize {
        self.product_size
    }
    /// Product melting temperature.
    pub fn product_tm(&self) -> f64 {
        self.product_tm
    }
    /// Absolute Tm difference between left and right primers.
    pub fn tm_diff(&self) -> f64 {
        self.tm_diff
    }
    /// Pair complementarity score (any alignment).
    pub fn compl_any(&self) -> f64 {
        self.compl_any
    }
    /// Pair complementarity score (3' end alignment).
    pub fn compl_end(&self) -> f64 {
        self.compl_end
    }
}

impl fmt::Display for PrimerPair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "L={} R={} product={}bp (penalty={:.3})",
            self.left.sequence(),
            self.right.sequence(),
            self.product_size,
            self.pair_penalty,
        )
    }
}

/// Statistics about oligos considered during design.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct OligoStats {
    pub considered: usize,
    pub ns: usize,
    pub target: usize,
    pub excluded: usize,
    pub gc: usize,
    pub gc_clamp: usize,
    pub gc_end_high: usize,
    pub temp_min: usize,
    pub temp_max: usize,
    pub bound_min: usize,
    pub bound_max: usize,
    pub size_min: usize,
    pub size_max: usize,
    pub compl_any: usize,
    pub compl_end: usize,
    pub hairpin: usize,
    pub repeat_score: usize,
    pub poly_x: usize,
    pub seq_quality: usize,
    pub stability: usize,
    pub template_mispriming: usize,
    pub ok: usize,
    pub masked: usize,
    pub must_match_fail: usize,
    pub not_in_any_ok_region: usize,
    pub does_not_overlap_required_point: usize,
}

/// Statistics about pairs considered during design.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct PairStats {
    pub considered: usize,
    pub product: usize,
    pub target: usize,
    pub temp_diff: usize,
    pub compl_any: usize,
    pub compl_end: usize,
    pub internal: usize,
    pub repeat_sim: usize,
    pub high_tm: usize,
    pub low_tm: usize,
    pub template_mispriming: usize,
    pub does_not_overlap_required_point: usize,
    pub not_in_any_ok_region: usize,
    pub ok: usize,
}

/// Complete result of a primer design run.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DesignResult {
    pairs: Vec<PrimerPair>,
    left_primers: Vec<PrimerRecord>,
    right_primers: Vec<PrimerRecord>,
    internal_oligos: Vec<PrimerRecord>,
    warnings: Option<String>,
    left_stats: OligoStats,
    right_stats: OligoStats,
    internal_stats: OligoStats,
    pair_stats: PairStats,
}

impl DesignResult {
    /// Creates a new `DesignResult`. Used internally by the design engine.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        pairs: Vec<PrimerPair>,
        left_primers: Vec<PrimerRecord>,
        right_primers: Vec<PrimerRecord>,
        internal_oligos: Vec<PrimerRecord>,
        warnings: Option<String>,
        left_stats: OligoStats,
        right_stats: OligoStats,
        internal_stats: OligoStats,
        pair_stats: PairStats,
    ) -> Self {
        Self {
            pairs,
            left_primers,
            right_primers,
            internal_oligos,
            warnings,
            left_stats,
            right_stats,
            internal_stats,
            pair_stats,
        }
    }

    /// Designed primer pairs, ordered by increasing penalty.
    pub fn pairs(&self) -> &[PrimerPair] {
        &self.pairs
    }
    /// True if no pairs were found.
    pub fn is_empty(&self) -> bool {
        self.pairs.is_empty()
    }
    /// Number of designed pairs.
    pub fn num_pairs(&self) -> usize {
        self.pairs.len()
    }
    /// All acceptable left primers (for list-mode tasks).
    pub fn left_primers(&self) -> &[PrimerRecord] {
        &self.left_primers
    }
    /// All acceptable right primers (for list-mode tasks).
    pub fn right_primers(&self) -> &[PrimerRecord] {
        &self.right_primers
    }
    /// All acceptable internal oligos (for list-mode tasks).
    pub fn internal_oligos(&self) -> &[PrimerRecord] {
        &self.internal_oligos
    }
    /// Warnings generated during design.
    pub fn warnings(&self) -> Option<&str> {
        self.warnings.as_deref()
    }
    /// Statistics for left primer selection.
    pub fn left_stats(&self) -> &OligoStats {
        &self.left_stats
    }
    /// Statistics for right primer selection.
    pub fn right_stats(&self) -> &OligoStats {
        &self.right_stats
    }
    /// Statistics for internal oligo selection.
    pub fn internal_stats(&self) -> &OligoStats {
        &self.internal_stats
    }
    /// Statistics for pair selection.
    pub fn pair_stats(&self) -> &PairStats {
        &self.pair_stats
    }
}

impl DesignResult {
    /// Returns an iterator over the designed primer pairs.
    pub fn iter(&self) -> std::slice::Iter<'_, PrimerPair> {
        self.pairs.iter()
    }
}

impl IntoIterator for DesignResult {
    type Item = PrimerPair;
    type IntoIter = std::vec::IntoIter<PrimerPair>;

    /// Consumes the result and iterates over the designed primer pairs.
    fn into_iter(self) -> Self::IntoIter {
        self.pairs.into_iter()
    }
}

impl<'a> IntoIterator for &'a DesignResult {
    type Item = &'a PrimerPair;
    type IntoIter = std::slice::Iter<'a, PrimerPair>;

    fn into_iter(self) -> Self::IntoIter {
        self.pairs.iter()
    }
}

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

    fn make_left_primer() -> PrimerRecord {
        PrimerRecord::new(
            OligoType::Left,
            "ATCGATCG".into(),
            10,
            8,
            55.0,
            0.5,
            50.0,
            1.0,
            0.5,
            30.0,
            5.0,
            0.1,
            None,
        )
    }

    fn make_right_primer() -> PrimerRecord {
        PrimerRecord::new(
            OligoType::Right,
            "CGATCGAT".into(),
            99,
            8,
            56.0,
            0.5,
            50.0,
            1.0,
            0.5,
            30.0,
            5.0,
            0.2,
            None,
        )
    }

    #[test]
    fn test_primer_record_left_position() {
        let rec = make_left_primer();
        assert_eq!(rec.position_on_template(), 10..18);
        assert_eq!(rec.oligo_type(), OligoType::Left);
        assert_eq!(rec.sequence(), "ATCGATCG");
        assert_eq!(rec.length(), 8);
    }

    #[test]
    fn test_primer_record_right_position() {
        let rec = make_right_primer();
        // Right primer: start=99, length=8 → positions 92..100
        assert_eq!(rec.position_on_template(), 92..100);
    }

    #[test]
    fn test_primer_record_internal_position() {
        let rec = PrimerRecord::new(
            OligoType::Internal,
            "ATCG".into(),
            50,
            4,
            40.0,
            0.0,
            50.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            None,
        );
        assert_eq!(rec.position_on_template(), 50..54);
    }

    #[test]
    fn test_primer_record_accessors() {
        let rec = make_left_primer();
        assert!((rec.tm() - 55.0).abs() < f64::EPSILON);
        assert!((rec.gc_content() - 50.0).abs() < f64::EPSILON);
        assert!((rec.penalty() - 0.1).abs() < f64::EPSILON);
        assert!(rec.problems().is_none());
    }

    #[test]
    fn test_primer_pair() {
        let left = make_left_primer();
        let right = make_right_primer();
        let pair = PrimerPair::new(left, right, None, 0.3, 90, 72.0, 1.0, 2.0, 1.0);
        assert_eq!(pair.product_size(), 90);
        assert!((pair.pair_penalty() - 0.3).abs() < f64::EPSILON);
        assert!(pair.internal().is_none());
        assert!(!pair.left().sequence().is_empty());
    }

    #[test]
    fn test_design_result_empty() {
        let result = DesignResult::new(
            vec![],
            vec![],
            vec![],
            vec![],
            None,
            OligoStats::default(),
            OligoStats::default(),
            OligoStats::default(),
            PairStats::default(),
        );
        assert!(result.is_empty());
        assert_eq!(result.num_pairs(), 0);
        assert!(result.warnings().is_none());
    }

    #[test]
    fn test_oligo_stats_default() {
        let s = OligoStats::default();
        assert_eq!(s.considered, 0);
        assert_eq!(s.ok, 0);
    }

    #[test]
    fn test_pair_stats_default() {
        let s = PairStats::default();
        assert_eq!(s.considered, 0);
        assert_eq!(s.ok, 0);
    }
}