grafen 0.9.1

Create graphene and other substrates for use in molecular dynamics simulations.
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
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
//! Modify the list of `ComponentEntry` objects in a `DataBase`.

// This module is a bit of a mess.

use error::{GrafenCliError, UIResult, UIErrorKind};
use ui::utils::{MenuResult, get_value_from_user, print_description, print_list_description_short,
                remove_items, reorder_list, select_command, select_item};

use grafen::coord::{Coord, Direction};
use grafen::database::ComponentEntry;
use grafen::database::ComponentEntry::*;
use grafen::describe::Describe;
use grafen::surface;
use grafen::surface::{CylinderCap, LatticeType};
use grafen::system::Residue;
use grafen::volume;

use dialoguer::Checkboxes;
use std::error::Error;
use std::fmt::Write;
use std::result;

pub fn user_menu(mut component_list: &mut Vec<ComponentEntry>, residue_list: &[Residue])
        -> MenuResult {
    let components_backup = component_list.clone();

    create_menu![
        @pre: { print_list_description_short("Component definitions", &component_list); };

        AddComponent, "Create a component definition" => {
            new_component(&residue_list)
                .map(|component| {
                    component_list.push(component);
                    Some("Successfully created component definition".to_string())
                })
                .map_err(|_| GrafenCliError::RunError(
                    "Could not create component definition".to_string()
                ))
        },
        RemoveComponent, "Remove a component definition" => {
            remove_items(&mut component_list)
                .map(|_| None)
                .map_err(|err| GrafenCliError::RunError(
                    format!("Could not remove a component: {}", err.description())
                ))
        },
        ReorderList, "Reorder component definition list" => {
            reorder_list(&mut component_list)
                .map(|_| None)
                .map_err(|err| GrafenCliError::RunError(
                    format!("Could not reorder the list: {}", err.description())
                ))
        },
        QuitAndSave, "Finish editing component definition list" => {
            return Ok(Some("Finished editing component definition list".to_string()));
        },
        QuitWithoutSaving, "Abort and discard changes" => {
            *component_list = components_backup;
            return Ok(Some("Discarding changes to component definition list".to_string()));
        }
    ];
}

#[derive(Clone, Copy, Debug)]
/// Available component types.
enum ComponentSelect {
    Sheet,
    Cylinder,
    Cuboid,
    Abort,
}
use self::ComponentSelect::*;

/// This menu changes the main component type and then calls that type's construction menu.
fn new_component(residue_list: &[Residue]) -> UIResult<ComponentEntry> {
    loop {
        let component_type = select_component_type()?;

        let result = match component_type {
            Sheet => create_sheet(&residue_list),
            Cylinder => create_cylinder(&residue_list),
            Cuboid => create_cuboid(&residue_list),
            Abort => return Err(UIErrorKind::Abort),
        };

        match result {
            // All is good!
            Ok(component) => return Ok(component),

            // User asked to change a component.
            Err(ChangeOrError::ChangeComponent) => (),

            // User aborted the component creation.
            Err(ChangeOrError::Error(UIErrorKind::Abort)) => return Err(UIErrorKind::Abort),

            // Something went wrong when constructing a component. Reloop the menu.
            Err(ChangeOrError::Error(_)) => eprintln!("could not create component"),
        }
    }
}

fn select_component_type() -> UIResult<ComponentSelect> {
    let (choices, item_texts) = create_menu_items![
        (Sheet, "Sheet"),
        (Cylinder, "Cylinder"),
        (Cuboid, "Cuboid box"),
        (Abort, "(Abort)")
    ];

    eprintln!("Component type:");
    select_command(item_texts, choices).map_err(|err| UIErrorKind::from(err))
}

/// Error enum to handle the case when we return to a previous menu to change a component,
/// not because an error was encountered.
enum ChangeOrError {
    ChangeComponent,
    Error(UIErrorKind),
}

impl From<UIErrorKind> for ChangeOrError {
    fn from(err: UIErrorKind) -> ChangeOrError {
        ChangeOrError::Error(err)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
/// Types of components to construct.
enum ComponentType {
    Surface,
    Volume,
}
use self::ComponentType::*;

/**********************
 * Sheet construction *
 **********************/

/// Use a builder to get all value before constructing the component.
struct SheetBuilder {
    name: String,
    lattice: LatticeType,
    residue: Residue,
    normal: Direction,
    std_z: Option<f64>,
}

impl SheetBuilder {
    fn initialize(residue_list: &[Residue]) -> UIResult<SheetBuilder> {
        let lattice = select_lattice()?;

        eprintln!("Residue:");
        let residue = select_residue(&residue_list)?;

        eprintln!("Sheet normal vector direction:");
        let normal = select_direction()?;

        Ok(SheetBuilder {
            name: String::new(),
            lattice,
            residue,
            normal,
            std_z: None,
        })
    }

    fn finalize(&self) -> result::Result<ComponentEntry, &str> {
        if self.name.is_empty() {
            return Err("Cannot add component: No name is set")
        } else {
            Ok(SurfaceSheet(surface::Sheet {
                name: Some(self.name.clone()),
                residue: Some(self.residue.clone()),
                lattice: self.lattice.clone(),
                std_z: self.std_z,
                origin: Coord::default(),
                normal: self.normal,
                length: 0.0,
                width: 0.0,
                coords: vec![],
            }))
        }
    }
}

impl Describe for SheetBuilder {
    fn describe(&self) -> String {
        let mut description = String::new();
        const ERR: &'static str = "could not construct a string";

        writeln!(description, "Name: {}", &self.name).expect(ERR);
        writeln!(description, "Lattice: {:?}", &self.lattice).expect(ERR);
        writeln!(description, "Normal: {}", &self.normal).expect(ERR);
        writeln!(description, "Residue: {}", &self.residue.code).expect(ERR);
        writeln!(description, "Z-variance: {}", &self.std_z.unwrap_or(0.0)).expect(ERR);

        description
    }

    fn describe_short(&self) -> String { self.describe() }
}

#[derive(Clone, Copy, Debug)]
enum SheetMenu {
    ChangeComponent,
    SetName,
    SetLattice,
    SetNormal,
    SetResidue,
    SetVarianceZ,
    QuitAndSave,
    QuitWithoutSaving,
}

fn create_sheet(residue_list: &[Residue]) -> result::Result<ComponentEntry, ChangeOrError> {
    use self::SheetMenu::*;

    let (commands, item_texts) = create_menu_items![
        (ChangeComponent, "Change component type"),
        (SetName, "Set name"),
        (SetResidue, "Set residue"),
        (SetLattice, "Set lattice"),
        (SetNormal, "Set normal vector direction"),
        (SetVarianceZ, "Set variance of residue positions along z"),
        (QuitAndSave, "Finalize component definition and return"),
        (QuitWithoutSaving, "Abort")
    ];

    let mut builder = SheetBuilder::initialize(&residue_list)?;

    loop {
        eprintln!("{}", builder.describe());

        let command = select_command(item_texts, commands).map_err(|err| UIErrorKind::from(err))?;

        match command {
            ChangeComponent => return Err(ChangeOrError::ChangeComponent),
            SetName => match get_value_from_user::<String>("Component name") {
                Ok(new_name) => {
                    builder.name = new_name;
                },
                Err(_) => {
                    eprintln!("error: Could not read name");
                },
            },
            SetResidue => match select_residue(&residue_list) {
                Ok(new_residue) => {
                    builder.residue = new_residue;
                },
                Err(_) => eprintln!("error: Could not select new residue"),
            },
            SetLattice => match select_lattice() {
                Ok(new_lattice) => {
                    builder.lattice = new_lattice;
                },
                Err(_) => eprintln!("error: Could not select new lattice"),
            },
            SetNormal => match select_direction() {
                Ok(new_direction) => {
                    builder.normal = new_direction;
                },
                Err(_) => eprintln!("error: Could not select new direction"),
            },
            SetVarianceZ => match get_variance() {
                Ok(new_std_z) => {
                    builder.std_z = new_std_z;
                },
                Err(_) => eprintln!("error: Could not read new variance"),
            },
            QuitAndSave => match builder.finalize() {
                Ok(component) => return Ok(component),
                Err(msg) => eprintln!("{}", msg),
            },
            QuitWithoutSaving => return Err(ChangeOrError::Error(UIErrorKind::Abort)),
        }
    }
}

fn get_variance() -> UIResult<Option<f64>> {
    let std = get_value_from_user::<f64>("Standard deviation 'σ' of distribution (nm)")?;

    if std == 0.0 {
        Ok(None)
    } else {
        Ok(Some(std))
    }
}

/*************************
 * Cylinder construction *
 *************************/

struct CylinderBuilder {
    name: String,
    cylinder_type: ComponentType,
    lattice: Option<LatticeType>,
    residue: Residue,
    density: Option<f64>,
    cap: Option<CylinderCap>,
    alignment: Direction,
}

impl CylinderBuilder {
    fn initialize(residue_list: &[Residue]) -> UIResult<CylinderBuilder> {
        let cylinder_type = select_cylinder_type()?;
        let residue = select_residue(&residue_list)?;

        let lattice = if cylinder_type == Surface {
            Some(select_lattice()?)
        } else {
            None
        };

        Ok(CylinderBuilder {
            name: String::new(),
            cylinder_type,
            lattice,
            residue,
            density: None,
            cap: None,
            alignment: Direction::Z,
        })
    }

    fn finalize(&self) -> result::Result<ComponentEntry, &str> {
        if self.name.is_empty() {
            return Err("Cannot add component: No name is set")
        } else {
            match self.cylinder_type {
                Surface => {
                    Ok(SurfaceCylinder(surface::Cylinder {
                        name: Some(self.name.clone()),
                        residue: Some(self.residue.clone()),
                        lattice: self.lattice.unwrap(),
                        alignment: self.alignment,
                        cap: self.cap,
                        origin: Coord::default(),
                        radius: 0.0,
                        height: 0.0,
                        coords: vec![],
                    }))
                },

                Volume => {
                    Ok(VolumeCylinder(volume::Cylinder {
                        name: Some(self.name.clone()),
                        residue: Some(self.residue.clone()),
                        alignment: self.alignment,
                        origin: Coord::default(),
                        radius: 0.0,
                        height: 0.0,
                        density: self.density,
                        coords: vec![],
                    }))
                },
            }
        }
    }
}

impl Describe for CylinderBuilder {
    fn describe(&self) -> String {
        let mut description = String::new();
        const ERR: &'static str = "could not construct a string";

        writeln!(description, "Name: {}", &self.name).expect(ERR);

        match self.cylinder_type {
            Surface => {
                writeln!(description, "Type: Cylinder Surface").expect(ERR);

                let lattice_string = match self.lattice {
                    Some(lattice) => format!("{:?}", lattice),
                    None => "".into(),
                };

                writeln!(description, "Lattice: {}", lattice_string).expect(ERR);
                writeln!(description, "Residue: {}", self.residue.code).expect(ERR);

                let cap_string = self.cap
                    .map(|cap| format!("{}", cap))
                    .unwrap_or("None".to_string());

                writeln!(description, "Cap: {}", cap_string).expect(ERR);
            },
            Volume => {
                writeln!(description, "Type: Cylinder Volume").expect(ERR);
                writeln!(description, "Residue: {}", self.residue.code).expect(ERR);

                let density_string = self.density
                    .map(|dens| format!("{}", dens))
                    .unwrap_or("None".into());
                writeln!(description, "Density: {}", density_string).expect(ERR);
            },
        }

        writeln!(description, "Alignment: {}", self.alignment).expect(ERR);

        description
    }

    fn describe_short(&self) -> String { self.describe() }
}

#[derive(Clone, Copy, Debug)]
enum CylinderSurfaceMenu {
    ChangeComponent,
    ChangeCylinderType,
    SetName,
    SetResidue,
    SetCap,
    SetAlignment,
    QuitAndSave,
    QuitWithoutSaving,
}

#[derive(Clone, Copy, Debug)]
enum CylinderVolumeMenu {
    ChangeComponent,
    ChangeCylinderType,
    SetName,
    SetResidue,
    SetDensity,
    SetAlignment,
    QuitAndSave,
    QuitWithoutSaving,
}

fn create_cylinder(residue_list: &[Residue]) -> result::Result<ComponentEntry, ChangeOrError> {
    let mut builder = CylinderBuilder::initialize(&residue_list)?;

    loop {
        print_description(&builder);

        // Always match against the type to select the correct menu
        match builder.cylinder_type {
            Surface => {
                use self::CylinderSurfaceMenu::*;

                // These are statically compiled so we can keep the construction in this loop
                let (surface_commands, surface_texts) = create_menu_items![
                    (ChangeComponent, "Change component type"),
                    (ChangeCylinderType, "Change cylinder type"),
                    (SetName, "Set name"),
                    (SetResidue, "Set residue"),
                    (SetCap, "Cap either cylinder edge"),
                    (SetAlignment, "Set cylinder main axis alignment"),
                    (QuitAndSave, "Finalize component definition and return"),
                    (QuitWithoutSaving, "Abort")
                ];

                let command = select_command(surface_texts, surface_commands)
                    .map_err(|err| UIErrorKind::from(err))?;

                match command {
                    ChangeComponent => return Err(ChangeOrError::ChangeComponent),
                    ChangeCylinderType => match select_cylinder_type() {
                        Ok(new_type) => {
                            let lattice = if new_type == Surface {
                                Some(select_lattice()?)
                            } else {
                                None
                            };

                            builder.cylinder_type = new_type;
                            builder.lattice = lattice;
                        },
                        Err(_) => eprintln!("error: Could not select new cylinder type"),
                    },
                    SetName => match get_value_from_user::<String>("Component name") {
                        Ok(new_name) => {
                            builder.name = new_name;
                        },
                        Err(_) => {
                            eprintln!("error: Could not read name");
                        },
                    },
                    SetResidue => match select_residue(&residue_list) {
                        Ok(new_residue) => {
                            builder.residue = new_residue;
                        },
                        Err(_) => eprintln!("error: Could not select new residue"),
                    },
                    SetCap => match select_cap() {
                        Ok(new_cap) => {
                            builder.cap = new_cap;
                        },
                        Err(_) => eprintln!("error: Could not select new cap"),
                    },
                    SetAlignment => match select_direction() {
                        Ok(new_direction) => {
                            builder.alignment = new_direction;
                        },
                        Err(_) => eprintln!("error: Could not select new direction"),
                    },
                    QuitAndSave => match builder.finalize() {
                        Ok(component) => return Ok(component),
                        Err(msg) => eprintln!("{}", msg),
                    },
                    QuitWithoutSaving => return Err(ChangeOrError::Error(UIErrorKind::Abort)),
                }
            },

            Volume => {
                use self::CylinderVolumeMenu::*;

                // These are statically compiled so we can keep the construction in this loop
                let (volume_commands, volume_texts) = create_menu_items![
                    (ChangeComponent, "Change component type"),
                    (ChangeCylinderType, "Change cylinder type"),
                    (SetName, "Set name"),
                    (SetResidue, "Set residue"),
                    (SetDensity, "Set default density"),
                    (SetAlignment, "Set cylinder main axis alignment"),
                    (QuitAndSave, "Finalize component definition and return"),
                    (QuitWithoutSaving, "Abort")
                ];

                let command = select_command(volume_texts, volume_commands)
                    .map_err(|err| UIErrorKind::from(err))?;

                match command {
                    ChangeComponent => return Err(ChangeOrError::ChangeComponent),
                    ChangeCylinderType => match select_cylinder_type() {
                        Ok(new_type) => {
                            let lattice = if new_type == Surface {
                                Some(select_lattice()?)
                            } else {
                                None
                            };

                            builder.cylinder_type = new_type;
                            builder.lattice = lattice;
                        },
                        Err(_) => eprintln!("error: Could not select new cylinder type"),
                    },
                    SetName => match get_value_from_user::<String>("Component name") {
                        Ok(new_name) => {
                            builder.name = new_name;
                        },
                        Err(_) => {
                            eprintln!("error: Could not read name");
                        },
                    },
                    SetResidue => match select_residue(&residue_list) {
                        Ok(new_residue) => {
                            builder.residue = new_residue;
                        },
                        Err(_) => eprintln!("error: Could not select new residue"),
                    },
                    SetDensity => match get_density() {
                        Ok(density) => {
                            builder.density = density;
                        },
                        Err(_) => eprintln!("error: Could not set density"),
                    },
                    SetAlignment => match select_direction() {
                        Ok(new_direction) => {
                            builder.alignment = new_direction;
                        },
                        Err(_) => eprintln!("error: Could not select new direction"),
                    },
                    QuitAndSave => match builder.finalize() {
                        Ok(component) => return Ok(component),
                        Err(msg) => eprintln!("{}", msg),
                    },
                    QuitWithoutSaving => return Err(ChangeOrError::Error(UIErrorKind::Abort)),
                }
            },
        }

        eprintln!("");
    }
}

fn select_cylinder_type() -> UIResult<ComponentType> {
    let (classes, item_texts) = create_menu_items![
        (Surface, "Surface"),
        (Volume, "Volume")
    ];

    select_command(item_texts, classes)
}

fn select_cap() -> UIResult<Option<CylinderCap>> {
    let choices = &[
        "Bottom",
        "Top"
    ];

    eprintln!("Set caps on cylinder sides ([space] select, [enter] confirm):");
    let selections = Checkboxes::new().items(choices).interact()?;

    match (selections.contains(&0), selections.contains(&1)) {
        (true, true) => Ok(Some(CylinderCap::Both)),
        (true, false) => Ok(Some(CylinderCap::Bottom)),
        (false, true) => Ok(Some(CylinderCap::Top)),
        _ => Ok(None),
    }
}

fn select_direction() -> UIResult<Direction> {
    use grafen::coord::Direction::*;

    let (choices, item_texts) = create_menu_items![
        (X, "X"),
        (Y, "Y"),
        (Z, "Z")
    ];

    select_command(item_texts, choices).map_err(|err| UIErrorKind::from(err))
}

/***********************
 * Cuboid construction *
 ***********************/

struct CuboidBuilder {
    name: String,
    residue: Residue,
    density: Option<f64>,
}

impl CuboidBuilder {
    fn initialize(residue_list: &[Residue]) -> UIResult<CuboidBuilder> {
        let residue = select_residue(&residue_list)?;

        Ok(CuboidBuilder {
            name: String::new(),
            residue,
            density: None,
        })
    }

    fn finalize(&self) -> result::Result<ComponentEntry, &str> {
        if self.name.is_empty() {
            return Err("Cannot add component: No name is set")
        } else {
            Ok(VolumeCuboid(volume::Cuboid {
                name: Some(self.name.clone()),
                residue: Some(self.residue.clone()),
                density: self.density.clone(),
                .. volume::Cuboid::default()
            }))
        }
    }
}

impl Describe for CuboidBuilder {
    fn describe(&self) -> String {
        let mut description = String::new();
        const ERR: &'static str = "could not construct a string";

        writeln!(description, "Name: {}", &self.name).expect(ERR);
        writeln!(description, "Residue: {}", self.residue.code).expect(ERR);

        let density_string = self.density.map(|dens| format!("{}", dens)).unwrap_or("None".into());
        writeln!(description, "Density: {}", density_string).expect(ERR);

        description
    }

    fn describe_short(&self) -> String { self.describe() }
}

#[derive(Clone, Copy, Debug)]
enum CuboidMenu {
    ChangeComponent,
    SetName,
    SetResidue,
    SetDensity,
    QuitAndSave,
    QuitWithoutSaving,
}

fn create_cuboid(residue_list: &[Residue]) -> result::Result<ComponentEntry, ChangeOrError> {
    let mut builder = CuboidBuilder::initialize(&residue_list)?;

    use self::CuboidMenu::*;

    loop {
        print_description(&builder);

        let (commands, item_texts) = create_menu_items![
            (ChangeComponent, "Change component type"),
            (SetName, "Set name"),
            (SetResidue, "Set residue"),
            (SetDensity, "Set default density"),
            (QuitAndSave, "Finalize component definition and return"),
            (QuitWithoutSaving, "Abort")
        ];

        let command = select_command(item_texts, commands)
            .map_err(|err| UIErrorKind::from(err))?;

        match command {
            ChangeComponent => return Err(ChangeOrError::ChangeComponent),
            SetName => match get_value_from_user::<String>("Component name") {
                Ok(new_name) => {
                    builder.name = new_name;
                },
                Err(_) => {
                    eprintln!("error: Could not read name");
                },
            },
            SetResidue => match select_residue(&residue_list) {
                Ok(new_residue) => {
                    builder.residue = new_residue;
                },
                Err(_) => eprintln!("error: Could not select new residue"),
            },
            SetDensity => match get_density() {
                Ok(density) => {
                    builder.density = density;
                },
                Err(_) => eprintln!("error: Could not set density"),
            },
            QuitAndSave => match builder.finalize() {
                Ok(component) => return Ok(component),
                Err(msg) => eprintln!("{}", msg),
            },
            QuitWithoutSaving => return Err(ChangeOrError::Error(UIErrorKind::Abort)),
        }

        eprintln!("");
    }
}

/************************************
 * Selection of lattice and residue *
 ************************************/

#[derive(Clone, Copy, Debug)]
/// Available lattices to construct from. Each of these require
/// a separate constructor since they have different qualities in
/// their corresponding `LatticeType` unit.
enum LatticeSelection {
    Triclinic,
    Hexagonal,
    PoissonDisc,
}

fn get_density() -> UIResult<Option<f64>> {
    let density = get_value_from_user::<f64>("Density (1/nm^3, negative: unset)")?;

    if density > 0.0 {
        Ok(Some(density))
    } else {
        Ok(None)
    }
}

fn select_residue(residue_list: &[Residue]) -> UIResult<Residue> {
    select_item(&residue_list, None).map(|res| res.clone())
}

fn select_lattice() -> UIResult<LatticeType> {
    use self::LatticeSelection::*;

    let (choices, item_texts) = create_menu_items![
        (Triclinic, "Triclinic lattice: two base vector lengths and an in-between angle"),
        (Hexagonal, "Hexagonal lattice: a honeycomb grid with a spacing"),
        (PoissonDisc, "Poisson disc: Randomly generated points with a density")
    ];

    let lattice = select_command(item_texts, choices)?;

    match lattice {
        Triclinic => {
            eprintln!("A triclinic lattice is constructed from two base ");
            eprintln!("vectors of length 'a' and 'b', separated by an angle 'γ'.");
            eprintln!("");

            let a = get_value_from_user::<f64>("Length 'a' (nm)")?;
            let b = get_value_from_user::<f64>("Length 'b' (nm)")?;
            let gamma = get_value_from_user::<f64>("Angle 'γ' (deg.)")?;

            Ok(LatticeType::Triclinic { a, b, gamma })
        },
        Hexagonal => {
            eprintln!("A hexagonal lattice is a honeycomb grid with an input side length 'a'.");
            eprintln!("");

            let a = get_value_from_user::<f64>("Spacing 'a' (nm)")?;

            Ok(LatticeType::Hexagonal { a })
        },
        PoissonDisc => {
            eprintln!("A Poisson disc is a generated set of points with an even distribution.");
            eprintln!("They are generated with an input density 'ρ' points per area.");
            eprintln!("");

            let density = get_value_from_user::<f64>("Density 'ρ' (1/nm^2)")?;

            Ok(LatticeType::PoissonDisc { density })
        },
    }
}