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
use errors::*;
use input;
use ndarray::{Array3, Zip};
use ndarray_parallel::prelude::*;
use noisy_float::prelude::*;
use output;
use rand;
use rand::distributions::{Distribution, Normal};
use serde_yaml;
use slog::Logger;
use std::fmt;
use std::fs::File;
#[derive(Serialize, Deserialize, Debug)]
pub struct Grid {
pub size: Index3,
pub dn: R64,
pub dt: R64,
}
#[derive(Serialize, Deserialize, Debug)]
struct Point3 {
x: R64,
y: R64,
z: R64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Index3 {
pub x: usize,
pub y: usize,
pub z: usize,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Output {
pub screen_update: u64,
pub snap_update: Option<u64>,
pub file_type: FileType,
pub save_wavefns: bool,
pub save_potential: bool,
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub enum PotentialType {
NoPotential,
Cube,
QuadWell,
Periodic,
Coulomb,
ComplexCoulomb,
ElipticalCoulomb,
SimpleCornell,
FullCornell,
Harmonic,
ComplexHarmonic,
Dodecahedron,
FromFile,
FromScript,
}
impl PotentialType {
pub fn variable_pot_sub(&self) -> bool {
match *self {
PotentialType::NoPotential
| PotentialType::Cube
| PotentialType::QuadWell
| PotentialType::Periodic
| PotentialType::Coulomb
| PotentialType::ComplexCoulomb
| PotentialType::Harmonic
| PotentialType::ComplexHarmonic
| PotentialType::Dodecahedron
| PotentialType::FromScript
| PotentialType::FromFile
| PotentialType::ElipticalCoulomb
| PotentialType::SimpleCornell => false,
PotentialType::FullCornell => true,
}
}
}
impl fmt::Display for PotentialType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
PotentialType::NoPotential => write!(f, "No potential (V=0)"),
PotentialType::Cube => write!(f, "3D square (i.e. cubic) well"),
PotentialType::QuadWell => write!(f, "3D quad well (short side along z-axis)"),
PotentialType::Periodic => write!(f, "Periodic"),
PotentialType::Coulomb => write!(f, "Coulomb"),
PotentialType::ComplexCoulomb => write!(f, "Complex coulomb"),
PotentialType::ElipticalCoulomb => write!(f, "Eliptical coulomb"),
PotentialType::SimpleCornell => write!(f, "Cornell"),
PotentialType::FullCornell => {
write!(f, "Fully anisotropic screened Cornell + spin correction")
}
PotentialType::Harmonic => write!(f, "Harmonic oscillator"),
PotentialType::ComplexHarmonic => write!(f, "Complex harmonic oscillator"),
PotentialType::Dodecahedron => write!(f, "Dodecahedron"),
PotentialType::FromFile => write!(f, "User generated potential from file"),
PotentialType::FromScript => write!(f, "User generated potential from script"),
}
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub enum InitialCondition {
FromFile,
Gaussian,
Coulomb,
Constant,
Boolean,
}
impl fmt::Display for InitialCondition {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InitialCondition::FromFile => write!(f, "From file on disk"),
InitialCondition::Gaussian => write!(f, "Random Gaussian"),
InitialCondition::Coulomb => write!(f, "Coulomb-like"),
InitialCondition::Constant => write!(f, "Constant of 0.1 in interior"),
InitialCondition::Boolean => write!(f, "Boolean test grid"),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
enum SymmetryConstraint {
NotConstrained,
AboutZ,
AntisymAboutZ,
AboutY,
AntisymAboutY,
}
impl fmt::Display for SymmetryConstraint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SymmetryConstraint::NotConstrained => write!(f, "None"),
SymmetryConstraint::AboutZ => write!(f, "Symmetric about z-axis"),
SymmetryConstraint::AntisymAboutZ => write!(f, "Antisymmetric about z-axis"),
SymmetryConstraint::AboutY => write!(f, "Symmetric about y-axis"),
SymmetryConstraint::AntisymAboutY => write!(f, "Antisymmetric about y-axis"),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub enum CentralDifference {
ThreePoint,
FivePoint,
SevenPoint,
}
impl CentralDifference {
pub fn bb(&self) -> usize {
match *self {
CentralDifference::ThreePoint => 2,
CentralDifference::FivePoint => 4,
CentralDifference::SevenPoint => 6,
}
}
pub fn ext(&self) -> usize {
match *self {
CentralDifference::ThreePoint => 1,
CentralDifference::FivePoint => 2,
CentralDifference::SevenPoint => 3,
}
}
}
impl fmt::Display for CentralDifference {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CentralDifference::ThreePoint => write!(f, "Three point: O(Δ{{x,y,z}}²)"),
CentralDifference::FivePoint => write!(f, "Five point: O(Δ{{x,y,z}}⁴)"),
CentralDifference::SevenPoint => write!(f, "Seven point: O(Δ{{x,y,z}}⁶)"),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub enum FileType {
Messagepack,
Csv,
Json,
Yaml,
Ron,
}
impl fmt::Display for FileType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
FileType::Messagepack => write!(f, "Messagepack"),
FileType::Csv => write!(f, "CSV"),
FileType::Json => write!(f, "JSON"),
FileType::Yaml => write!(f, "YAML"),
FileType::Ron => write!(f, "RON"),
}
}
}
impl FileType {
pub fn extentsion(&self) -> String {
match *self {
FileType::Messagepack => ".mpk".to_string(),
FileType::Csv => ".csv".to_string(),
FileType::Json => ".json".to_string(),
FileType::Yaml => ".yaml".to_string(),
FileType::Ron => ".ron".to_string(),
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
pub project_name: String,
pub grid: Grid,
pub tolerance: R64,
pub central_difference: CentralDifference,
pub max_steps: Option<u64>,
pub wavenum: u8,
pub wavemax: u8,
pub output: Output,
pub potential: PotentialType,
pub mass: R64,
pub init_condition: InitialCondition,
pub sig: f64,
init_symmetry: SymmetryConstraint,
#[serde(skip_deserializing)]
pub script_location: Option<String>,
}
impl Config {
pub fn load(file: &str, script: &str) -> Result<Config> {
let reader = File::open(file).chain_err(|| ErrorKind::ConfigLoad(file.to_string()))?;
let mut decoded_config: Config =
serde_yaml::from_reader(reader).chain_err(|| ErrorKind::Deserialize)?;
Config::parse(&decoded_config).chain_err(|| ErrorKind::ConfigParse)?;
if let PotentialType::FromScript = decoded_config.potential {
let mut locale = "./".to_string();
locale.push_str(script);
decoded_config.script_location = Some(locale);
} else {
decoded_config.script_location = None;
}
output::check_output_dir(&decoded_config.project_name)?;
output::copy_config(&decoded_config.project_name, file)
.chain_err(|| ErrorKind::CopyConfig(file.to_string()))?;
Ok(decoded_config)
}
fn parse(&self) -> Result<()> {
if self.grid.dt > self.grid.dn.powi(2) / r64(3.) {
return Err(ErrorKind::LargeDt.into());
}
if self.wavenum > self.wavemax {
return Err(ErrorKind::LargeWavenum.into());
}
Ok(())
}
pub fn print(&self, w: usize) {
println!(
"{:═^width$}",
format!(" {} - Configuration ", self.project_name),
width = w
);
let mid = w - 10;
if w > 95 {
let colwidth = mid / 4;
let dcolwidth = mid / 2;
println!(
"{:5}{:<dwidth$}{:<width$}{:<width$}",
"",
format!(
"Grid {{ x: {}, y: {}, z: {} }}",
self.grid.size.x, self.grid.size.y, self.grid.size.z
),
format!("Δ{{x,y,z}}: {:.3e}", self.grid.dn),
format!("Δt: {:.3e}", self.grid.dt),
dwidth = dcolwidth,
width = colwidth
);
println!(
"{:5}{:<width$}{:<width$}{:<width$}{:<width$}",
"",
format!("Screen update: {}", self.output.screen_update),
if self.output.snap_update.is_some() {
format!("Snapshot update: {}", self.output.snap_update.unwrap())
} else {
"Snapshot update: Off".to_string()
},
format!("Save wavefns: {}", self.output.save_wavefns),
format!("Save potential: {}", self.output.save_potential),
width = colwidth
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("CD precision: {}", self.central_difference),
format!("Output file format: {}", self.output.file_type),
width = dcolwidth
);
println!(
"{:5}{:<twidth$}{:<width$}",
"",
format!("Potential: {}", self.potential),
format!("Mass: {} amu", self.mass),
twidth = colwidth * 3,
width = colwidth
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Energy covergence tolerance: {:.3e}", self.tolerance),
if self.max_steps.is_some() {
format!(
"Maximum number of steps: {:.3e}",
self.max_steps.unwrap() as f64
)
} else {
"Maximum number of steps: ∞".to_string()
},
width = dcolwidth
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Starting wavefunction: {}", self.wavenum),
format!("Maximum wavefunction: {}", self.wavemax),
width = dcolwidth
);
if self.init_condition == InitialCondition::Gaussian {
println!(
"{:5}{:<width$}{:<width$}",
"",
format!(
"Initial conditions: {} ({} σ)",
self.init_condition, self.sig
),
format!("Symmetry Constraints: {}", self.init_symmetry),
width = dcolwidth
);
} else {
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Initial conditions: {}", self.init_condition),
format!("Symmetry Constraints: {}", self.init_symmetry),
width = dcolwidth
);
}
} else {
let colwidth = mid / 2;
println!(
"{:5}{}",
"",
format!(
"Grid {{ x: {}, y: {}, z: {} }}",
self.grid.size.x, self.grid.size.y, self.grid.size.z
)
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Δ{{x,y,z}}: {:.3e}", self.grid.dn),
format!("Δt: {:.3e}", self.grid.dt),
width = colwidth
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Screen update: {}", self.output.screen_update),
if self.output.snap_update.is_some() {
format!("Snapshot update: {}", self.output.snap_update.unwrap())
} else {
"Snapshot update: Off".to_string()
},
width = colwidth
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Save wavefns: {}", self.output.save_wavefns),
format!("Save potential: {}", self.output.save_potential),
width = colwidth
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("CD precision: {}", self.central_difference),
format!("Output file format: {}", self.output.file_type),
width = colwidth
);
println!(
"{:5}{:<twidth$}{:<width$}",
"",
format!("Potential: {}", self.potential),
format!("Mass: {} amu", self.mass),
twidth = (mid / 4) * 3,
width = mid / 4
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Energy covergence tolerance: {:.3e}", self.tolerance),
if self.max_steps.is_some() {
format!(
"Maximum number of steps: {:.3e}",
self.max_steps.unwrap() as f64
)
} else {
"Maximum number of steps: ∞".to_string()
},
width = colwidth
);
println!(
"{:5}{:<width$}{:<width$}",
"",
format!("Starting wavefunction: {}", self.wavenum),
format!("Maximum wavefunction: {}", self.wavemax),
width = colwidth
);
if self.init_condition == InitialCondition::Gaussian {
println!(
"{:5}{}",
"",
format!(
"Initial conditions: {} ({} σ)",
self.init_condition, self.sig
)
);
println!(
"{:5}{}",
"",
format!("Symmetry Constraints: {}", self.init_symmetry)
);
} else {
println!(
"{:5}{}",
"",
format!("Initial conditions: {}", self.init_condition)
);
println!(
"{:5}{}",
"",
format!("Symmetry Constraints: {}", self.init_symmetry)
);
}
}
println!("{:═^width$}", "", width = w);
}
}
pub fn set_initial_conditions(config: &Config, log: &Logger) -> Result<Array3<R64>> {
info!(log, "Setting initial conditions for wavefunction");
let num = &config.grid.size;
let bb = config.central_difference.bb();
let init_size: [usize; 3] = [
num.x as usize + bb,
num.y as usize + bb,
num.z as usize + bb,
];
let mut w: Array3<R64> = match config.init_condition {
InitialCondition::FromFile => {
input::wavefunction(config.wavenum, init_size, bb, &config.output.file_type, log)
.chain_err(|| ErrorKind::LoadWavefunction(config.wavenum))?
}
InitialCondition::Gaussian => generate_gaussian(config, init_size),
InitialCondition::Coulomb => generate_coulomb(config, init_size),
InitialCondition::Constant => Array3::<R64>::from_elem(init_size, r64(0.1)),
InitialCondition::Boolean => generate_boolean(init_size),
};
let ext = config.central_difference.ext() as isize;
w.slice_mut(s![.., .., 0..ext])
.par_map_inplace(|el| *el = r64(0.));
w.slice_mut(s![
..,
..,
init_size[2] as isize - ext..init_size[2] as isize
]).par_map_inplace(|el| *el = r64(0.));
w.slice_mut(s![0..ext, .., ..])
.par_map_inplace(|el| *el = r64(0.));
w.slice_mut(s![
init_size[0] as isize - ext..init_size[0] as isize,
..,
..
]).par_map_inplace(|el| *el = r64(0.));
w.slice_mut(s![.., 0..ext, ..])
.par_map_inplace(|el| *el = r64(0.));
w.slice_mut(s![
..,
init_size[1] as isize - ext..init_size[1] as isize,
..
]).par_map_inplace(|el| *el = r64(0.));
symmetrise_wavefunction(config, &mut w);
Ok(w)
}
fn generate_gaussian(config: &Config, init_size: [usize; 3]) -> Array3<R64> {
let normal = Normal::new(0.0, config.sig);
let mut w = Array3::<R64>::zeros(init_size);
w.par_map_inplace(|el| *el = r64(normal.sample(&mut rand::thread_rng())));
w
}
fn generate_coulomb(config: &Config, init_size: [usize; 3]) -> Array3<R64> {
let mut w = Array3::<R64>::zeros(init_size);
Zip::indexed(&mut w).par_apply(|(i, j, k), x| {
let dx = r64(i as f64) - (r64(init_size[0] as f64) / r64(2.));
let dy = r64(j as f64) - (r64(init_size[1] as f64) / r64(2.));
let dz = r64(k as f64) - (r64(init_size[2] as f64) / r64(2.));
let r = config.grid.dn * (dx.powi(2) + dy.powi(2) + dz.powi(2)).sqrt();
let costheta = config.grid.dn * dz / r;
let cosphi = config.grid.dn * dx / r;
let mr2 = (-config.mass * r / r64(2.)).exp();
*x = (-config.mass * r).exp()
+ (r64(2.) - config.mass * r) * mr2
+ config.mass * r * mr2 * costheta
+ config.mass * r * mr2 * (r64(1.) - costheta.powi(2)).sqrt() * cosphi;
});
w
}
fn generate_boolean(init_size: [usize; 3]) -> Array3<R64> {
let mut w = Array3::<R64>::zeros(init_size);
Zip::indexed(&mut w).par_apply(|(i, j, k), el| {
*el = r64(i as f64) % r64(2.) * r64(j as f64) % r64(2.) * r64(k as f64) % r64(2.);
});
w
}
pub fn symmetrise_wavefunction(config: &Config, w: &mut Array3<R64>) {
let num = &config.grid.size;
let sign = match config.init_symmetry {
SymmetryConstraint::NotConstrained => r64(0.),
SymmetryConstraint::AntisymAboutY | SymmetryConstraint::AntisymAboutZ => r64(-1.),
SymmetryConstraint::AboutY | SymmetryConstraint::AboutZ => r64(1.),
};
match config.init_symmetry {
SymmetryConstraint::NotConstrained => {}
SymmetryConstraint::AboutZ | SymmetryConstraint::AntisymAboutZ => {
for sx in 0..(num.x + 6) {
for sy in 3..(3 + num.y + 1) {
for sz in 3..(3 + num.z + 1) {
let mut z = sz;
if z > (3 + num.z) / 2 {
z = (3 + num.z) + 1 - z;
}
w[[sx, sy, sz]] = sign * w[[sx, sy, z]];
}
}
}
}
SymmetryConstraint::AboutY | SymmetryConstraint::AntisymAboutY => {
for sx in 0..(num.x + 6) {
for sy in 3..(3 + num.y + 1) {
let mut y = sy;
if y > (3 + num.y) / 2 {
y = (3 + num.y) + 1 - y;
}
for sz in 3..(3 + num.z + 1) {
w[[sx, sy, sz]] = sign * w[[sx, y, sz]];
}
}
}
}
};
}