-
Notifications
You must be signed in to change notification settings - Fork 87
/
soap.py
1210 lines (1088 loc) · 49.5 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 -*-
"""Copyright 2019 DScribe developers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from warnings import warn
import numpy as np
from scipy.special import gamma
from scipy.linalg import sqrtm, inv
from ase import Atoms
import ase.geometry.cell
import ase.data
from dscribe.utils.species import get_atomic_numbers
from dscribe.descriptors.descriptorlocal import DescriptorLocal
import dscribe.ext
class SOAP(DescriptorLocal):
"""Class for generating a partial power spectrum from Smooth Overlap of
Atomic Orbitals (SOAP). This implementation uses real (tesseral) spherical
harmonics as the angular basis set and provides two orthonormalized
alternatives for the radial basis functions: spherical primitive gaussian
type orbitals ("gto") or the polynomial basis set ("polynomial").
For reference, see:
"On representing chemical environments, Albert P. Bartók, Risi Kondor, and
Gábor Csányi, Phys. Rev. B 87, 184115, (2013),
https://doi.org/10.1103/PhysRevB.87.184115
"Comparing molecules and solids across structural and alchemical space",
Sandip De, Albert P. Bartók, Gábor Csányi and Michele Ceriotti, Phys.
Chem. Chem. Phys. 18, 13754 (2016), https://doi.org/10.1039/c6cp00415f
"Machine learning hydrogen adsorption on nanoclusters through structural
descriptors", Marc O. J. Jäger, Eiaki V. Morooka, Filippo Federici Canova,
Lauri Himanen & Adam S. Foster, npj Comput. Mater., 4, 37 (2018),
https://doi.org/10.1038/s41524-018-0096-5
"""
def __init__(
self,
r_cut=None,
n_max=None,
l_max=None,
sigma=1.0,
rbf="gto",
weighting=None,
average="off",
compression={"mode": "off", "species_weighting": None},
species=None,
periodic=False,
sparse=False,
dtype="float64",
):
"""
Args:
r_cut (float): A cutoff for local region in angstroms. Should be
bigger than 1 angstrom for the gto-basis.
n_max (int): The number of radial basis functions.
l_max (int): The maximum degree of spherical harmonics.
sigma (float): The standard deviation of the gaussians used to expand the
atomic density.
rbf (str): The radial basis functions to use. The available options are:
* ``"gto"``: Spherical gaussian type orbitals defined as :math:`g_{nl}(r) = \sum_{n'=1}^{n_\mathrm{max}}\,\\beta_{nn'l} r^l e^{-\\alpha_{n'l}r^2}`
* ``"polynomial"``: Polynomial basis defined as :math:`g_{n}(r) = \sum_{n'=1}^{n_\mathrm{max}}\,\\beta_{nn'} (r-r_\mathrm{cut})^{n'+2}`
weighting (dict): Contains the options which control the
weighting of the atomic density. Leave unspecified if
you do not wish to apply any weighting. The dictionary may
contain the following entries:
* ``"function"``: The weighting function to use. The
following are currently supported:
* ``"poly"``: :math:`w(r) = \left\{ \\begin{array}{ll} c(1 + 2 (\\frac{r}{r_0})^{3} -3 (\\frac{r}{r_0})^{2}))^{m}, \\ \\text{for}\\ r \\leq r_0\\\\ 0, \\ \\text{for}\\ r > r_0 \end{array}\\right.`
This function goes exactly to zero at :math:`r=r_0`. If
you do not explicitly provide ``r_cut`` in the
constructor, ``r_cut`` is automatically set to ``r0``.
You can provide the parameters ``c``, ``m`` and ``r0`` as
additional dictionary items.
For reference see:
"Caro, M. (2019). Optimizing many-body atomic
descriptors for enhanced computational performance of
machine learning based interatomic potentials. Phys.
Rev. B, 100, 024112."
* ``"pow"``: :math:`w(r) = \\frac{c}{d + (\\frac{r}{r_0})^{m}}`
If you do not explicitly provide ``r_cut`` in the
constructor, ``r_cut`` will be set as the value at which
this function decays to the value given by the
``threshold`` entry in the weighting dictionary (defaults
to 1e-2), You can provide the parameters ``c``, ``d``,
``m``, ``r0`` and ``threshold`` as additional dictionary
items.
For reference see:
"Willatt, M., Musil, F., & Ceriotti, M. (2018).
Feature optimization for atomistic machine learning
yields a data-driven construction of the periodic
table of the elements. Phys. Chem. Chem. Phys., 20,
29661-29668.
"
* ``"exp"``: :math:`w(r) = \\frac{c}{d + e^{-r/r_0}}`
If you do not explicitly provide ``r_cut`` in the
constructor, ``r_cut`` will be set as the value at which
this function decays to the value given by the
``threshold`` entry in the weighting dictionary (defaults
to 1e-2), You can provide the parameters ``c``, ``d``,
``r0`` and ``threshold`` as additional dictionary items.
* ``"w0"``: Optional weight for atoms that are directly on top
of a requested center. Setting this value to zero essentially
hides the central atoms from the output. If a weighting
function is also specified, this constant will override it
for the central atoms.
average (str): The averaging mode over the centers of interest.
Valid options are:
* ``"off"``: No averaging.
* ``"inner"``: Averaging over sites before summing up the magnetic quantum numbers: :math:`p_{nn'l}^{Z_1,Z_2} \sim \sum_m (\\frac{1}{n} \sum_i c_{nlm}^{i, Z_1})^{*} (\\frac{1}{n} \sum_i c_{n'lm}^{i, Z_2})`
* ``"outer"``: Averaging over the power spectrum of different sites: :math:`p_{nn'l}^{Z_1,Z_2} \sim \\frac{1}{n} \sum_i \sum_m (c_{nlm}^{i, Z_1})^{*} (c_{n'lm}^{i, Z_2})`
compression (dict): Contains the options which specify the feature compression to apply.
Applying compression can slightly reduce the accuracy of models trained on the feature
representation but can also dramatically reduce the size of the feature vector
and hence the computational cost. Options are:
* ``"mode"``: Specifies the type of compression. This can be one of:
* ``"off"``: No compression; default.
* ``"mu2"``: The SOAP feature vector is generated in an element-agnostic way, so that
the size of the feature vector is now independent of the number of elements (see Darby et al.
below for details). It is still possible when using this option to construct a feature
vector that distinguishes between elements by supplying element-specific weighting under
"species_weighting", see below.
* ``"mu1nu1"``: Implements the mu=1, nu=1 feature compression scheme from Darby et al.: :math:`p_{inn'l}^{Z_1,Z_2} \sum_m (c_{nlm}^{i, Z_1})^{*} (\sum_z c_{n'lm}^{i, z})`.
In other words, each coefficient for each species is multiplied by a "species-mu2" sum over the corresponding set of coefficients for all other species.
If this option is selected, features are generated for each center, but the number of features (the size of each feature vector) scales linearly rather than
quadratically with the number of elements in the system.
* ``"crossover"``: The power spectrum does not contain cross-species information
and is only run over each unique species Z. In this configuration, the size of
the feature vector scales linearly with the number of elements in the system.
* ``"species_weighting"``: Either ``None`` or a dictionary mapping each species to a
species-specific weight. If None, there is no species-specific weighting. If a dictionary,
must contain a matching key for each species in the ``species`` iterable.
The main use of species weighting is to weight each element differently when using
the "mu2" option for ``compression``.
For reference see:
"Darby, J.P., Kermode, J.R. & Csányi, G.
Compressing local atomic neighbourhood descriptors.
npj Comput Mater 8, 166 (2022). https://doi.org/10.1038/s41524-022-00847-y"
species (iterable): The chemical species as a list of atomic
numbers or as a list of chemical symbols. Notice that this is not
the atomic numbers that are present for an individual system, but
should contain all the elements that are ever going to be
encountered when creating the descriptors for a set of systems.
Keeping the number of chemical species as low as possible is
preferable.
periodic (bool): Set to True if you want the descriptor output to
respect the periodicity of the atomic systems (see the
pbc-parameter in the constructor of ase.Atoms).
sparse (bool): Whether the output should be a sparse matrix or a
dense numpy array.
dtype (str): The data type of the output. Valid options are:
* ``"float32"``: Single precision floating point numbers.
* ``"float64"``: Double precision floating point numbers.
"""
supported_dtype = set(("float32", "float64"))
if dtype not in supported_dtype:
raise ValueError(
"Invalid output data type '{}' given. Please use "
"one of the following: {}".format(dtype, supported_dtype)
)
super().__init__(periodic=periodic, sparse=sparse, dtype=dtype)
# Setup the involved chemical species
self.species = species
# Test that general settings are valid
if sigma <= 0:
raise ValueError(
"Only positive gaussian width parameters 'sigma' are allowed."
)
self._eta = 1 / (2 * sigma**2)
self._sigma = sigma
supported_rbf = {"gto", "polynomial"}
if rbf not in supported_rbf:
raise ValueError(
"Invalid radial basis function of type '{}' given. Please use "
"one of the following: {}".format(rbf, supported_rbf)
)
if n_max < 1:
raise ValueError(
"Must have at least one radial basis function." "n_max={}".format(n_max)
)
supported_average = set(("off", "inner", "outer"))
if average not in supported_average:
raise ValueError(
"Invalid average mode '{}' given. Please use "
"one of the following: {}".format(average, supported_average)
)
if not (weighting or r_cut):
raise ValueError("Either weighting or r_cut need to be defined")
if weighting:
w0 = weighting.get("w0")
if w0 is not None:
if w0 < 0:
raise ValueError("Define w0 > 0 in weighting.")
weighting["w0"] = float(w0)
func = weighting.get("function")
if func is not None:
weighting_functions = {"poly", "pow", "exp"}
if func not in weighting_functions:
raise ValueError(
"Weighting function not implemented. Please choose "
"among one of the following {}".format(weighting_functions)
)
r0 = weighting.get("r0")
if r0 is None or r0 <= 0:
raise ValueError("Define r0 > 0 in weighting.")
weighting["r0"] = float(r0)
c = weighting.get("c")
if c is None or c < 0:
raise ValueError("Define c >= 0 in weighting.")
weighting["c"] = float(c)
if func == "poly":
m = weighting.get("m")
if m is None or m < 0:
raise ValueError("Define m >= 0 in weighting.")
weighting["m"] = float(m)
elif func == "pow":
d = weighting.get("d")
if d is None or d < 0:
raise ValueError("Define d >= 0 in weighting.")
weighting["d"] = float(d)
m = weighting.get("m")
if m is None or m < 0:
raise ValueError("Define m >= 0 in weighting.")
weighting["m"] = float(m)
weighting["threshold"] = float(weighting.get("threshold", 1e-2))
elif func == "exp":
d = weighting.get("d")
if d < 0:
raise ValueError("Define d >= 0 in weighting.")
weighting["d"] = float(d)
weighting["threshold"] = float(weighting.get("threshold", 1e-2))
else:
weighting = {}
if not r_cut:
r_cut = self._infer_r_cut(weighting)
# Test that radial basis set specific settings are valid
if rbf == "gto":
if r_cut <= 1:
raise ValueError(
"When using the gaussian radial basis set (gto), the radial "
"cutoff should be bigger than 1 angstrom."
)
# Precalculate the alpha and beta constants for the GTO basis
self._alphas, self._betas = self.get_basis_gto(r_cut, n_max, l_max)
# Test l_max
if l_max < 0:
raise ValueError("l_max cannot be negative. l_max={}".format(l_max))
elif l_max > 20:
raise ValueError(
"The maximum available l_max for SOAP is currently 20, you have"
" requested l_max={}".format(l_max)
)
self._r_cut = float(r_cut)
self._weighting = weighting
self._n_max = n_max
self._l_max = l_max
self._rbf = rbf
self.average = average
self.compression = compression
def prepare_centers(self, system, centers=None):
"""Validates and prepares the centers for the C++ extension."""
# Check that the system does not have elements that are not in the list
# of atomic numbers
self.check_atomic_numbers(system.get_atomic_numbers())
# Check if periodic is valid
if self.periodic:
cell = system.get_cell()
if np.cross(cell[0], cell[1]).dot(cell[2]) == 0:
raise ValueError("System doesn't have cell to justify periodicity.")
# Setup the local positions
if centers is None:
list_positions = system.get_positions()
indices = np.arange(len(system))
else:
# Check validity of position definitions and create final cartesian
# position list
error = ValueError(
"The argument 'positions' should contain a non-empty "
"one-dimensional list of"
" atomic indices or a two-dimensional "
"list of cartesian coordinates with x, y and z components."
)
if not isinstance(centers, (list, tuple, np.ndarray)) or len(centers) == 0:
raise error
list_positions = []
indices = np.full(len(centers), -1, dtype=np.int64)
for idx, i in enumerate(centers):
if np.issubdtype(type(i), np.integer):
list_positions.append(system.get_positions()[i])
indices[idx] = i
elif isinstance(i, (list, tuple, np.ndarray)):
if len(i) != 3:
raise error
list_positions.append(i)
else:
raise error
return np.asarray(list_positions), indices
def get_cutoff_padding(self):
"""The radial cutoff is extended by adding a padding that depends on
the used used sigma value. The padding is chosen so that the gaussians
decay to the specified threshold value at the cutoff distance.
"""
threshold = 0.001
cutoff_padding = self._sigma * np.sqrt(-2 * np.log(threshold))
return cutoff_padding
def _infer_r_cut(self, weighting):
"""Used to determine an appropriate r_cut based on where the given
weighting function setup.
"""
if weighting["function"] == "pow":
t = weighting["threshold"]
m = weighting["m"]
c = weighting["c"]
d = weighting["d"]
r0 = weighting["r0"]
r_cut = r0 * (c / t - d) ** (1 / m)
return r_cut
elif weighting["function"] == "poly":
r0 = weighting["r0"]
return r0
elif weighting["function"] == "exp":
t = weighting["threshold"]
c = weighting["c"]
d = weighting["d"]
r0 = weighting["r0"]
r_cut = r0 * np.log(c / t - d)
return r_cut
else:
return None
def init_internal_dev_array(self, n_centers, n_atoms, n_types, n, l_max):
d = np.zeros(
(n_atoms, n_centers, n_types, n, (l_max + 1) * (l_max + 1)),
dtype=np.float64,
)
return d
def init_internal_array(self, n_centers, n_types, n, l_max):
d = np.zeros(
(n_centers, n_types, n, (l_max + 1) * (l_max + 1)), dtype=np.float64
)
return d
def create(
self, system, centers=None, n_jobs=1, only_physical_cores=False, verbose=False
):
"""Return the SOAP output for the given systems and given centers.
Args:
system (:class:`ase.Atoms` or list of :class:`ase.Atoms`): One or
many atomic structures.
centers (list): Centers where to calculate SOAP. Can be
provided as cartesian positions or atomic indices. If no
centers are defined, the SOAP output will be created for all
atoms in the system. When calculating SOAP for multiple
systems, provide the centers as a list for each system.
n_jobs (int): Number of parallel jobs to instantiate. Parallellizes
the calculation across samples. Defaults to serial calculation
with n_jobs=1. If a negative number is given, the used cpus
will be calculated with, n_cpus + n_jobs, where n_cpus is the
amount of CPUs as reported by the OS. With only_physical_cores
you can control which types of CPUs are counted in n_cpus.
only_physical_cores (bool): If a negative n_jobs is given,
determines which types of CPUs are used in calculating the
number of jobs. If set to False (default), also virtual CPUs
are counted. If set to True, only physical CPUs are counted.
verbose(bool): Controls whether to print the progress of each job
into to the console.
Returns:
np.ndarray | sparse.COO: The SOAP output for the given systems and
centers. The return type depends on the 'sparse'-attribute. The
first dimension is determined by the amount of centers and
systems and the second dimension is determined by the
get_number_of_features()-function. When multiple systems are
provided the results are ordered by the input order of systems and
their positions.
"""
# Validate input / combine input arguments
if isinstance(system, Atoms):
system = [system]
centers = [centers]
n_samples = len(system)
if centers is None:
inp = [(i_sys,) for i_sys in system]
else:
n_pos = len(centers)
if n_pos != n_samples:
raise ValueError(
"The given number of centers does not match the given "
"number of systems."
)
inp = list(zip(system, centers))
# Determine if the outputs have a fixed size
n_features = self.get_number_of_features()
static_size = None
if self.average != "off":
static_size = [n_features]
else:
if centers is None:
n_centers = len(inp[0][0])
else:
first_sample, first_pos = inp[0]
if first_pos is not None:
n_centers = len(first_pos)
else:
n_centers = len(first_sample)
def is_static():
for i_job in inp:
if centers is None:
if len(i_job[0]) != n_centers:
return False
else:
if i_job[1] is not None:
if len(i_job[1]) != n_centers:
return False
else:
if len(i_job[0]) != n_centers:
return False
return True
if is_static():
static_size = [n_centers, n_features]
# Create in parallel
output = self.create_parallel(
inp,
self.create_single,
n_jobs,
static_size,
only_physical_cores,
verbose=verbose,
)
return output
def create_single(self, system, centers=None):
"""Return the SOAP output for the given system and given centers.
Args:
system (:class:`ase.Atoms` | :class:`.System`): Input system.
centers (list): Cartesian positions or atomic indices. If
specified, the SOAP spectrum will be created for these points.
If no centers are defined, the SOAP output will be created
for all atoms in the system.
Returns:
np.ndarray | sparse.COO: The SOAP output for the
given system and centers. The return type depends on the
'sparse'-attribute. The first dimension is given by the number of
centers and the second dimension is determined by the
get_number_of_features()-function.
"""
cutoff_padding = self.get_cutoff_padding()
centers, _ = self.prepare_centers(system, centers)
n_centers = centers.shape[0]
pos = system.get_positions()
Z = system.get_atomic_numbers()
soap_mat = self.init_descriptor_array(n_centers)
# Determine the function to call based on rbf
if self._rbf == "gto":
# Orthonormalized RBF coefficients
alphas = self._alphas.flatten()
betas = self._betas.flatten()
# Calculate with extension
soap_gto = dscribe.ext.SOAPGTO(
self._r_cut,
self._n_max,
self._l_max,
self._eta,
self._weighting,
self.average,
cutoff_padding,
self._atomic_numbers,
self._species_weights,
self.periodic,
self.compression["mode"],
alphas,
betas,
)
# Calculate analytically with extension
soap_gto.create(
soap_mat,
pos,
Z,
ase.geometry.cell.complete_cell(system.get_cell()),
np.asarray(system.get_pbc(), dtype=bool),
centers,
)
elif self._rbf == "polynomial":
# Get the discretized and orthogonalized polynomial radial basis
# function values
rx, gss = self.get_basis_poly(self._r_cut, self._n_max)
gss = gss.flatten()
# Calculate with extension
soap_poly = dscribe.ext.SOAPPolynomial(
self._r_cut,
self._n_max,
self._l_max,
self._eta,
self._weighting,
self.average,
cutoff_padding,
self._atomic_numbers,
self._species_weights,
self.periodic,
self.compression["mode"],
rx,
gss,
)
soap_poly.create(
soap_mat,
pos,
Z,
ase.geometry.cell.complete_cell(system.get_cell()),
np.asarray(system.get_pbc(), dtype=bool),
centers,
)
# Averaged output is a global descriptor, and thus the first dimension
# is squeezed out to keep the output size consistent with the size of
# other global descriptors.
if self.average != "off":
soap_mat = np.squeeze(soap_mat, axis=0)
return soap_mat
def validate_derivatives_method(self, method, attach):
"""Used to validate and determine the final method for calculating the
derivatives.
"""
methods = {"numerical", "analytical", "auto"}
if method not in methods:
raise ValueError(
"Invalid method specified. Please choose from: {}".format(methods)
)
if method == "numerical":
return method
# Check if analytical derivatives can be used
try:
if self._rbf == "polynomial":
raise ValueError(
"Analytical derivatives currently not available for polynomial "
"radial basis functions."
)
if self.average != "off":
raise ValueError(
"Analytical derivatives currently not available for averaged output."
)
if self.compression["mode"] not in ["off", "crossover"]:
raise ValueError(
"Analytical derivatives not currently available for mu1nu1, mu2 compression."
)
if self.periodic:
raise ValueError(
"Analytical derivatives currently not available for periodic systems."
)
if self._weighting:
raise ValueError(
"Analytical derivatives currently not available when weighting is used."
)
except Exception as e:
if method == "analytical":
raise e
elif method == "auto":
method = "numerical"
else:
if method == "auto":
method = "analytical"
return method
def derivatives_numerical(
self,
d,
c,
system,
centers,
indices,
attach,
return_descriptor=True,
):
"""Return the numerical derivatives for the given system.
Args:
system (:class:`ase.Atoms`): Atomic structure.
indices (list): Indices of atoms for which the derivatives will be
computed for.
return_descriptor (bool): Whether to also calculate the descriptor
in the same function call. This is true by default as it
typically is faster to calculate both in one go.
Returns:
If return_descriptor is True, returns a tuple, where the first item
is the derivative array and the second is the descriptor array.
Otherwise only returns the derivatives array. The derivatives array
is a 3D numpy array. The dimensions are: [n_atoms, 3, n_features].
The first dimension goes over the included atoms. The order is same
as the order of atoms in the given system. The second dimension
goes over the cartesian components, x, y and z. The last dimension
goes over the features in the default order.
"""
pos = system.get_positions()
Z = system.get_atomic_numbers()
cell = ase.geometry.cell.complete_cell(system.get_cell())
pbc = np.asarray(system.get_pbc(), dtype=bool)
cutoff_padding = self.get_cutoff_padding()
centers, center_indices = self.prepare_centers(system, centers)
if self._rbf == "gto":
alphas = self._alphas.flatten()
betas = self._betas.flatten()
soap_gto = dscribe.ext.SOAPGTO(
self._r_cut,
self._n_max,
self._l_max,
self._eta,
self._weighting,
self.average,
cutoff_padding,
self._atomic_numbers,
self._species_weights,
self.periodic,
self.compression["mode"],
alphas,
betas,
)
# Calculate numerically with extension
soap_gto.derivatives_numerical(
d,
c,
pos,
Z,
cell,
pbc,
centers,
center_indices,
indices,
attach,
return_descriptor,
)
elif self._rbf == "polynomial":
rx, gss = self.get_basis_poly(self._r_cut, self._n_max)
gss = gss.flatten()
# Calculate numerically with extension
soap_poly = dscribe.ext.SOAPPolynomial(
self._r_cut,
self._n_max,
self._l_max,
self._eta,
self._weighting,
self.average,
cutoff_padding,
self._atomic_numbers,
self._species_weights,
self.periodic,
self.compression["mode"],
rx,
gss,
)
soap_poly.derivatives_numerical(
d,
c,
pos,
Z,
ase.geometry.cell.complete_cell(system.get_cell()),
np.asarray(system.get_pbc(), dtype=bool),
centers,
center_indices,
indices,
attach,
return_descriptor,
)
def derivatives_analytical(
self,
d,
c,
system,
centers,
indices,
attach,
return_descriptor=True,
):
"""Return the analytical derivatives for the given system.
Args:
system (:class:`ase.Atoms`): Atomic structure.
indices (list): Indices of atoms for which the derivatives will be
computed for.
return_descriptor (bool): Whether to also calculate the descriptor
in the same function call. This is true by default as it
typically is faster to calculate both in one go.
Returns:
If return_descriptor is True, returns a tuple, where the first item
is the derivative array and the second is the descriptor array.
Otherwise only returns the derivatives array. The derivatives array
is a 3D numpy array. The dimensions are: [n_atoms, 3, n_features].
The first dimension goes over the included atoms. The order is same
as the order of atoms in the given system. The second dimension
goes over the cartesian components, x, y and z. The last dimension
goes over the features in the default order.
"""
pos = system.get_positions()
Z = system.get_atomic_numbers()
cell = ase.geometry.cell.complete_cell(system.get_cell())
pbc = np.asarray(system.get_pbc(), dtype=bool)
cutoff_padding = self.get_cutoff_padding()
centers, center_indices = self.prepare_centers(system, centers)
sorted_species = self._atomic_numbers
n_species = len(sorted_species)
n_centers = centers.shape[0]
n_atoms = len(system)
alphas = self._alphas.flatten()
betas = self._betas.flatten()
soap_gto = dscribe.ext.SOAPGTO(
self._r_cut,
self._n_max,
self._l_max,
self._eta,
self._weighting,
self.average,
cutoff_padding,
self._atomic_numbers,
self._species_weights,
self.periodic,
self.compression["mode"],
alphas,
betas,
)
# These arrays are only used internally by the C++ code.
# Allocating them here with python is much faster than
# allocating similarly sized arrays within C++. It seems
# that numpy does some kind of lazy allocation that is
# highly efficient for zero-initialized arrays. Similar
# performace could not be achieved even with calloc.
xd = self.init_internal_dev_array(
n_centers, n_atoms, n_species, self._n_max, self._l_max
)
yd = self.init_internal_dev_array(
n_centers, n_atoms, n_species, self._n_max, self._l_max
)
zd = self.init_internal_dev_array(
n_centers, n_atoms, n_species, self._n_max, self._l_max
)
soap_gto.derivatives_analytical(
d,
c,
xd,
yd,
zd,
pos,
Z,
cell,
pbc,
centers,
center_indices,
indices,
attach,
return_descriptor,
)
@property
def species(self):
return self._species
@species.setter
def species(self, value):
"""Used to check the validity of given atomic numbers and to initialize
the C-memory layout for them.
Args:
value(iterable): Chemical species either as a list of atomic
numbers or list of chemical symbols.
"""
# The species are stored as atomic numbers for internal use.
self._set_species(value)
# Setup mappings between atom indices and types
self.atomic_number_to_index = {}
self.index_to_atomic_number = {}
for i_atom, atomic_number in enumerate(self._atomic_numbers):
self.atomic_number_to_index[atomic_number] = i_atom
self.index_to_atomic_number[i_atom] = atomic_number
self.n_elements = len(self._atomic_numbers)
@property
def compression(self):
return self._compression
@compression.setter
def compression(self, value):
"""Used to check the validity of compression species weighting and set it up.
Note that species must already be set up in order to set species
weighting.
Args:
value(iterable): Chemical species either as a list of atomic
numbers or list of chemical symbols.
"""
# Check mode
supported_modes = set(("off", "mu2", "mu1nu1", "crossover"))
mode = value.get("mode", "off")
if mode not in supported_modes:
raise ValueError(
"Invalid compression mode '{}' given. Please use "
"one of the following: {}".format(mode, supported_modes)
)
# Check species weighting
species_weighting = value.get("species_weighting")
if species_weighting is None:
self._species_weights = np.ones((self.n_elements))
else:
if not isinstance(species_weighting, dict):
raise ValueError(
"Invalid species weighting '{}' given. Species weighting must "
"be either None or a dict.".format(value)
)
if len(species_weighting) != self.n_elements:
raise ValueError(
"The species_weighting dictionary, "
"if supplied, must contain the same keys as "
"the list of accepted species."
)
species_weights = []
for specie in list(self.species):
if specie not in species_weighting:
raise ValueError(
"The species_weighting dictionary, "
"if supplied, must contain the same keys as "
"the list of accepted species."
)
if isinstance(specie, (int, np.integer)):
if specie <= 0:
raise ValueError(
"Species weighting {} contained a zero or negative "
"atomic number.".format(species_weighting)
)
species_weights.append((species_weighting[specie], specie))
else:
species_weights.append(
(species_weighting[specie], ase.data.atomic_numbers.get(specie))
)
species_weights = [
s[0] for s in sorted(species_weights, key=lambda x: x[1])
]
self._species_weights = np.array(species_weights).astype(np.float64)
self._compression = value
def get_number_of_features(self):
"""Used to inquire the final number of features that this descriptor
will have.
Returns:
int: Number of features for this descriptor.
"""
n_elem = len(self._atomic_numbers)
if self.compression["mode"] == "mu2":
return int((self._n_max) * (self._n_max + 1) * (self._l_max + 1) / 2)
elif self.compression["mode"] == "mu1nu1":
return int(self._n_max**2 * n_elem * (self._l_max + 1))
elif self.compression["mode"] == "crossover":
return int(n_elem * self._n_max * (self._n_max + 1) / 2 * (self._l_max + 1))
n_elem_radial = n_elem * self._n_max
return int((n_elem_radial) * (n_elem_radial + 1) / 2 * (self._l_max + 1))
def get_location(self, species):
"""Can be used to query the location of a species combination in the
the flattened output.
Args:
species(tuple): A tuple containing a pair of species as chemical
symbols or atomic numbers. The tuple can be for example ("H", "O").
Returns:
slice: slice containing the location of the specified species
combination. The location is given as a python slice-object, that
can be directly used to target ranges in the output.
Raises:
ValueError: If the requested species combination is not in the
output or if invalid species defined.
"""
# Check that the corresponding part is calculated
if len(species) != 2:
raise ValueError("Please use a pair of atomic numbers or chemical symbols.")
# Change chemical elements into atomic numbers
numbers = []
for specie in species:
if isinstance(specie, str):
try:
specie = ase.data.atomic_numbers[specie]
except KeyError:
raise ValueError("Invalid chemical species: {}".format(specie))
numbers.append(specie)
# See if species defined
for number in numbers:
if number not in self._atomic_number_set:
raise ValueError(
"Atomic number {} was not specified in the species.".format(number)
)
# Change into internal indexing
numbers = [self.atomic_number_to_index[x] for x in numbers]
n_elem = self.n_elements
if numbers[0] > numbers[1]:
numbers = list(reversed(numbers))
i = numbers[0]
j = numbers[1]
if self.compression["mode"] == "off":
n_elem_feat_symm = self._n_max * (self._n_max + 1) / 2 * (self._l_max + 1)
n_elem_feat_unsymm = self._n_max * self._n_max * (self._l_max + 1)
n_elem_feat = n_elem_feat_symm if i == j else n_elem_feat_unsymm
# The diagonal terms are symmetric and off-diagonal terms are
# unsymmetric
m_symm = i + int(j > i)
m_unsymm = j + i * n_elem - i * (i + 1) / 2 - m_symm
start = int(m_symm * n_elem_feat_symm + m_unsymm * n_elem_feat_unsymm)
end = int(start + n_elem_feat)
elif self.compression["mode"] == "mu2":
n_elem_feat_symm = self._n_max * (self._n_max + 1) * (self._l_max + 1) / 2
start = 0
end = int(0 + n_elem_feat_symm)
elif self.compression["mode"] in ["mu1nu1", "crossover"]:
n_elem_feat_symm = self._n_max**2 * (self._l_max + 1)
if self.compression["mode"] == "crossover":
n_elem_feat_symm = (
self._n_max * (self._n_max + 1) * (self._l_max + 1) / 2
)
if i != j: