-
Notifications
You must be signed in to change notification settings - Fork 1
/
soap.py
3919 lines (3444 loc) · 168 KB
/
soap.py
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
993
994
995
996
997
998
999
1000
# coding=utf-8
from __future__ import print_function
import copy
import itertools
import numbers
import os
import sys
from timeit import default_timer as timer
import numpy as np
import scipy
import scipy.special as sp
import GPy
from GPy.kern import Kern
from GPy import Param
from paramz.caching import Cache_this
from paramz.transformations import Logexp, Logistic
import ase
import ase.neighborlist
from atatutils.str2gpaw import ATAT2GPAW
from atatutils.file_parsers import ATATStructure
from exp_spherical_in import exp_spherical_in
def gregory_weights(n_nodes, h, order):
from scipy.linalg import cholesky, pascal, toeplitz
# http://www.colorado.edu/amath/sites/default/files/attached-files/gregory.pdf
# Create Gregory coefficients
r = 1./np.arange(1, order + 1)
tp = toeplitz(r[:-1], r[0] * np.eye(1, order - 1))
gc = np.linalg.solve(tp, r[1:])
# create the weights
w = h * np.ones(n_nodes)
# Generate the Pascal Cholesky factor (up to signs).
# http://opg1.ucsd.edu/~sio221/SIO_221A_2009/SIO_221_Data/Matlab5/Toolbox/matlab/elmat/pascal.m
P = np.diag((-1)**np.arange(order - 1, dtype=int))
P[:, 0] = np.ones(order - 1)
for j in range(1, order - 2):
for i in range(j + 1, order - 1):
P[i, j] = P[i - 1, j] - P[i - 1, j - 1]
# Update the endpoint weights
w_updates = np.sum(h * np.repeat(gc.reshape(order - 1, 1), order -1, 1) * P, axis=0)
w[:order - 1] -= w_updates
w[:-order:-1] -= w_updates
return w
def gram_schmidt(vectors, inner_product):
basis = []
for v in vectors:
w = v - np.sum(inner_product(v, b) * b for b in basis)
if (w > 1e-10).any():
basis.append(w / np.sqrt(inner_product(w, w)))
return np.array(basis)
def r_basis(n, delta_r, alpha, x):
return np.exp(-alpha*(x-n*delta_r)**2)
def dr_basis_dalpha(n, delta_r, alpha, x):
return (x - n*delta_r)**2
def phi_mat(n, delta_r, alpha, x):
phi = np.empty((len(n), len(x)))
for i in range(len(n)):
for j in range(len(x)):
phi[i, j] = r_basis(n[i], delta_r, alpha, x[j])
return phi
def basis_overlap(nmax, rcut, alpha):
overlap = np.empty((nmax, nmax))
c1 = np.sqrt(2*alpha**3)/np.sqrt(128*alpha**5)
c2 = np.sqrt(np.pi)*alpha/np.sqrt(128*alpha**5)
for i in range(nmax):
for j in range(i + 1):
ri = i*(rcut/nmax)
rj = j*(rcut/nmax)
T1 = c1 * np.exp(-alpha*(ri**2 + rj**2)) * (ri + rj)
T1 -= c1 * np.exp(-alpha*(2*rcut**2 + ri**2 + rj**2 - 2*rcut*(ri+rj))) * (2*rcut + ri + rj)
T2 = c2 * np.exp(-alpha/2.*(ri-rj)**2) * (1. + alpha*(ri + rj)**2) * \
(sp.erf(np.sqrt(alpha/2) * (2*rcut - ri - rj)) + sp.erf(np.sqrt(alpha/2) * (ri + rj)))
overlap[i, j] = overlap[j, i] = T1 + T2
return overlap
def sympy_basis_overlap(nmax, rcut):
from sympy import Matrix, sqrt, pi, exp, erf
from sympy.abc import a
overlap = [0] * nmax
for i in range(len(overlap)):
overlap[i] = [0] * nmax
c1 = sqrt(2 * a ** 3) / sqrt(128 * a ** 5)
c2 = sqrt(pi) * a / sqrt(128 * a ** 5)
for i in range(nmax):
for j in range(i + 1):
ri = i * (rcut / nmax)
rj = j * (rcut / nmax)
T1 = c1 * exp(-a * (ri ** 2 + rj ** 2)) * (ri + rj)
T1 -= c1 * exp(-a * (2 * rcut ** 2 + ri ** 2 + rj ** 2 - 2 * rcut * (ri + rj))) * (
2 * rcut + ri + rj)
T2 = c2 * exp(-a / 2. * (ri - rj) ** 2) * (1. + a * (ri + rj) ** 2) * \
(erf(sqrt(a / 2) * (2 * rcut - ri - rj)) + erf(sqrt(a / 2) * (ri + rj)))
overlap[i][j] = overlap[j][i] = T1 + T2
overlap = Matrix(overlap)
return overlap
def sympy_dG_dalpha(n_max, delta_r, alpha, x, r_cut):
from sympy.abc import a
n = range(n_max)
S = sympy_basis_overlap(n_max, r_cut)
dS = np.array(S.diff().evalf(subs={a:alpha})).astype(float)
L = scipy.linalg.cholesky(np.array(S).astype(float), lower=True)
L_1 = np.linalg.inv(L)
theta = np.tril(np.dot(np.dot(L_1, dS), L_1.T))
theta[np.diag_indices(3)] *= 0.5
dL_T = -np.dot(theta, L_1).T
Phi = phi_mat(n, delta_r, alpha, x)
dPhi = np.zeros_like(Phi)
for i in range(Phi.shape[0]):
for j in range(Phi.shape[1]):
dPhi[i, j] = -Phi[i, j] * dr_basis_dalpha(n[j], delta_r, alpha, x[i])
dG_dalpha = np.dot(dPhi.T, L_1.T).T + np.dot(Phi.T, dL_T)
return dG_dalpha
def fcut(rcut, rdelta, r):
"""Smooth radial cut-off function with parameters rcut, rdelta."""
if r <= rcut-rdelta:
return 1.
elif r <= rcut:
return 0.5*(1+np.cos(np.pi*(r-rcut+rdelta)/rdelta))
return 0.
def nearest_neighbour_distance(atoms, which=0, largest=False):
"""Nearest neighbor distance between the atoms.
Parameters
----------
atoms : ase.Atoms object
Atoms object where we look for the nearest neighbor distance.
which : int >= 0
Atom with respect to which we look for the NND.
largest : bool, optional
If True, return the maximum NND in the system. This
ensures every atom in the system has at least one neighbor
within a distance nnd.
Returns
-------
nnd : float > 0
NND of atom which or maximum nearest neighbor distance of all atoms.
"""
# Neighbour list of size given by the cell. Always contains some atom
nl = ase.neighborlist.NeighborList([np.min(np.linalg.norm(atoms.cell, axis=1))] * atoms.positions.shape[0],
self_interaction=False)
nl.update(atoms)
if not largest:
# Consider only atom 'which'
ds = []
indices, offsets = nl.get_neighbors(which)
for i, o in zip(indices, offsets):
ds.append(np.linalg.norm(atoms.positions[i] + np.dot(o, atoms.get_cell()) - atoms.positions[which]))
nnd = np.min(ds)
else:
nnds = []
for which in range(atoms.positions.shape[0]):
ds = []
indices, offsets = nl.get_neighbors(which)
for i, o in zip(indices, offsets):
ds.append(np.linalg.norm(atoms.positions[i] + np.dot(o, atoms.get_cell()) - atoms.positions[which]))
nnds.append(np.min(ds))
nnd = np.max(nnds)
return nnd
def iv(n, x):
try:
return sp.spherical_in(n, x)
except:
x += 1.e-15
return sp.iv(n + 0.5, x) * np.sqrt(np.pi / (2 * x))
def exp_iv(y, n, x):
return exp_spherical_in(y, n, x)
def c_ilm(l, m, alpha, ri, thetai, phii, x, derivative=False):
I_01 = 4 * np.pi * exp_iv(-alpha * (x*x + ri*ri), l, 2 * alpha * x * ri) * np.conj(sp.sph_harm(m, l, thetai, phii))
if derivative:
dI_01 = I_01 * (l / alpha - (x*x + ri*ri))
dI_01 += 8 * np.pi * x * ri * exp_iv(-alpha * (x*x + ri*ri), l + 1, 2 * alpha * x * ri) * \
np.conj(sp.sph_harm(m, l, thetai, phii))
if derivative:
return I_01, dI_01
return I_01
def c_ilm2(l, m, alpha, ar2g2, thetai, phii, arg, derivative=False):
I_01 = 4 * np.pi * exp_iv(-ar2g2, l, arg) * np.conj(sp.sph_harm(m, l, thetai, phii))
if derivative:
dI_01 = I_01 * ((l - ar2g2) / alpha)
dI_01 += 4 * np.pi * arg / alpha * exp_iv(-ar2g2, l + 1, arg) * \
np.conj(sp.sph_harm(m, l, thetai, phii))
return I_01, dI_01
return I_01
def get_cnlm(atoms, n_max, l_max, alpha, gr2dr, r_grid, derivative=False, mpi_comm=None):
r"""Calculate the coefficients of the expansion of the pseudo-density
for the given atomic environment.
Parameters
----------
atoms : miniAtoms or ase.Atoms object
Object representing an atomic environment.
n_max : int > 0
Maximum order of the radial expansion.
l_max : int > 0
Maximum order of the angular expansion.
alpha : float > 0
Precision of the Gaussian representing the atoms.
gr2dr : 2-D np.ndarray of float
Array containing the radial basis functions, one per row,
evaluated at r_grid_points, such that
np.dot(gr2dr[n], v) \approx \int r^2 g_n(r) v(r) dr.
r_grid : 1-D np.ndarray
Radial mesh to evaluate the integrals.
derivative: bool
Whether to return the derivatives with respect to alpha
Returns
-------
c_nlm : 1-D ndarray of complex float
Contains the flattened array :math:`c_{nlm}`.
c_nlm : 1-D ndarray of complex float
Contains the flattened array :math:`\partial c_{nlm}/\partial \alpha`.
"""
parallel = True
mpi_rank = 0
mpi_size = 1
if mpi_comm is None:
parallel = False
else:
mpi_rank = mpi_comm.Get_rank()
mpi_size = mpi_comm.Get_size()
from mpi4py import MPI
c_nlm = np.zeros(n_max * l_max * l_max, dtype=complex)
if derivative:
dc_nlm = np.zeros(n_max * l_max * l_max, dtype=complex)
r_cartesian = np.copy(atoms.positions)
r, theta, phi = cart2sph(r_cartesian)
r_grid2 = r_grid * r_grid
ar2g2 = np.empty((r.shape[0], r_grid2.shape[0]))
arg = np.empty((r.shape[0], r_grid2.shape[0]))
for a in range(r.shape[0]):
ar2g2[a] = alpha * (r[a] * r[a] + r_grid2)
arg[a] = 2. * alpha * r[a] * r_grid
I_all = np.zeros((sum_odd_integers(l_max - 1) * r.shape[0], r_grid.shape[0]), dtype=complex)
dI_all = np.zeros((sum_odd_integers(l_max - 1) * r.shape[0], r_grid.shape[0]), dtype=complex)
lchunk, chunksizes, offsets = partition1d(I_all.shape[0], mpi_rank, mpi_size)
if parallel:
I_local = np.zeros((chunksizes[mpi_rank], r_grid.shape[0]), dtype=complex)
dI_local = np.zeros((chunksizes[mpi_rank], r_grid.shape[0]), dtype=complex)
else:
I_local = I_all
dI_local = dI_all
for idx in range(lchunk[0], lchunk[1]):
l = int(np.sqrt(idx /r.shape[0]))
m = idx /r.shape[0] - l**2
a = idx % r.shape[0]
if derivative:
I_local[idx - offsets[mpi_rank]], dI_local[idx - offsets[mpi_rank]] = \
c_ilm2(l, m - l, alpha, ar2g2[a], theta[a], phi[a], arg[a], derivative)
else:
I_local[idx - offsets[mpi_rank]] = c_ilm2(l, m - l, alpha, ar2g2[a], theta[a], phi[a], arg[a])
if parallel:
mpi_comm.Allgatherv(I_local.ravel(),
[I_all.ravel(), chunksizes * r_grid.shape[0],
offsets * r_grid.shape[0], MPI.DOUBLE_COMPLEX])
if derivative:
mpi_comm.Allgatherv(dI_local.ravel(),
[dI_all.ravel(), chunksizes * r_grid.shape[0],
offsets * r_grid.shape[0], MPI.DOUBLE_COMPLEX])
if parallel:
lchunk, chunksizes, offsets = partition1d(n_max * l_max * l_max, mpi_rank, mpi_size)
for idx in range(lchunk[0], lchunk[1]):
n = idx / (l_max * l_max)
nidx = idx % (l_max * l_max)
l = int(np.sqrt(nidx))
m = nidx - (l * (l + 1))
for a in range(r.shape[0]):
c_nlm[idx] += np.dot(gr2dr[n], I_all[(l**2 + m + l) * r.shape[0] + a])
if derivative:
dc_nlm[idx] += np.dot(gr2dr[n], dI_all[(l**2 + m + l) * r.shape[0] + a])
mpi_comm.Allgatherv(c_nlm[lchunk[0]: lchunk[1]],
[c_nlm, chunksizes, offsets, MPI.DOUBLE_COMPLEX])
if derivative:
mpi_comm.Allgatherv(dc_nlm[lchunk[0]: lchunk[1]],
[dc_nlm, chunksizes, offsets, MPI.DOUBLE_COMPLEX])
else:
for a, n, l in itertools.product(range(r.shape[0]), range(n_max), range(l_max)):
for m in range(-l, l + 1):
idx = n * l_max * l_max + l * l + (m + l)
c_nlm[idx] += np.dot(gr2dr[n], I_all[(l ** 2 + m + l) * r.shape[0] + a])
if derivative:
dc_nlm[idx] += np.dot(gr2dr[n], dI_all[(l ** 2 + m + l) * r.shape[0] + a])
if derivative:
return c_nlm, dc_nlm
return c_nlm
def get_dcnlm_dalpha(atoms, n_max, l_max, alpha, gr2dr, r_grid, derivative=False, mpi_comm=None):
r"""Calculate the derivative of the coefficients of the expansion of the pseudo-density
for the given atomic environment.
Parameters
----------
atoms : miniAtoms or ase.Atoms object
Object representing an atomic environment.
n_max : int > 0
Maximum order of the radial expansion.
l_max : int > 0
Maximum order of the angular expansion.
alpha : float > 0
Precision of the Gaussian representing the atoms.
gr2dr : 2-D np.ndarray of float
Array containing the radial basis functions, one per row,
evaluated at r_grid_points, such that
np.dot(gr2dr[n], v) \approx \int r^2 g_n(r) v(r) dr.
r_grid : 1-D np.ndarray
Radial mesh to evaluate the integrals.
derivative: bool
Whether to return the derivatives with respect to alpha
Returns
-------
c_nlm : 1-D ndarray of complex float
Contains the flattened array :math:`c_{nlm}`.
c_nlm : 1-D ndarray of complex float
Contains the flattened array :math:`\partial c_{nlm}/\partial \alpha`.
"""
parallel = True
mpi_rank = 0
mpi_size = 1
if mpi_comm is None:
parallel = False
else:
mpi_rank = mpi_comm.Get_rank()
mpi_size = mpi_comm.Get_size()
from mpi4py import MPI
dc_nlm = np.zeros(n_max * l_max * l_max, dtype=complex)
r_cartesian = np.copy(atoms.positions)
r, theta, phi = cart2sph(r_cartesian)
r_grid2 = r_grid * r_grid
ar2g2 = np.empty((r.shape[0], r_grid2.shape[0]))
arg = np.empty((r.shape[0], r_grid2.shape[0]))
for a in range(r.shape[0]):
ar2g2[a] = alpha * (r[a] * r[a] + r_grid2)
arg[a] = 2. * alpha * r[a] * r_grid
dI_all = np.zeros((sum_odd_integers(l_max - 1) * r.shape[0], r_grid.shape[0]), dtype=complex)
lchunk, chunksizes, offsets = partition1d(I_all.shape[0], mpi_rank, mpi_size)
if parallel:
dI_local = np.zeros((chunksizes[mpi_rank], r_grid.shape[0]), dtype=complex)
else:
dI_local = dI_all
for idx in range(lchunk[0], lchunk[1]):
l = int(np.sqrt(idx / r.shape[0]))
m = idx / r.shape[0] - l ** 2
a = idx % r.shape[0]
_, dI_local[idx - offsets[mpi_rank]] = \
c_ilm2(l, m - l, alpha, ar2g2[a], theta[a], phi[a], arg[a], derivative)
if parallel:
mpi_comm.Allgatherv(dI_local.ravel(),
[dI_all.ravel(), chunksizes * r_grid.shape[0],
offsets * r_grid.shape[0], MPI.DOUBLE_COMPLEX])
if parallel:
lchunk, chunksizes, offsets = partition1d(n_max * l_max * l_max, mpi_rank, mpi_size)
for idx in range(lchunk[0], lchunk[1]):
n = idx / (l_max * l_max)
nidx = idx % (l_max * l_max)
l = int(np.sqrt(nidx))
m = nidx - (l * (l + 1))
for a in range(r.shape[0]):
dc_nlm[idx] += np.dot(gr2dr[n], dI_all[(l ** 2 + m + l) * r.shape[0] + a])
mpi_comm.Allgatherv(dc_nlm[lchunk[0]: lchunk[1]],
[dc_nlm, chunksizes, offsets, MPI.DOUBLE_COMPLEX])
else:
for a, n, l in itertools.product(range(r.shape[0]), range(n_max), range(l_max)):
for m in range(-l, l + 1):
idx = n * l_max * l_max + l * l + (m + l)
dc_nlm[idx] += np.dot(gr2dr[n], dI_all[(l ** 2 + m + l) * r.shape[0] + a])
return dc_nlm
def sum_squares_odd_integers(n):
"""Sum of the squares of the first n odd integers.
"""
return n * (2 * n + 1) * (2 * n - 1) / 3
def sum_odd_integers(n):
"""Sum of the first n odd integers.
"""
return (n + 1)**2
def cart2sph(coords):
"""Change coordinates from cartesian to spherical.
Parameters
----------
coords : 2-D np.ndarray of float > 0
2-D array of shape (N, 3) with the Cartesian coordinates
of the points.
Returns
-------
r, theta, phi : 1-D np.ndarray of float
1-D arrays of shape (N,) with the spherical
coordinates of the points.
"""
r = np.linalg.norm(coords, axis=1)
coords_hat = np.zeros_like(coords)
theta = np.zeros(r.shape[0])
phi = np.zeros_like(theta)
mask = r > 0
coords_hat[mask] = (coords[mask].T / r[mask]).T
theta[mask] = np.arccos(coords_hat[mask, 2])
phi[mask] = np.arctan2(coords[mask, 1], coords[mask, 0])
return r, theta, phi
def sph2cart(r, theta, phi):
"""Change coordinates from spherical to cartesian.
Parameters
----------
r : 1-D np.ndarray of float > 0
1-D array of shape (N,) with radial coordinates.
theta : 1-D np.ndarray of float
phi : 1-D np.ndarray of float
Returns
-------
x, y, z : 1-D np.ndarray of float
Cartesian coordinates of the points.
"""
rsin_theta = r * np.sin(theta)
x = rsin_theta * np.cos(phi)
y = rsin_theta * np.sin(phi)
z = r * np.cos(theta)
return x, y, z
def dirac_delta(i, j):
"""Dirac delta symbol between i and j.
Parameters
----------
i
Object to be compared with j.
j
Object to be compared with i.
Returns
-------
int {0, 1}
1 if i==j and 0 otherwise.
Notes
-----
The only condition to use the function is that
the operator `==` must be defined between i and j.
"""
if i == j:
return 1
return 0
def partition1d(ndata, rank, size):
"""Partitions a 1D array of size ndata between size processes.
Parameters
----------
ndata : int > 0
Number of elements of the array.
rank : int >=0
Rank (id) of the process.
size : int >=0
Number of processes.
Returns
-------
lchunk : list of 2 int
Indices (first and one past last) of the chunk for process rank.
chunksizes : 1-D ndarray of int
Size (in rows) of all the chunks.
offsets : 1-D ndarray of int
Offsets (in rows) of all the chunks.
"""
base = ndata / size
leftover = ndata % size
chunksizes = np.ones(size, dtype=int) * base
chunksizes[:leftover] += 1
offsets = np.zeros(size, dtype=int)
offsets[1:] = np.cumsum(chunksizes)[:-1]
# Local update
lchunk = [offsets[rank], offsets[rank] + chunksizes[rank]]
return lchunk, chunksizes, offsets
def partition1d_weights(weights, rank, size):
"""Partition of a 1D array into sets of similar weight sum.
Parameters
----------
weights : np.ndarray
Array with the weight for each elements of the array
to be partitioned.
rank : int >=0
Rank (id) of the process.
size : int >=0
Number of processes.
Returns
-------
: 1-D ndarray
Array with the indices of the elements of the local partition.
"""
partition_i = [[] for i in range(size)]
partition_w = [[] for i in range(size)]
idx_sorted = np.argsort(np.asarray(weights))
for i_w in idx_sorted[::-1]:
sums = [sum(group) for group in partition_w]
w_i = weights[i_w]
group = np.argmin(np.asarray(sums))
partition_i[group].append(i_w)
partition_w[group].append(w_i)
return np.array(sorted(partition_i[rank], key=int))
def partition1d_weights_chunked(weights, rank, size):
"""Partition of a 1D array into sets of similar weight sum.
The partition is constrained to use contiguous chunks
of the original array.
Parameters
----------
weights : np.ndarray
Array with the weight for each elements of the array
to be partitioned.
rank : int >=0
Rank (id) of the process.
size : int >=0
Number of processes.
Returns
-------
lchunk : list of 2 int
Indices (first and one past last) of the chunk for process rank.
chunksizes : 1-D ndarray of int
Size (in rows) of all the chunks.
offsets : 1-D ndarray of int
Offsets (in rows) of all the chunks.
"""
if len(weights) < size:
chunks = [[0, 0] for i in range(size)]
for i in range(len(weights)):
chunks[i] = [i, i + 1]
chunksizes = [chunk[1] - chunk[0] for chunk in chunks]
offsets = [chunk[0] for chunk in chunks]
return chunks[rank], np.array(chunksizes), np.array(offsets)
lweight = sum(weights) / size
# remainder = sum(weights) % size
lweights = lweight * np.ones(size)
# lweights[:remainder] += 1
partition_w = [[] for i in range(size)]
chunks = [[] for i in range(size)]
group = 0
chunks[0].append(0)
for i_w, w_i in enumerate(weights):
partition_w[group].append(w_i)
lsum = sum(partition_w[group])
if lsum >= lweights[group]:
chunks[group].append(i_w + 1)
group += 1
if group < size:
chunks[group].append(i_w + 1)
else:
break
if len(chunks[-1]) == 1:
chunks[-1].append(i_w + 1)
chunksizes = [chunk[1] - chunk[0] for chunk in chunks]
offsets = [chunk[0] for chunk in chunks]
return chunks[rank], np.array(chunksizes), np.array(offsets)
def partition_ltri_rows(nrows, rank, size):
"""Partitions a matrix assuming the cost of the partitioned
computation depends only on the elements of the lower triangular part.
Parameters
----------
nrows : int > 0
Number of rows of the matrix.
rank : int >=0
Rank (id) of the process.
size : int >=0
Number of processes.
Returns
-------
lchunk : list of 2 int
Indices (first and one past last) of the chunk for process rank.
chunksizes : 1-D ndarray of int
Size (in rows) of all the chunks.
offsets : 1-D ndarray of int
Offsets (in rows) of all the chunks.
Notes
-----
The algorithm only partitions in rows, so a perfect balancing is not possible.
This is motivated by the case where each row represents a data point so that
we just distribute data points.
"""
# TODO: Consider the case where we partition the memory of the 2-D array directly.
ndata = nrows * (nrows + 1) / 2
base = ndata / size
offsets = np.zeros(size, dtype=int)
for i in range(1, size):
inside = False
prev = offsets[i - 1]
for j in range(prev + 1, nrows):
if j * (j + 1) / 2 - prev * (prev + 1) / 2 > base:
offsets[i] = j
inside = True
break
if not inside:
offsets[i] = nrows
print('WARNING: too many processes for the size of the matrix')
chunksizes = np.ones(size, dtype=int)
chunksizes[:-1] = offsets[1:] - offsets[:-1]
chunksizes[-1] = nrows - offsets[-1]
# Local update
lchunk = [offsets[rank], offsets[rank] + chunksizes[rank]]
return lchunk, chunksizes, offsets
def partition_utri_rows(nrows, rank, size):
"""Partitions a matrix assuming the cost of the partitioned
computation depends only on the elements of the upper triangular part.
Parameters
----------
nrows : int > 0
Number of rows of the matrix.
rank : int >=0
Rank (id) of the process.
size : int >=0
Number of processes.
Returns
-------
lchunk : list of 2 int
Indices (first and one past last) of the chunk for process rank.
chunksizes : 1-D ndarray of int
Size (in rows) of all the chunks.
offsets : 1-D ndarray of int
Offsets (in rows) of all the chunks.
Notes
-----
The algorithm only partitions in rows, so a perfect balancing is not possible.
This is motivated by the case where each row represents a data point so that
we just distribute data points.
"""
# TODO: Consider the case where we partition the memory of the 2-D array directly.
ndata = nrows * (nrows + 1) / 2
base = ndata / size
offsets = np.zeros(size, dtype=int)
for i in range(1, size):
prev = offsets[i - 1]
for j in range(0, nrows):
if (j * (nrows - prev) - j * (j - 1) / 2) > base:
offsets[i] = prev + j
break
chunksizes = np.ones(size, dtype=int)
chunksizes[:-1] = offsets[1:] - offsets[:-1]
chunksizes[-1] = nrows - offsets[-1]
# Local update
lchunk = [offsets[rank], offsets[rank] + chunksizes[rank]]
return lchunk, chunksizes, offsets
class miniAtoms(object):
"""Minimal atoms class including only positions
and atomic numbers using the same ase.Atoms interface.
Attributes
----------
numbers : 1-D np.ndarray of int
Atomic numbers of the represented atoms.
positions : 2-D np.ndarray of float
Positions of the represented atoms.
Parameters
----------
atoms : ase.Atoms object, optional
ase.Atoms object to initialize from its positions and atomic numbers.
positions : 2-D np.ndarray of float, optional
Positions of the represented atoms.
numbers : 1-D np.ndarray of int, optional
Atomic numbers of the represented atoms.
"""
def __init__(self, atoms=None, positions=None, numbers=None):
if atoms is not None:
self.positions = np.copy(atoms.positions)
self.numbers = np.copy(atoms.numbers)
elif positions is not None:
assert len(positions.shape) == 2, 'Positions array must be 2-dimensional'
assert positions.shape[1] == 3, 'Each coordinate must be 3-dimensional'
self.positions = np.copy(positions)
if numbers is not None:
self.numbers = np.copy(numbers)
else:
self.numbers = np.array(positions.shape[0]*[-1])
else:
raise NotImplementedError('No initialization for miniAtoms using given inputs implemented')
def get_atomic_numbers(self):
"""Get an array with atomic numbers.
Returns
-------
atomic_numbers : 1-D np.ndarray of int
Array of shape (N,) with atomic numbers.
"""
return self.numbers.copy()
def set_atomic_numbers(self, atomic_numbers):
"""Set atomic numbers to new values. The user is
responsible for keeping positions up to date as well.
Parameters
----------
atomic_numbers : 1-D np.ndarray of int
Array of shape (N,) with atomic numbers.
"""
assert len(atomic_numbers.shape) == 1
self.atomic_numbers = atomic_numbers
def get_positions(self):
"""Get an array with positions.
Returns
-------
positions : 2-D np.ndarray of float
Array of shape (N, 3) with positions.
"""
return self.positions.copy()
def set_positions(self, positions):
"""Set positions to new values. The user is responsible
for keeping atomic numbers up to date as well.
Parameters
----------
positions : 2-D np.ndarray of floats
Array of shape (N, 3) with positions.
"""
assert positions.shape[1] == 3
self.positions = positions
def __eq__(self, other):
"""Check for identity of two miniAtoms objects.
Parameters
----------
other : ase.Atoms or miniAtoms object
Atoms to compare to.
Returns
-------
bool
True if both objects have the same positions
and atomic numbers.
Notes
-----
The comparision od the positions is done directly in float,
no tolerance is allowed.
"""
return (self.positions == other.positions).all() and (self.numbers == other.numbers).all()
def __ne__(self, other):
"""
Parameters
----------
other : ase.Atoms or miniAtoms object
Atoms to compare to.
Returns
-------
bool
False if both objects have the same positions
and atomic numbers.
Notes
-----
The comparision od the positions is done directly in float,
no tolerance is allowed.
"""
return not self.__eq__(other)
def __len__(self):
"""Length of the miniAtoms object, i.e., its number of atoms.
Returns
-------
int > 0
Number of atoms represented by the object.
"""
return self.positions.shape[0]
def __getitem__(self, i):
"""Return a subset of the atoms.
Parameters
----------
i : int >= 0
Index or range of indices to select the subset of atoms.
"""
if isinstance(i, numbers.Integral):
natoms = len(self)
if i < -natoms or i >= natoms:
raise IndexError('Index out of range.')
return miniAtoms(positions=self.positions[i:i+1, :], numbers=self.numbers[i:i+1])
elif isinstance(i, list) and len(i) > 0:
# Make sure a list of booleans will work correctly and not be
# interpreted at 0 and 1 indices.
i = np.array(i)
return miniAtoms(positions=self.positions[i, :], numbers=self.numbers[i, :])
else:
raise IndexError('Invalid index.')
def __delitem__(self, i):
"""Delete a subset of the atoms.
Parameters
----------
i : int >= 0
Index or range of indices to select the subset of atoms.
"""
# li = range(len(self))
if isinstance(i, int):
i = np.array([i])
if isinstance(i, list) and len(i) > 0:
# Make sure a list of booleans will work correctly and not be
# interpreted at 0 and 1 indices.
i = np.array(i)
mask = np.ones(len(self), bool)
mask[i] = False
self.positions = self.positions[mask]
self.numbers = self.numbers[mask]
def __repr__(self):
"""Representation of the object as a string.
"""
tokens = []
tokens.append('positions={}'.format(self.positions))
tokens.append('numbers={}'.format(self.numbers))
return '{}({})'.format(self.__class__.__name__, ', '.join(tokens))
def __str__(self):
"""String with the positions and atomic numbers.
"""
return '{}\n{}'.format(self.positions, self.numbers)
class SOAP(Kern):
r"""Implementation of the SOAP kernel as a GPy kernel as described in [1]_, [2]_.
Attributes
----------
alpha : list of floats > 0
Precision of the Gaussians representing the pseudo-density of
each type of atom.
derivative : bool
Determines if the derivative will be calculated in the next call to
the kernel function K(X, X').
elements : dict materials: list of int
Atomic number of each element for each material.
exponent : int > 0
Exponent for the definition of the kernel.
kernel_times : list of float
Times of each call to the kernel function K(X, X').
l_max : int > 0
Maximum order in the angular expansion of the pseudo-density.
materials : list of str
Path to the folder containing the data of the materials for the model.
mpi_comm : MPI communicator
Communicator to do the parallel processing.
mpi_rank : int >= 0
Id of the process.
mpi_size : int > 0
Number of processes.
n_max : int > 0
Maximum order in the radial expansion of the pseudo-density.
num_diff : bool
Determines if the derivatives are approximated numerically.
optimize_sigma : bool
Determines if the gradient of sigma is calculated for its optimization.
parallel_cnlm : bool
Determines if certain calculations are parallelized.
power_spectrum_times : list of float
Times of each call to get_all_power_spectrum
r_cut : float > 0
Cut-off radius for constructing the atomic neighbourhoods.
r_grid_points : int > 0
Number of grid points for numerical integration in the radial coordinate.
reduction_times_X_X : list of float
Times of the calculation of the similiarity among a single group of
atomic structures given the power spectra.
reduction_times_X_X2 : list of float
Times of the calculation of the similiarity between the atomic structures
of two groups given their power spectra.
sigma : paramz Param
Standard deviation of the Gaussians representing the pseudo-density of
each type of atom.
Parameters
----------
input_dim : int > 0
Dimensionality of the input space.
sigma : iterable of float > 0.
Standard deviation of the Gaussians representing the pseudo-density of
each type of atom.
kappa : iterable of float > 0.
Similarity between different species for which the kernel is used. It
is the flattened upper diagonal of the similarity matrix.
r_cut : float > 0
Cut-off radius for constructing the atomic neighbourhoods.
l_max : int > 0
Maximum order in the angular expansion of the pseudo-density.
n_max : int > 0
Maximum order in the radial expansion of the pseudo-density.