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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
#![deny(missing_docs)]
//! This crate allows one to design DNA molecules.
//!
//! The following creates a strand zig-zagging between three helices,
//! and outputs it to a file:
//!
//! ```
//! use codenano::*;
//! let mut design: Design<(), ()> = Design::new();
//! for i in 0..3 {
//!    design.add_grid_helix(i, 0);
//! }
//! // Let's first design a strand.
//! design.strand(0, 0).to(31)
//!   .cross(1).to(10)
//!   .cross(2).to(21);
//! // Now its reverse complement:
//! design.strand(2, 21).to(10)
//!    .cross(1).to(31)
//!    .cross(0).to(0);
//! design.write_to("my_design.json").unwrap()
//! ```
//!
//! This library is compatible with the `codenano-server` crate, which
//! watches changes made to a file and shows the result in 3D in a web
//! browser. Additionally, the client part of that crate can run
//! finite element simulations and display the secondary structure.

#[macro_use]
extern crate serde_derive;
extern crate failure;
extern crate serde;

pub use failure::Error;
use std::collections::HashMap;
use std::f64::consts::PI;
use std::borrow::Cow;

/// 3D points and vectors
pub mod geometry;
use crate::geometry::*;

/// Extra tools for sequences (random completions, etc.)
pub mod sequences;

/// Conversion to Cadnano format.
pub mod cadnano;

/// The main type of this crate, describing a DNA design.
#[derive(Serialize, Deserialize)]
pub struct Design<StrandLabel, DomainLabel> {
    /// Version of this format.
    pub version: String,
    /// The vector of all helices used in this design. Helices have a
    /// position and an orientation in 3D.
    pub helices: Vec<Helix>,
    /// The vector of strands.
    pub strands: Vec<Strand<StrandLabel, DomainLabel>>,
    /// Parameters of DNA geometry. This can be skipped (in JSON), or
    /// set to `None` in Rust, in which case a default set of
    /// parameters from the literature is used.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub parameters: Option<Parameters>,
}

fn is_false(x: &bool) -> bool {
    !*x
}

fn none<Label>() -> Option<Label> {
    None
}

/// A DNA strand.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Strand<Label, DomainLabel> {
    /// The (ordered) vector of domains, where each domain is a
    /// directed interval of a helix.
    pub domains: Vec<Domain<DomainLabel>>,
    /// The sequence of this strand, if any. If the sequence is longer
    /// than specified by the domains, a prefix is assumed. Can be
    /// skipped in the serialisation.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub sequence: Option<Cow<'static, str>>,
    /// Is this sequence cyclic? Can be skipped (and defaults to
    /// `false`) in the serialization.
    #[serde(skip_serializing_if = "is_false", default)]
    pub cyclic: bool,
    /// Colour of this strand. If skipped, a default colour will be
    /// chosen automatically.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub color: Option<u32>,
    /// An optional label for the strand. Can be
    /// `serde_json::Value::Null`, and skipped in the serialisation.
    #[serde(skip_serializing_if = "Option::is_none", default = "none")]
    pub label: Option<Label>,
}

/// A domain, i.e. an interval of a helix.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Domain<Label> {
    /// Index of the helix in the array of helices. Indices start at
    /// 0.
    pub helix: isize,
    /// Position of the leftmost base of this domain along the helix
    /// (this might be the first or last base of the domain, depending
    /// on the `right` parameter below).
    pub start: isize,
    /// Position of the first base after the rightmost base of the
    /// domain, along the helix. Domains must always be such that
    /// `domain.start < domain.end`.
    pub end: isize,
    /// If true, the "5' to 3'" direction of this domain runs in the
    /// same direction as the helix, i.e. "to the right" along the
    /// axis of the helix. Else, the 5' to 3' runs to the left along
    /// the axis.
    pub right: bool,
    /// An optional label that can be attached to strands.
    #[serde(skip_serializing_if = "Option::is_none", default = "none")]
    pub label: Option<Label>,
    /// In addition to the strand-level sequence, individual domains
    /// may have sequences too. The precedence has to be defined by
    /// the user of this library.
    pub sequence: Option<Cow<'static,str>>,
}

impl<Label> Domain<Label> {
    /// Iterate through the positions of this domain, in 5' to 3'
    /// order (meaning that the values produced by this iterator might
    /// be increasing or decreasing).
    pub fn iter(&self) -> DomainIter {
        DomainIter {
            start: self.start,
            end: self.end,
            right: self.right,
        }
    }
    /// Translate this domain. The first parameter is the translation
    /// along the helix, the second one is a translation across
    /// helices (probably most meaningful for a flat design).
    pub fn translate(self, dx: isize, dy: isize) -> Self {
        use std::convert::TryFrom;
        Domain {
            start: self.start + dx,
            end: self.end + dx,
            helix: usize::try_from(self.helix as isize + dy).unwrap() as isize,
            ..self
        }
    }
    /// Translate this domain along its helix.
    pub fn shift_x(self, dx: isize) -> Self {
        Domain {
            start: self.start + dx,
            end: self.end + dx,
            ..self
        }
    }
    /// Translate this domain to a different helix (probably most
    /// meaningful for a flat design).
    pub fn shift_y(self, dy: isize) -> Self {
        use std::convert::TryFrom;
        Domain {
            helix: usize::try_from(self.helix as isize + dy).unwrap() as isize,
            ..self
        }
    }
}

/// An iterator over all positions of a domain.
pub struct DomainIter {
    start: isize,
    end: isize,
    right: bool,
}

impl Iterator for DomainIter {
    type Item = isize;
    fn next(&mut self) -> Option<Self::Item> {
        if self.start == self.end {
            None
        } else if self.right {
            let s = self.start;
            self.start += 1;
            Some(s)
        } else {
            let s = self.end - 1;
            self.end -= 1;
            Some(s)
        }
    }
}

/// The sequence of the M13 bacteriophage, used for example for DNA
/// Origami.
pub const M13_7249: &'static str = include_str!("m13");
/// A cut version of the M13, which can be obtained with enzymes from
/// the original genome (the `M13_7249` one).
pub const M13_594: &'static str = include_str!("m13_594");

/// DNA geometric parameters.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct Parameters {
    /// Distance between two consecutive bases along the axis of a
    /// helix, in nanometers.
    pub z_step: f64,
    /// Radius of a helix, in nanometers.
    pub helix_radius: f64,
    /// Number of bases per turn in nanometers.
    pub bases_per_turn: f64,
    /// Minor groove angle. DNA helices have a "minor groove" and a
    /// "major groove", meaning that two paired nucleotides are not at
    /// opposite positions around a double helix (i.e. at an angle of
    /// 180°), but instead have a different angle.
    ///
    /// Strands are directed. The "normal" direction is called "5' to
    /// 3'" (named after parts of the nucleotides). This parameter is
    /// the small angle, which is clockwise from the normal strand to
    /// the reverse strand.
    pub groove_angle: f64,

    /// Gap between two neighbouring helices.
    pub inter_helix_gap: f64,
}

impl Default for Parameters {
    fn default() -> Self {
        Parameters {
            // z-step and helix radius from:
            //
            // Single-molecule portrait of DNA and RNA double helices,
            // J. Ricardo Arias-Gonzalez, Integrative Biology, Royal
            // Society of Chemistry, 2014, vol. 6, p.904
            z_step: 0.332,
            helix_radius: 1.,
            // bases per turn from Wu Rothemund (Nature Chemistry).
            bases_per_turn: 10.44,
            groove_angle: -24. * PI / 34.,
            // From Paul's paper.
            inter_helix_gap: 1.,
        }
    }
}

/// A DNA helix. All bases of all strands must be on a helix.
///
/// The three angles are illustrated in the following image, from [the NASA website](https://www.grc.nasa.gov/www/k-12/airplane/rotations.html):
///
/// ![Aircraft angles](https://www.grc.nasa.gov/www/k-12/airplane/Images/rotations.gif)
#[derive(Serialize, Deserialize)]
pub struct Helix {
    /// Position of the origin of the helix axis.
    pub origin: Point<f64>,

    /// Angle around the axis of the helix.
    pub roll: f64,

    /// Horizontal rotation.
    pub yaw: f64,

    /// Vertical rotation.
    pub pitch: f64,
}

impl Helix {
    // Angle on the circle
    fn theta(&self, n: isize, b: bool, cst: &Parameters) -> f64 {
        let shift = if b { cst.groove_angle } else { 0. };
        n as f64 * 2. * PI / cst.bases_per_turn + shift + self.roll
    }

    fn ry(point: Point<f64>, theta: f64) -> Point<f64> {
        Point {
            x: point.x * theta.cos() + point.z * theta.sin(),
            y: point.y,
            z: point.x * -theta.sin() + point.z * theta.cos(),
        }
    }

    fn rz(point: Point<f64>, theta: f64) -> Point<f64> {
        Point {
            x: point.x * theta.cos() + point.y * -theta.sin(),
            y: point.x * theta.sin() + point.y * theta.cos(),
            z: point.z,
        }
    }

    /// 3D position of a nucleotide on this helix. `n` is the position along the axis, and `right` is true iff the 5' to 3' direction of the strand containing that nucleotide runs in the same direction as the axis of the helix.
    pub fn space_pos(&self, p: &Parameters, n: isize, right: bool) -> Point<f64> {
        let theta = self.theta(n, right, p);
        let mut ret = Point {
            x: n as f64 * p.z_step,
            y: theta.cos() * p.helix_radius,
            z: -theta.sin() * p.helix_radius,
        };
        ret = Helix::ry(ret, self.yaw);
        ret = Helix::rz(ret, self.pitch);
        ret.x += self.origin.x;
        ret.y += self.origin.y;
        ret.z += self.origin.z;
        ret
    }
}

/// Identity of a helix, useful for referring to it.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HelixId(pub isize);

impl From<isize> for HelixId {
    fn from(e: isize) -> Self {
        HelixId(e)
    }
}

impl From<i32> for HelixId {
    fn from(e: i32) -> Self {
        HelixId(e as isize)
    }
}

impl From<usize> for HelixId {
    fn from(e: usize) -> Self {
        HelixId(e as isize)
    }
}

/// Identity of a strand, useful for referring to it.
pub struct StrandId(pub usize);

/// This is just a communication type between the server and the
/// client, serialisable in JSON. No need to really expose it.
#[doc(hidden)]
#[derive(Serialize, Deserialize)]
pub struct Res {
    pub out: String,
    pub err: String,
}

/// A pointer to a strand being built, containing a current domain and
/// position.
pub struct StrandRef<'a, StrandLabel, DomainLabel> {
    builder: &'a mut Design<StrandLabel, DomainLabel>,
    strand_id: usize,
    x: Option<isize>,
    x0: Option<isize>,
}

impl<StrandLabel: serde::Serialize, DomainLabel: serde::Serialize> Design<StrandLabel, DomainLabel> {
    /// Initiates a design.
    pub fn new() -> Self {
        Design {
            version: env!("CARGO_PKG_VERSION").to_string(),
            helices: Vec::new(),
            strands: Vec::new(),
            parameters: Some(Parameters::default()),
        }
    }

    /// Creates a flat helix (in the `z = 0` plane).
    pub fn square_grid_helix(&self, h: isize, v: isize) -> Helix {
        Helix {
            origin: Point {
                x: 0.,
                y: h as f64
                    * (self.parameters.unwrap().helix_radius * 2.
                        + self.parameters.unwrap().inter_helix_gap),
                z: v as f64
                    * (self.parameters.unwrap().helix_radius * 2.
                        + self.parameters.unwrap().inter_helix_gap),
            },
            roll: 0.,
            pitch: 0.,
            yaw: 0.,
        }
    }

    /// Initiates a design with the given geometric parameters.
    pub fn with_parameters(parameters: Parameters) -> Self {
        let mut b = Design::new();
        b.parameters = Some(parameters);
        b
    }

    /// Add a helix created be `Self::square_grid_helix`.
    pub fn add_grid_helix(&mut self, h: isize, v: isize) -> HelixId {
        self.helices.push(self.square_grid_helix(h, v));
        HelixId((self.helices.len() - 1) as isize)
    }

    /// Add an arbitrary helix.
    pub fn add_helix(
        &mut self,
        x: f64,
        y: f64,
        z: f64,
        roll: f64,
        pitch: f64,
        yaw: f64,
    ) -> HelixId {
        self.helices.push(Helix {
            origin: Point { x, y, z },
            roll,
            pitch,
            yaw,
        });
        HelixId((self.helices.len() - 1) as isize)
    }

    /// Start a strand, placing the first base at the position given
    /// by `helix` and `start`.
    pub fn strand<H: Into<HelixId>>(&mut self, helix: H, start: isize) -> StrandRef<StrandLabel, DomainLabel> {
        let strand_id = self.strands.len();
        self.strands.push(Strand {
            domains: vec![Domain {
                helix: helix.into().0,
                start,
                end: start,
                right: true,
                label: None,
                sequence: None,
            }],
            label: None,
            sequence: None,
            cyclic: false,
            color: None,
        });
        StrandRef {
            strand_id,
            builder: self,
            x: Some(start),
            x0: Some(start),
        }
    }

    /// Create a strand with no initial domain. Useful for adding
    /// custom domains, for example domains obtained by geometric
    /// operations from other domains.
    pub fn empty_strand(&mut self) -> StrandRef<StrandLabel, DomainLabel> {
        let strand_id = self.strands.len();
        self.strands.push(Strand {
            domains: Vec::new(),
            cyclic: false,
            color: None,
            sequence: None,
            label: None,
        });
        StrandRef {
            strand_id,
            builder: self,
            x: None,
            x0: None,
        }
    }

    /// Write this design to the standard output.
    pub fn write(&self) -> Result<(), Error> {
        serde_json::to_writer(std::io::stdout(), self)?;
        Ok(())
    }

    /// Write this design to a file. If the `REMOTE` environment
    /// variable is set, write it to the standard output instead.
    pub fn write_to<P: AsRef<std::path::Path>>(&self, p: P) -> Result<(), Error> {
        if std::env::var("REMOTE").is_ok() {
            serde_json::to_writer_pretty(std::io::stdout(), &self)?
        } else {
            serde_json::to_writer_pretty(std::fs::File::create(p)?, &self)?
        }
        Ok(())
    }

    /// Tests whether all bases have different positions, and returns
    /// an offending strand else. The return format is `(helix,
    /// position, right, i, j)`, where `i` and `j` are the indices of
    /// two strands sharing this position.
    pub fn unique_positions(&self) -> Option<(isize, isize, bool, usize, usize)> {
        let mut positions = HashMap::new();
        for (i, s) in self.strands.iter().enumerate() {
            for dom in s.domains.iter() {
                for pos in dom.iter() {
                    if let Some(prev) = positions.insert((dom.helix, pos, dom.right), i) {
                        return Some((dom.helix, pos, dom.right, i, prev));
                    }
                }
            }
        }
        None
    }
}

// http://eleanormaclure.files.wordpress.com/2011/03/colour-coding.pdf
const KELLY: [u32; 19] = [
    // 0xF2F3F4, // White
    // 0x222222, // Black,
    0xF3C300, 0x875692, // 0xF38400, // Orange, too close to others
    0xA1CAF1, 0xBE0032, 0xC2B280, 0x848482, 0x008856, 0xE68FAC, 0x0067A5, 0xF99379, 0x604E97,
    0xF6A600, 0xB3446C, 0xDCD300, 0x882D17, 0x8DB600, 0x654522, 0xE25822, 0x2B3D26,
];

impl<StrandLabel, DomainLabel> Strand<StrandLabel, DomainLabel> {
    /// Provide a default color to the strand.
    pub fn default_color(&self) -> u32 {
        for domain in self.domains.iter() {
            let x1 = if domain.right {
                domain.end - 1
            } else {
                domain.start
            };
            let h = domain.helix as isize;
            let x = x1 + (x1 % 11) + 5 * h;
            let n = KELLY.len() as isize;
            return KELLY[(((x % n) + n) % n) as usize];
        }
        0
    }
}

impl<'a, StrandLabel, DomainLabel> StrandRef<'a, StrandLabel, DomainLabel> {
    /// Retrieve the identity of the strand currently being built.
    pub fn id(&self) -> StrandId {
        StrandId(self.strand_id)
    }

    /// Total (current) length of the strand being created. Adding
    /// more points will increase the length.
    pub fn len(&self) -> usize {
        self.domains()
            .iter()
            .map(|d| (d.end - d.start) as usize)
            .sum()
    }

    /// Choose a color for this strand.
    pub fn with_color(self, color: u32) -> Self {
        self.builder.strands[self.strand_id].color = Some(color);
        self
    }

    /// Choose a color for this strand.
    pub fn with_kelly_color(self, color: usize) -> Self {
        self.builder.strands[self.strand_id].color = Some(KELLY[color]);
        self
    }

    /// List the current domains of this strand (more domains can be
    /// added later).
    pub fn domains(&self) -> &[Domain<DomainLabel>] {
        &self.builder.strands[self.strand_id].domains
    }

    /// Gives a mutable pointer to the vector of domains.
    pub fn domains_mut(&mut self) -> &mut Vec<Domain<DomainLabel>> {
        &mut self.builder.strands[self.strand_id].domains
    }

    /// Push a domain onto this strand.
    pub fn push_domain(&mut self, domain: Domain<DomainLabel>) {
        self.x = Some(if domain.right {
            domain.end - 1
        } else {
            domain.start
        });
        self.builder.strands[self.strand_id].domains.push(domain);
    }

    /// Extend this strand with multiple domains.
    pub fn extend<I: Iterator<Item = Domain<DomainLabel>>>(&mut self, i: I) {
        for i in i {
            self.push_domain(i)
        }
    }

    /// Sets the sequence of this strand.
    pub fn with_sequence<I:Into<Cow<'static,str>>>(self, sequence: I) -> Self {
        self.builder.strands[self.strand_id].sequence = Some(sequence.into());
        self
    }

    /// Sets the sequence of this strand.
    pub fn with_domain_sequence<I:Into<Cow<'static,str>>>(self, sequence: I) -> Self {
        self.builder.strands[self.strand_id]
            .domains
            .last_mut()
            .unwrap()
            .sequence = Some(sequence.into());
        self
    }

    /// Move along the helix. This method can be called multiple times
    /// consecutively, but the direction of the domain is set only on
    /// the first call, subsequent calls only change the 3' end of the
    /// domain (which is the rightmost point if `self.right` is true,
    /// and the leftmost point else).
    pub fn to(mut self, x: isize) -> Self {
        let strand = self.builder.strands[self.strand_id]
            .domains
            .last_mut()
            .unwrap();
        self.x = Some(x);
        let x0 = self.x0.unwrap();
        if x > x0 {
            strand.right = true;
            strand.start = x0;
            strand.end = x + 1;
        } else {
            strand.right = false;
            strand.start = x;
            strand.end = x0 + 1;
        }
        self
    }

    /// Remove the last domain of the strand.
    pub fn pop(mut self) -> Self {
        self.builder.strands[self.strand_id].domains.pop();
        if let Some(last) = self.builder.strands[self.strand_id].domains.last() {
            self.x = Some(if last.right { last.end - 1 } else { last.start })
        } else {
            self.x = None
        }
        self
    }

    /// Change the initial point of the first domain of this strand.
    pub fn rev_to(mut self, x: isize) -> Self {
        if self.builder.strands[self.strand_id].domains.is_empty() {
            return self;
        }
        let ref mut strand = self.builder.strands[self.strand_id].domains[0];
        self.x = Some(x);
        let x0 = self.x0.unwrap();
        if x > x0 {
            strand.right = true;
            strand.start = x0;
            strand.end = x + 1;
        } else {
            strand.right = false;
            strand.start = x;
            strand.end = x0 + 1;
        }
        self
    }

    /// Give a label to this strand.
    pub fn with_label(self, label: StrandLabel) -> Self {
        self.builder.strands[self.strand_id].label = Some(label);
        self
    }

    /// Give a label to the most recently produced domain on this strand.
    pub fn with_domain_label(self, label: DomainLabel) -> Self {
        self.builder.strands[self.strand_id]
            .domains
            .last_mut()
            .unwrap()
            .label = Some(label);
        self
    }

    /// Finish a domain, and start a new one on the same helix and at
    /// the same position.
    pub fn next_domain_to(mut self, to: isize) -> Self {
        let helix = self.builder.strands[self.strand_id].domains.last().unwrap().helix;
        // If the previous domain is on the same helix.
        let (start, end, right) =
            if to < self.x.unwrap() {
                let n = (to, self.x.unwrap(), false);
                self.x = Some(to);
                n
            } else {
                let n = (self.x.unwrap() + 1, to + 1, true);
                self.x = Some(to);
                n
            };
        let domain = Domain {
            helix, start, end, right,
            label: None,
            sequence: None,
        };
        self.builder.strands[self.strand_id].domains.push(domain);
        self
    }

    /// Move the cursor to a different helix, keeping the same current
    /// position along the axis of the helix (most meaningful when the helices are in the same plane).
    pub fn cross<H: Into<HelixId>>(self, h: H) -> Self {
        let x = self.x.unwrap();
        self.cross_to(h, x)
    }

    /// Move the cursor to a different helix, at the specified
    /// position.
    pub fn cross_to<H: Into<HelixId>>(mut self, h: H, start: isize) -> Self {
        let helix = h.into().0;
        if helix >= self.builder.helices.len() as isize {
            panic!("Crossing to an undefined helix")
        }
        self.builder.strands[self.strand_id].domains.push(Domain {
            helix,
            start,
            end: start,
            right: true,
            label: None,
            sequence: None,
        });
        self.x0 = Some(start);
        self.x = Some(start);
        self
    }

    /// Compute the horizontal symmetry of this strand with respect to
    /// x-coordinate `x`.
    pub fn hflip(self, x: isize) -> Self {
        for dom in self.builder.strands[self.strand_id].domains.iter_mut() {
            let start = dom.start;
            dom.start = x - dom.end;
            dom.end = x - start;
        }
        self.builder.strands[self.strand_id].domains.reverse();
        self
    }

    /// Compute the vertical symmetry of this strand with respect to
    /// y-coordinate `y`. Most meaningful in flat designs.
    pub fn vflip<H: Into<HelixId>>(self, y: H) -> Self {
        let y = y.into();
        for dom in self.builder.strands[self.strand_id].domains.iter_mut() {
            assert!(y.0 >= dom.helix);
            dom.helix = 2 * y.0 - dom.helix
        }
        self
    }

    /// Translate this strand (all domains) to a different
    /// position. `x` is the horizontal translation (along the axis of
    /// the helices), and `y` moves between helices. Most meaningful
    /// in a flat, on-grid design.
    pub fn translate(self, x: isize, y: isize) -> Self {
        use std::convert::TryFrom;
        for dom in self.builder.strands[self.strand_id].domains.iter_mut() {
            dom.helix = usize::try_from(dom.helix as isize + y).unwrap() as isize;
            dom.start += x;
            dom.end += x;
        }
        self
    }
}

fn sequence<StrandLabel, DomainLabel>(
    positions: &HashMap<(usize, isize, bool), char>,
    strand: &Strand<StrandLabel, DomainLabel>,
) -> String {
    let mut seq = String::new();
    // println!("label = {:?}", strand.label);
    for dom in strand.domains.iter() {
        if let Some(ref s) = dom.sequence {
            seq.push_str(s);
            continue;
        }
        assert!(dom.helix >= 0);
        for pos in dom.iter() {
            seq.push(sequences::complement(
                *positions
                    .get(&(dom.helix as usize, pos, !dom.right))
                    .unwrap(),
            ))
        }
    }
    seq
}

/// Common geometric transforms on domains (most useful when working
/// on grids or partial grids).
pub mod transforms {
    use super::Domain;

    /// Rotate all the domains provided as input by 180°. This can be
    /// used on domains obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn rotate<Label>(domains: &mut [Domain<Label>]) {
        let max_helix = domains.iter().map(|x| x.helix).max().unwrap();
        for dom in domains.iter_mut() {
            let start = dom.start;
            dom.start = -dom.end;
            dom.end = -start;
            dom.helix = max_helix - dom.helix;
            dom.right = !dom.right;
        }
    }

    /// Flip all the domains provided as input vertically, i.e. relative
    /// to a horizontal axis. This can be used on domains obtained
    /// with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn v_flip<Label>(domains: &mut [Domain<Label>], max_helix: isize) {
        for dom in domains.iter_mut() {
            dom.helix = max_helix - dom.helix;
        }
    }

    /// Reverse the direction of the list of domains provided as
    /// input, starting from the very last base back to the first
    /// one. This can be used on domains obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn reverse<Label>(domains: &mut [Domain<Label>]) {
        for dom in domains.iter_mut() {
            dom.right = !dom.right;
        }
    }

    /// Flip all the domains provided as input horizontally,
    /// i.e. relative to a vertical axis. This can be used on domains
    /// obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn h_flip<Label>(domains: &mut [Domain<Label>]) {
        for dom in domains.iter_mut() {
            let start = dom.start;
            dom.start = -dom.end;
            dom.end = -start;
        }
    }

    /// Trnsalate all the domains provided as input by the specified
    /// number of helices (parameter `dh`) and bases (parameter
    /// `dx`). This can be used on domains obtained with
    /// [`StrandRef::domains()`](../struct.StrandRef.html#method.domains)
    /// method.
    pub fn translate<Label>(domains: &mut [Domain<Label>], dh: isize, dx: isize) {
        use std::convert::TryFrom;
        for dom in domains.iter_mut() {
            dom.helix = usize::try_from(dom.helix as isize + dh).unwrap() as isize;
            dom.start += dx;
            dom.end += dx;
        }
    }
}

impl<StrandLabel, DomainLabel> Design<StrandLabel, DomainLabel> {
    fn positions(&self) -> HashMap<(usize, isize, bool), char> {
        // First add sequences to all positions
        let mut positions = HashMap::new();
        for s in self.strands.iter() {
            if let Some(ref seq) = s.sequence {
                let mut seq = seq.chars();
                for dom in s.domains.iter() {
                    if dom.helix < 0 {
                        continue;
                    }
                    for pos in dom.iter() {
                        let c = seq.next().unwrap();
                        positions.insert((dom.helix as usize, pos, dom.right), c);
                    }
                }
            }
        }
        positions
    }

    /// Output all the sequences of the strands whose sequence has not
    /// been forced.
    pub fn sequences(&self) -> Vec<String> {
        let positions = self.positions();
        let mut sequences = Vec::new();
        for s in self.strands.iter() {
            if s.sequence.is_none() {
                sequences.push(sequence(&positions, s))
            }
        }
        sequences
    }
}

#[cfg(feature = "excel")]
impl<StrandLabel: Ord + std::fmt::Display, DomainLabel: Ord + std::fmt::Display> Design<StrandLabel, DomainLabel> {
    /// Output plates with the sequences, ordered by label, as an
    /// Excel spreadsheet that can be ordered from [the IDT
    /// website](https://idtdna.com).
    ///
    /// All strands `s` such that `filter(s).is_some()` are included,
    /// and only those. Moreover, if `filter(s) == Some(true)`, a new
    /// plate is started if the current plate is nonempty.
    ///
    /// Moreover, strands are ran through the `filter` function in the
    /// same order as they are in `self`.
    pub fn make_plates_96<F: FnMut(&Strand<StrandLabel, DomainLabel>) -> Option<bool>, G: FnMut(usize) -> String>(
        &mut self,
        file: &str,
        mut filter: F,
        mut format: G,
    ) {
        self.strands.sort_by(|a, b| a.label.cmp(&b.label));
        let mut current_label = &None;
        let mut current_plate = 0;

        let mut plate = Plate96::new();
        let mut plates = vec![Vec::new()];
        let positions = self.positions();
        for s in self.strands.iter() {
            if *current_label != s.label && plate.row > 0 {
                plate.incr_col();
            }

            if plate.n != current_plate {
                plates.push(Vec::new());
                current_plate = plate.n;
            }
            if let Some(x) = filter(s) {
                // println!("{:?}", plate);
                if x && (plate.row != 0 || plate.column != 0) {
                    plate.incr_plate();
                    plates.push(Vec::new());
                    current_plate = plate.n;
                }
                plates.last_mut().unwrap().push((
                    plate.column,
                    plate.row,
                    &s.label,
                    sequence(&positions, s),
                ));
                plate.incr()
            }
            current_label = &s.label;
        }
        use simple_excel_writer::*;
        let mut wb = Workbook::create(file);
        for (i, seqs) in plates.iter().enumerate() {
            let mut sheet = wb.create_sheet(&format(i));
            sheet.add_column(Column { width: 30.0 });
            sheet.add_column(Column { width: 30.0 });
            sheet.add_column(Column { width: 30.0 });
            wb.write_sheet(&mut sheet, |sw| {
                sw.append_row(row!["Well Position", "Name", "Sequence"])?;
                for &(col, row, label, ref seq) in seqs.iter() {
                    let row = (b'A' + row as u8) as char;
                    let label = if let Some(ref label) = label {
                        format!("{}", label)
                    } else {
                        format!("{}{}", row, col + 1)
                    };
                    sw.append_row(row![
                        format!("{}{}", row, col + 1).as_str(),
                        label.as_str(),
                        seq.as_str()
                    ])?
                }
                Ok(())
            })
            .unwrap()
        }
        wb.close().unwrap();
    }
}

#[cfg(feature = "excel")]
#[derive(Debug, Copy, Clone)]
struct Plate96 {
    n: usize,
    column: usize,
    row: usize,
}

#[cfg(feature = "excel")]
impl Plate96 {
    fn new() -> Self {
        Plate96 {
            n: 0,
            column: 0,
            row: 0,
        }
    }
    fn incr(&mut self) {
        self.row += 1;
        if self.row >= 8 {
            self.incr_col()
        }
    }
    fn incr_col(&mut self) {
        self.column += 1;
        self.row = 0;
        if self.column >= 12 {
            self.incr_plate()
        }
    }
    fn incr_plate(&mut self) {
        self.column = 0;
        self.row = 0;
        self.n += 1;
    }
}