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
use config;
use config::{CentralDifference, Config, Index3, InitialCondition};
use errors::*;
use indicatif::{ProgressBar, ProgressStyle};
use input;
use ndarray::{Array3, ArrayView3, ArrayViewMut3, Zip};
use ndarray_parallel::prelude::*;
use noisy_float::prelude::*;
use output;
use potential;
use potential::Potentials;
use slog::Logger;
use std::f64::MAX;
#[derive(Debug)]
pub struct Observables {
pub energy: R64,
pub norm2: R64,
pub v_infinity: R64,
pub r2: R64,
}
pub fn run(config: &Config, log: &Logger, debug_level: usize) -> Result<()> {
let potentials = potential::load_arrays(config, log)?;
let mut w_store: Vec<Array3<R64>> = Vec::new();
if config.wavenum > 0 {
input::load_wavefunctions(config, log, &mut w_store)?;
}
info!(log, "Starting calculation");
for wnum in config.wavenum..config.wavemax + 1 {
solve(config, log, debug_level, &potentials, wnum, &mut w_store)?;
}
Ok(())
}
fn solve(
config: &Config,
log: &Logger,
debug_level: usize,
potentials: &Potentials,
wnum: u8,
w_store: &mut Vec<Array3<R64>>,
) -> Result<()> {
let mut phi: Array3<R64> = if wnum > 0 {
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,
];
if let Ok(wfn) = input::wavefunction(wnum, init_size, bb, &config.output.file_type, log) {
info!(log, "Loaded (current) wavefunction {} from disk", wnum);
if config.init_condition != InitialCondition::FromFile && wnum > config.wavenum {
warn!(
log,
"Loaded a higher order wavefunction from disk although Initial conditions are set to '{}'.",
config.init_condition
);
}
wfn
} else {
info!(
log,
"Loaded wavefunction {} from memory as initial condition",
wnum - 1
);
w_store[wnum as usize - 1].clone()
}
} else {
config::set_initial_conditions(config, log).chain_err(|| ErrorKind::SetInitialConditions)?
};
output::print_observable_header(wnum);
let prog_bar = ProgressBar::new(100);
if debug_level == 3 {
let term_width = *output::TERMWIDTH;
let bar_width = (term_width - 24).to_string();
let mut bar_template = String::new();
bar_template.push_str("{msg}\n\n[{elapsed_precise}] |{bar:");
bar_template.push_str(&bar_width);
bar_template.push_str(".cyan/blue}| {spinner:.green} ETA: {eta:>3}");
prog_bar.set_style(
ProgressStyle::default_bar()
.template(&bar_template)
.progress_chars("█▓░")
.tick_chars("⣾⣽⣻⢿⡿⣟⣯⣷ "),
);
prog_bar.set_position(0);
}
let mut step = 0;
let mut converged = false;
let mut last_energy = r64(MAX);
let mut diff_old = MAX;
loop {
let observables = compute_observables(config, potentials, &phi);
let norm_energy = observables.energy / observables.norm2;
let tau = r64(step as f64) * config.grid.dt;
normalise_wavefunction(&mut phi, observables.norm2);
if wnum > 0 {
orthogonalise_wavefunction(wnum, &mut phi, w_store);
}
if config.output.snap_update.is_some() && step % config.output.snap_update.unwrap() == 0 {
config::symmetrise_wavefunction(config, &mut phi);
normalise_wavefunction(&mut phi, observables.norm2);
let ext = config.central_difference.ext();
let work = get_work_area(&phi, ext);
info!(
log,
"Saving partially converged wavefunction {} to disk.", wnum
);
if let Err(err) = output::wavefunction(
&work,
wnum,
false,
&config.project_name,
&config.output.file_type,
) {
warn!(
log,
"Could not output partial wavefunction per snap_update request: {}", err
);
}
}
let diff = (norm_energy - last_energy).abs();
if diff < config.tolerance {
if debug_level == 3 {
prog_bar.finish_and_clear();
}
println!("{}", output::print_measurements(tau, diff, &observables));
output::finalise_measurement(
&observables,
wnum,
r64(config.grid.size.x as f64),
&config.project_name,
&config.output.file_type,
)?;
if config.output.snap_update.is_some() {
info!(
log,
"Removing partially converged wavefunction {} from disk.", wnum
);
if let Err(err) =
output::remove_partial(wnum, &config.project_name, &config.output.file_type)
{
warn!(
log,
"The temporary wavefunction_{}_partial{} file could not be removed from the output directory: {}",
wnum,
config.output.file_type.extentsion(),
err
);
}
}
converged = true;
break;
} else {
last_energy = norm_energy;
}
if debug_level == 3 {
if let Some(estimate) = eta(step, diff_old, diff.raw(), config) {
let percent = (100. - (estimate
/ ((step as f64 / config.output.screen_update as f64) + estimate)
* 100.))
.floor();
if percent.is_finite() {
prog_bar.set_position(percent as u64);
}
}
prog_bar.set_message(&output::print_measurements(tau, diff, &observables));
}
if config.max_steps.is_some() && step > config.max_steps.unwrap() {
break;
}
evolve(wnum, config, potentials, &mut phi, w_store);
diff_old = diff.raw();
step += config.output.screen_update;
}
if config.output.save_wavefns {
info!(log, "Saving wavefunction {} to disk", wnum);
let work = get_work_area(&phi, config.central_difference.ext());
if let Err(err) = output::wavefunction(
&work,
wnum,
converged,
&config.project_name,
&config.output.file_type,
) {
warn!(log, "Could not write wavefunction to disk: {}", err);
}
}
if converged {
info!(log, "Caluculation Converged");
w_store.push(phi);
Ok(())
} else {
Err(ErrorKind::MaxStep.into())
}
}
fn eta(step: u64, diff_old: f64, diff_new: f64, config: &Config) -> Option<f64> {
let x1 = step as f64;
let y1 = diff_new.log10();
let rise = y1 - diff_old.log10();
let run = config.output.screen_update as f64;
let m = rise / run;
let x = ((config.tolerance.log10().raw() - y1) / m) + x1;
if x.is_finite() {
let estimate = ((x - x1) / run).floor();
if estimate > 0. {
return Some(estimate);
}
}
None
}
fn compute_observables(config: &Config, potentials: &Potentials, phi: &Array3<R64>) -> Observables {
let ext = config.central_difference.ext();
let phi_work = get_work_area(phi, ext);
let mut work = Array3::<R64>::zeros(phi_work.dim());
let energy = {
let v = get_work_area(&potentials.v, ext);
match config.central_difference {
CentralDifference::ThreePoint => {
let denominator = r64(2.) * config.grid.dn * config.grid.dn * config.mass;
Zip::indexed(&mut work).and(v).and(phi_work).par_apply(
|(i, j, k), work, &v, &w| {
let lx = i as isize + 1;
let ly = j as isize + 1;
let lz = k as isize + 1;
let o = 1;
let l = phi.slice(s![lx - 1..lx + 2, ly - 1..ly + 2, lz - 1..lz + 2]);
*work = v * w * w
- w * (l[[o + 1, o, o]]
+ l[[o - 1, o, o]]
+ l[[o, o + 1, o]]
+ l[[o, o - 1, o]]
+ l[[o, o, o + 1]]
+ l[[o, o, o - 1]] - r64(6.) * w)
/ denominator;
},
);
}
CentralDifference::FivePoint => {
let denominator = r64(24.) * config.grid.dn * config.grid.dn * config.mass;
Zip::indexed(&mut work).and(v).and(phi_work).par_apply(
|(i, j, k), work, &v, &w| {
let lx = i as isize + 2;
let ly = j as isize + 2;
let lz = k as isize + 2;
let o = 2;
let _16 = r64(16.);
let l = phi.slice(s![lx - 2..lx + 3, ly - 2..ly + 3, lz - 2..lz + 3]);
*work = v * w * w
- w * (-l[[o + 2, o, o]]
+ _16 * l[[o + 1, o, o]]
+ _16 * l[[o - 1, o, o]]
- l[[o - 2, o, o]]
- l[[o, o + 2, o]]
+ _16 * l[[o, o + 1, o]]
+ _16 * l[[o, o - 1, o]]
- l[[o, o - 2, o]]
- l[[o, o, o + 2]]
+ _16 * l[[o, o, o + 1]]
+ _16 * l[[o, o, o - 1]]
- l[[o, o, o - 2]]
- r64(90.) * w) / denominator;
},
);
}
CentralDifference::SevenPoint => {
let denominator = r64(360.) * config.grid.dn * config.grid.dn * config.mass;
Zip::indexed(&mut work).and(v).and(phi_work).par_apply(
|(i, j, k), work, &v, &w| {
let lx = i as isize + 3;
let ly = j as isize + 3;
let lz = k as isize + 3;
let o = 3;
let _2 = r64(2.);
let _27 = r64(27.);
let _270 = r64(270.);
let l = phi.slice(s![lx - 3..lx + 4, ly - 3..ly + 4, lz - 3..lz + 4]);
*work = v * w * w
- w * (_2 * l[[o + 3, o, o]] - _27 * l[[o + 2, o, o]]
+ _270 * l[[o + 1, o, o]]
+ _270 * l[[o - 1, o, o]]
- _27 * l[[o - 2, o, o]]
+ _2 * l[[o - 3, o, o]]
+ _2 * l[[o, o + 3, o]]
- _27 * l[[o, o + 2, o]]
+ _270 * l[[o, o + 1, o]]
+ _270 * l[[o, o - 1, o]]
- _27 * l[[o, o - 2, o]]
+ _2 * l[[o, o - 3, o]]
+ _2 * l[[o, o, o + 3]]
- _27 * l[[o, o, o + 2]]
+ _270 * l[[o, o, o + 1]]
+ _270 * l[[o, o, o - 1]]
- _27 * l[[o, o, o - 2]]
+ _2 * l[[o, o, o - 3]]
- r64(1470.) * w) / denominator;
},
);
}
}
r64(work.into_par_iter().map(|i| i.raw()).sum())
};
let norm2 = phi_work.into_par_iter().map(|&el| el * el).sum();
let v_infinity = {
match potentials.pot_sub {
(Some(ref potsub), None) => {
Zip::from(&mut work)
.and(phi_work)
.and(potsub.view())
.par_apply(|work, &w, &potsub| {
*work = w * w * potsub;
});
work.into_par_iter().map(|i| i.raw()).sum()
}
(None, Some(potsub)) => {
Zip::from(&mut work).and(phi_work).par_apply(|work, &w| {
*work = w * w * potsub;
});
work.into_par_iter().map(|i| i.raw()).sum()
}
_ => 0.,
}
};
let r2 = {
Zip::indexed(&mut work)
.and(phi_work)
.par_apply(|(i, j, k), work, &w| {
let idx = Index3 { x: i, y: j, z: k };
let r2 = potential::calculate_r2(&idx, &config.grid);
*work = w * w * r2;
});
work.into_par_iter().map(|i| i.raw()).sum()
};
Observables {
energy: energy,
norm2: norm2,
v_infinity: r64(v_infinity),
r2: r64(r2),
}
}
fn get_norm_squared(w: &ArrayView3<R64>) -> R64 {
w.into_par_iter().map(|&el| el * el).sum()
}
fn normalise_wavefunction(w: &mut Array3<R64>, norm2: R64) {
let norm = norm2.sqrt();
w.par_map_inplace(|el| *el /= norm);
}
fn orthogonalise_wavefunction(wnum: u8, w: &mut Array3<R64>, w_store: &[Array3<R64>]) {
for lower in w_store.iter().take(wnum as usize) {
let mut overlap = Array3::<R64>::zeros(w.dim());
Zip::from(&mut overlap)
.and(lower)
.and(w.view())
.par_apply(|overlap, &lower, &w| *overlap = lower * w);
let overlap_sum: f64 = overlap.into_par_iter().map(|i| i.raw()).sum();
Zip::from(w.view_mut())
.and(lower)
.par_apply(|w, &lower| *w -= lower * overlap_sum);
}
}
pub fn get_work_area(arr: &Array3<R64>, ext: usize) -> ArrayView3<R64> {
let dims = arr.dim();
let exti = ext as isize;
arr.slice(s![
exti..dims.0 as isize - exti,
exti..dims.1 as isize - exti,
exti..dims.2 as isize - exti
])
}
pub fn get_mut_work_area(arr: &mut Array3<R64>, ext: usize) -> ArrayViewMut3<R64> {
let dims = arr.dim();
let exti = ext as isize;
arr.slice_mut(s![
exti..dims.0 as isize - exti,
exti..dims.1 as isize - exti,
exti..dims.2 as isize - exti
])
}
fn evolve(
wnum: u8,
config: &Config,
potentials: &Potentials,
phi: &mut Array3<R64>,
w_store: &[Array3<R64>],
) {
let bb = config.central_difference.bb();
let ext = config.central_difference.ext();
let mut work_dims = phi.dim();
work_dims.0 -= bb;
work_dims.1 -= bb;
work_dims.2 -= bb;
let pa = get_work_area(&potentials.a, ext);
let pb = get_work_area(&potentials.b, ext);
let mut work = Array3::<R64>::zeros(work_dims);
let mut steps = 0;
loop {
{
let w = get_work_area(phi, ext);
match config.central_difference {
CentralDifference::ThreePoint => {
let denominator = r64(2.) * config.grid.dn * config.grid.dn * config.mass;
Zip::indexed(&mut work).and(pa).and(pb).and(w).par_apply(
|(i, j, k), work, &pa, &pb, &w| {
let lx = i as isize + 1;
let ly = j as isize + 1;
let lz = k as isize + 1;
let o = 1;
let l = phi.slice(s![lx - 1..lx + 2, ly - 1..ly + 2, lz - 1..lz + 2]);
*work = w * pa
+ pb * config.grid.dt
* (l[[o + 1, o, o]]
+ l[[o - 1, o, o]]
+ l[[o, o + 1, o]]
+ l[[o, o - 1, o]]
+ l[[o, o, o + 1]]
+ l[[o, o, o - 1]]
- r64(6.) * w)
/ denominator;
},
);
}
CentralDifference::FivePoint => {
let denominator = r64(24.) * config.grid.dn * config.grid.dn * config.mass;
Zip::indexed(&mut work).and(pa).and(pb).and(w).par_apply(
|(i, j, k), work, &pa, &pb, &w| {
let lx = i as isize + 2;
let ly = j as isize + 2;
let lz = k as isize + 2;
let o = 2;
let _16 = r64(16.);
let l = phi.slice(s![lx - 2..lx + 3, ly - 2..ly + 3, lz - 2..lz + 3]);
*work = w * pa
+ pb * config.grid.dt
* (-l[[o + 2, o, o]]
+ _16 * l[[o + 1, o, o]]
+ _16 * l[[o - 1, o, o]]
- l[[o - 2, o, o]]
- l[[o, o + 2, o]]
+ _16 * l[[o, o + 1, o]]
+ _16 * l[[o, o - 1, o]]
- l[[o, o - 2, o]]
- l[[o, o, o + 2]]
+ _16 * l[[o, o, o + 1]]
+ _16 * l[[o, o, o - 1]]
- l[[o, o, o - 2]]
- r64(90.) * w)
/ denominator;
},
);
}
CentralDifference::SevenPoint => {
let denominator = r64(360.) * config.grid.dn * config.grid.dn * config.mass;
Zip::indexed(&mut work).and(pa).and(pb).and(w).par_apply(
|(i, j, k), work, &pa, &pb, &w| {
let lx = i as isize + 3;
let ly = j as isize + 3;
let lz = k as isize + 3;
let o = 3;
let _2 = r64(2.);
let _27 = r64(27.);
let _270 = r64(270.);
let l = phi.slice(s![lx - 3..lx + 4, ly - 3..ly + 4, lz - 3..lz + 4]);
*work = w * pa
+ pb * config.grid.dt
* (_2 * l[[o + 3, o, o]] - _27 * l[[o + 2, o, o]]
+ _270 * l[[o + 1, o, o]]
+ _270 * l[[o - 1, o, o]]
- _27 * l[[o - 2, o, o]]
+ _2 * l[[o - 3, o, o]]
+ _2 * l[[o, o + 3, o]]
- _27 * l[[o, o + 2, o]]
+ _270 * l[[o, o + 1, o]]
+ _270 * l[[o, o - 1, o]]
- _27 * l[[o, o - 2, o]]
+ _2 * l[[o, o - 3, o]]
+ _2 * l[[o, o, o + 3]]
- _27 * l[[o, o, o + 2]]
+ _270 * l[[o, o, o + 1]]
+ _270 * l[[o, o, o - 1]]
- _27 * l[[o, o, o - 2]]
+ _2 * l[[o, o, o - 3]]
- r64(1470.) * w)
/ denominator;
},
);
}
}
}
{
let mut w_fill = get_mut_work_area(phi, ext);
Zip::from(&mut w_fill)
.and(&work)
.par_apply(|w_fill, &work| {
*w_fill = work;
});
}
if wnum > 0 {
let norm2 = {
let phi_work = get_work_area(phi, ext);
get_norm_squared(&phi_work)
};
normalise_wavefunction(phi, norm2);
orthogonalise_wavefunction(wnum, phi, w_store);
}
steps += 1;
if steps >= config.output.screen_update {
break;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => {{
let eps = 1.0e-6;
let (a, b) = (&$a, &$b);
assert!(
(*a - *b).abs() < eps,
"assertion failed: `(left !== right)` \
(left: `{:?}`, right: `{:?}`, expect diff: `{:?}`, real diff: `{:?}`)",
*a,
*b,
eps,
(*a - *b).abs()
);
}};
($a:expr, $b:expr, $eps:expr) => {{
let (a, b) = (&$a, &$b);
assert!(
(*a - *b).abs() < $eps,
"assertion failed: `(left !== right)` \
(left: `{:?}`, right: `{:?}`, expect diff: `{:?}`, real diff: `{:?}`)",
*a,
*b,
$eps,
(*a - *b).abs()
);
}};
}
#[test]
fn gram_schmidt() {
let ground = Array3::<R64>::from_shape_fn((2, 2, 2), |(i, j, k)| r64((i + j + k) as f64));
let w_store: Vec<Array3<R64>> = vec![ground];
let mut test = Array3::<R64>::from_shape_fn((2, 2, 2), |(i, j, k)| {
let (fi, fj, fk) = (i as f64, j as f64, k as f64);
r64(-fi - fj - fk)
});
orthogonalise_wavefunction(1, &mut test, &w_store);
let compare = Array3::<R64>::from_shape_vec(
(2, 2, 2),
vec![
r64(0.),
r64(23.),
r64(23.),
r64(46.),
r64(23.),
r64(46.),
r64(46.),
r64(69.),
],
).unwrap();
assert!(compare.all_close(&test, r64(0.01)));
}
#[test]
fn work_area() {
let test = Array3::<R64>::zeros((5, 8, 7));
let work = get_work_area(&test, 1);
let dims = work.dim();
assert_eq!(dims.0, 3);
assert_eq!(dims.1, 6);
assert_eq!(dims.2, 5);
}
#[test]
fn mut_work_area() {
let mut test = Array3::<R64>::zeros((5, 8, 7));
let dims = {
let mut work = get_mut_work_area(&mut test, 1);
work.fill(r64(1.));
work.dim()
};
let compare = Array3::<R64>::from_shape_fn((5, 8, 7), |(i, j, k)| {
if (i == 0 || i == 4) || (j == 0 || j == 7) || (k == 0 || k == 6) {
r64(0.)
} else {
r64(1.)
}
});
assert_eq!(dims.0, 3);
assert_eq!(dims.1, 6);
assert_eq!(dims.2, 5);
assert!(compare.all_close(&test, r64(0.01)));
}
#[test]
fn norm2() {
let test = Array3::<R64>::from_shape_fn((5, 8, 7), |(i, j, k)| r64((i * j * k) as f64));
let work = get_work_area(&test, 1);
let result = get_norm_squared(&work);
assert_approx_eq!(result, r64(70070.));
}
#[test]
fn wfn_normalise() {
let normalised = Array3::<R64>::from_shape_fn((3, 2, 5), |(i, j, k)| {
let norm = r64(1.1091);
r64((i * j * k) as f64) / norm
});
let mut test = Array3::<R64>::from_shape_fn((3, 2, 5), |(i, j, k)| r64((i * j * k) as f64));
normalise_wavefunction(&mut test, r64(1.23));
assert!(test.all_close(&normalised, r64(0.01)));
}
}