tensorpotential 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. tensorpotential-0.4.0/LICENSE.md +92 -0
  2. tensorpotential-0.4.0/PKG-INFO +17 -0
  3. tensorpotential-0.4.0/README.md +29 -0
  4. tensorpotential-0.4.0/bin/grace_download +40 -0
  5. tensorpotential-0.4.0/bin/gracemaker +26 -0
  6. tensorpotential-0.4.0/setup.cfg +4 -0
  7. tensorpotential-0.4.0/setup.py +28 -0
  8. tensorpotential-0.4.0/tensorpotential/__init__.py +5 -0
  9. tensorpotential-0.4.0/tensorpotential/calculator/__init__.py +4 -0
  10. tensorpotential-0.4.0/tensorpotential/calculator/asecalculator.py +294 -0
  11. tensorpotential-0.4.0/tensorpotential/calculator/foundations_models.py +89 -0
  12. tensorpotential-0.4.0/tensorpotential/cli/__init__.py +0 -0
  13. tensorpotential-0.4.0/tensorpotential/cli/data.py +423 -0
  14. tensorpotential-0.4.0/tensorpotential/cli/gracemaker.py +403 -0
  15. tensorpotential-0.4.0/tensorpotential/cli/prepare.py +275 -0
  16. tensorpotential-0.4.0/tensorpotential/cli/train.py +856 -0
  17. tensorpotential-0.4.0/tensorpotential/compat/__init__.py +0 -0
  18. tensorpotential-0.4.0/tensorpotential/compat/pace/__init__.py +10 -0
  19. tensorpotential-0.4.0/tensorpotential/compat/pace/_version.py +623 -0
  20. tensorpotential-0.4.0/tensorpotential/compat/pace/constants.py +8 -0
  21. tensorpotential-0.4.0/tensorpotential/compat/pace/fit.py +818 -0
  22. tensorpotential-0.4.0/tensorpotential/compat/pace/fitmetrics.py +175 -0
  23. tensorpotential-0.4.0/tensorpotential/compat/pace/functions/__init__.py +3 -0
  24. tensorpotential-0.4.0/tensorpotential/compat/pace/functions/radial_functions.py +118 -0
  25. tensorpotential-0.4.0/tensorpotential/compat/pace/functions/spherical_harmonics.py +226 -0
  26. tensorpotential-0.4.0/tensorpotential/compat/pace/potentials/__init__.py +2 -0
  27. tensorpotential-0.4.0/tensorpotential/compat/pace/potentials/ace.py +1007 -0
  28. tensorpotential-0.4.0/tensorpotential/compat/pace/tensorpot.py +640 -0
  29. tensorpotential-0.4.0/tensorpotential/compat/pace/utils/__init__.py +1 -0
  30. tensorpotential-0.4.0/tensorpotential/compat/pace/utils/neighborlist.py +63 -0
  31. tensorpotential-0.4.0/tensorpotential/compat/pace/utils/symbols.py +118 -0
  32. tensorpotential-0.4.0/tensorpotential/compat/pace/utils/tensorcalc.py +123 -0
  33. tensorpotential-0.4.0/tensorpotential/compat/pace/utils/utilities.py +350 -0
  34. tensorpotential-0.4.0/tensorpotential/constants.py +66 -0
  35. tensorpotential-0.4.0/tensorpotential/data/__init__.py +6 -0
  36. tensorpotential-0.4.0/tensorpotential/data/databuilder.py +819 -0
  37. tensorpotential-0.4.0/tensorpotential/data/process_df.py +473 -0
  38. tensorpotential-0.4.0/tensorpotential/data/symbols.py +120 -0
  39. tensorpotential-0.4.0/tensorpotential/data/tpatoms.py +29 -0
  40. tensorpotential-0.4.0/tensorpotential/data/weighting.py +386 -0
  41. tensorpotential-0.4.0/tensorpotential/export.py +489 -0
  42. tensorpotential-0.4.0/tensorpotential/functions/__init__.py +1 -0
  43. tensorpotential-0.4.0/tensorpotential/functions/couplings.py +876 -0
  44. tensorpotential-0.4.0/tensorpotential/functions/nn.py +117 -0
  45. tensorpotential-0.4.0/tensorpotential/functions/radial.py +251 -0
  46. tensorpotential-0.4.0/tensorpotential/functions/spherical_harmonics.py +286 -0
  47. tensorpotential-0.4.0/tensorpotential/instructions/__init__.py +67 -0
  48. tensorpotential-0.4.0/tensorpotential/instructions/base.py +425 -0
  49. tensorpotential-0.4.0/tensorpotential/instructions/compute.py +2398 -0
  50. tensorpotential-0.4.0/tensorpotential/instructions/output.py +441 -0
  51. tensorpotential-0.4.0/tensorpotential/loss.py +583 -0
  52. tensorpotential-0.4.0/tensorpotential/metrics.py +158 -0
  53. tensorpotential-0.4.0/tensorpotential/potentials/__init__.py +1 -0
  54. tensorpotential-0.4.0/tensorpotential/potentials/presets.py +1091 -0
  55. tensorpotential-0.4.0/tensorpotential/tensorpot.py +487 -0
  56. tensorpotential-0.4.0/tensorpotential/tpmodel.py +386 -0
  57. tensorpotential-0.4.0/tensorpotential/utils.py +301 -0
  58. tensorpotential-0.4.0/tensorpotential.egg-info/PKG-INFO +17 -0
  59. tensorpotential-0.4.0/tensorpotential.egg-info/SOURCES.txt +67 -0
  60. tensorpotential-0.4.0/tensorpotential.egg-info/dependency_links.txt +1 -0
  61. tensorpotential-0.4.0/tensorpotential.egg-info/requires.txt +9 -0
  62. tensorpotential-0.4.0/tensorpotential.egg-info/top_level.txt +1 -0
  63. tensorpotential-0.4.0/tests/test_calculator.py +194 -0
  64. tensorpotential-0.4.0/tests/test_databuilder.py +34 -0
  65. tensorpotential-0.4.0/tests/test_export.py +65 -0
  66. tensorpotential-0.4.0/tests/test_instructions.py +671 -0
  67. tensorpotential-0.4.0/tests/test_integration_test.py +925 -0
  68. tensorpotential-0.4.0/tests/test_presets.py +63 -0
  69. tensorpotential-0.4.0/tests/test_process_df.py +42 -0
@@ -0,0 +1,92 @@
1
+ # Academic Software Licence (“ASL”)
2
+
3
+ ## Preamble
4
+
5
+ ASL is a software license that proposes to offer copyleft style rights to use the software in an academic non-commercial setting. The purpose of ASL is to encourage academic cooperation and collaboration free-of-charge whilst enabling academic institutions to earn revenue from the parallel licensing of valuable bodies of software code. Significant proportions of such revenue are typically reinvested in academic research.
6
+
7
+ ASL is not an open-source licence because it does not allow commercial use – it is an “available source” licence, meaning that the source code is made available subject to the terms of this licence and only for academic non-commercial use.
8
+
9
+ ASL is a reciprocal licence very similar to GPL and the core terms are identical to those of GNU GPLv2 (except for the limitation to non-commercial use), making it easier for those who know the GPLv2 to understand the licensing*. As a reciprocal licence, if you redistribute any derivative works you have created based on ASL licenced code, then you are required to license the new work under the ASL - including making your source code available and ensuring that licensees are aware of the terms of the ASL licence.
10
+
11
+ The non-commercial limitation makes ASL incompatible with the GPL and other open-source licences with copyleft provisions because these licences require that modified versions of the original program are made available free of charge for any type of use, including commercial, and this is prevented by ASL. As the two sets of reciprocal terms are incompatible, any modified version of the original program combining ASL and copylefted open-source code can be used internally but cannot be licensed out.
12
+
13
+ The non-commercial restriction is an integral part of the license and you may not remove it without the consent of the rights holder in the ASL licensed code. Please contact __ACEworks GbmH__ (e-mail: contact@aceworks.works) for any questions and/or to enquire about commercial use rights.
14
+
15
+ *The changes to the GPLv2 are: removing the Preamble, replacing the reference to the “General Public License” in clause 0 with a reference to the “ASL”, removing clause 9 and adding clause 13 with the non-commercial restriction and limited patent grant
16
+
17
+ ## TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
18
+
19
+ 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
20
+
21
+ Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
22
+
23
+ 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
24
+ You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
25
+
26
+ 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
27
+
28
+ a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
29
+
30
+ b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
31
+
32
+ c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
33
+ These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
34
+ Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
35
+ In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
36
+
37
+ 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
38
+
39
+ a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
40
+
41
+ b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
42
+
43
+ c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
44
+ The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
45
+ If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
46
+
47
+ 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
48
+
49
+ 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
50
+
51
+ 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
52
+
53
+ 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
54
+ If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
55
+ It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
56
+ This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
57
+
58
+ 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
59
+
60
+ 9. Not used.
61
+
62
+ 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
63
+
64
+ ### NO WARRANTY
65
+
66
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
67
+
68
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
69
+
70
+ ### Non Commercial Use; Limited Patent Rights Grant
71
+
72
+ 13. The Preamble of the GPLv2 does not apply to this License. The Program is provided to you by the Licensor subject to the following conditions, which prevail over any clause or indication to the contrary in the GPLv2:
73
+
74
+ a) The grant of rights under the License is for academic non-commercial use only. Academic non-commercial use is defined as use for academic research or other not-for-profit scholarly purposes, which are undertaken at an educational, non-profit, charitable or governmental institution, and which does not involve and is not intended to lead to the production or manufacture of products for sale, or the enhancement of a product or service in or proposed for commerce, or the performance of services for a fee.
75
+
76
+ b) Subject to your compliance with the License, in the event the Licensor holds patent rights on the Program or any part of it, the Licensor grants you a perpetual, worldwide, non-exclusive, royalty-free, irrevocable (except as stated in this section), limited patent licence to make, use, import and otherwise run, modify and distribute the Program. For the avoidance of doubt, this patent licence is limited to academic non-commercial use, as described above. If you institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program constitutes direct or contributory patent infringement, then any patent license granted to you under this License for the Program shall terminate as of the date such litigation is filed.
77
+
78
+ Use other than academic and non-commercial use as above is deemed to be commercial use and outside the scope of this License. If you intend to use the Program for a commercial use, then you must obtain a commercial use license for the Program. In that case, please contact the original licensor to enquire about commercial use licenses.
79
+
80
+ ## END OF TERMS AND CONDITIONS
81
+
82
+ ## Appendix: Suggested code header and licensing information
83
+ __gracemaker__ is © 2024, __Ruhr University Bochum__
84
+
85
+ __gracemaker__ is published and distributed under the Academic Software License v1.0 (ASL).
86
+
87
+ __gracemaker__ is distributed in the hope that it will be useful for non-commercial academic research, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ASL for more details.
88
+
89
+ You should have received a copy of the ASL along with this program;
90
+
91
+ You may contact the licensor at __contact@aceworks.works__
92
+
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.1
2
+ Name: tensorpotential
3
+ Version: 0.4.0
4
+ Home-page:
5
+ Author: Anton Bochkarev, Yury Lysogorskiy
6
+ Author-email:
7
+ Requires-Python: <3.12
8
+ License-File: LICENSE.md
9
+ Requires-Dist: scipy
10
+ Requires-Dist: tensorflow<2.17
11
+ Requires-Dist: matscipy
12
+ Requires-Dist: numpy
13
+ Requires-Dist: sympy
14
+ Requires-Dist: pandas<3.0.0
15
+ Requires-Dist: ase
16
+ Requires-Dist: pyyaml>=6.0.2
17
+ Requires-Dist: tqdm
@@ -0,0 +1,29 @@
1
+ # GRACE - GRaph Atomic Cluster Expansion
2
+
3
+ Project GRACEmaker is a heavily modified and in large parts rewritten version of the PACEmaker software geared towards support for multi-component materials and graph architectures.
4
+
5
+ Please see https://github.com/AntBoc/pace-tutorial-2024 for installation instructions and examples.
6
+
7
+ More complete documentation will be available soon.
8
+
9
+ # Reference
10
+ Please see
11
+ * [Anton Bochkarev, Yury Lysogorskiy, and Ralf Drautz Graph Atomic Cluster Expansion for Semilocal Interactions beyond Equivariant Message Passing. Phys. Rev. X 14, 021036 (2024)](https://journals.aps.org/prx/abstract/10.1103/PhysRevX.14.021036)
12
+
13
+ ```bibtex
14
+ @article{PhysRevX.14.021036,
15
+ title = {Graph Atomic Cluster Expansion for Semilocal Interactions beyond Equivariant Message Passing},
16
+ author = {Bochkarev, Anton and Lysogorskiy, Yury and Drautz, Ralf},
17
+ journal = {Phys. Rev. X},
18
+ volume = {14},
19
+ issue = {2},
20
+ pages = {021036},
21
+ numpages = {28},
22
+ year = {2024},
23
+ month = {Jun},
24
+ publisher = {American Physical Society},
25
+ doi = {10.1103/PhysRevX.14.021036},
26
+ url = {https://link.aps.org/doi/10.1103/PhysRevX.14.021036}
27
+ }
28
+
29
+ ```
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env python
2
+ import os
3
+ import sys
4
+ import argparse
5
+
6
+ from tensorpotential.calculator.foundations_models import download_fm, MODELS_NAME_LIST
7
+
8
+
9
+ def build_parser():
10
+ parser = argparse.ArgumentParser(
11
+ prog="grace_download", description="Download foundational models"
12
+ )
13
+
14
+ parser.add_argument(
15
+ "model",
16
+ help=f"Model name ({', '.join(MODELS_NAME_LIST)}). Default is None - all models are downloaded",
17
+ type=str,
18
+ nargs="?",
19
+ default=None,
20
+ )
21
+
22
+ return parser
23
+
24
+
25
+ def main(args):
26
+ parser = build_parser()
27
+ args_parse = parser.parse_args(args)
28
+ model = args_parse.model
29
+ if model is None:
30
+ model_list = MODELS_NAME_LIST
31
+ else:
32
+ model_list = [model]
33
+
34
+ for model in model_list:
35
+ model_path = download_fm(model)
36
+ print(f"{model} -> {model_path}")
37
+
38
+
39
+ if __name__ == "__main__":
40
+ main(sys.argv[1:])
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env python
2
+
3
+ import logging
4
+ import os
5
+ import sys
6
+
7
+ LOG_FMT = "%(asctime)s %(levelname).1s - %(message)s"
8
+ logging.basicConfig(level=logging.INFO, format=LOG_FMT, datefmt="%Y/%m/%d %H:%M:%S")
9
+ log = logging.getLogger()
10
+
11
+ strategy = None
12
+ strategy_desc = ""
13
+ if "TF_CONFIG" in os.environ:
14
+ tf_config = os.environ["TF_CONFIG"]
15
+ log.info(f"TF_CONFIG detected: {tf_config}")
16
+ log.info("Switching to MultiWorker distributed strategy")
17
+
18
+ import tensorflow as tf
19
+
20
+ strategy = tf.distribute.MultiWorkerMirroredStrategy()
21
+ strategy_desc = "Multi Host / Multi GPU"
22
+
23
+ from tensorpotential.cli.gracemaker import main
24
+
25
+ if __name__ == "__main__":
26
+ main(sys.argv[1:], strategy=strategy, strategy_desc=strategy_desc)
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,28 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="tensorpotential",
5
+ version="0.4.0",
6
+ packages=find_packages(include=["tensorpotential", "tensorpotential.*"]),
7
+ url="",
8
+ license="",
9
+ author="Anton Bochkarev, Yury Lysogorskiy",
10
+ author_email="",
11
+ description="",
12
+ python_requires="<3.12",
13
+ install_requires=[
14
+ "scipy",
15
+ "tensorflow<2.17",
16
+ "matscipy",
17
+ "numpy",
18
+ "sympy",
19
+ "pandas<3.0.0",
20
+ "ase",
21
+ "pyyaml>=6.0.2",
22
+ "tqdm",
23
+ ],
24
+ scripts=[
25
+ "bin/gracemaker",
26
+ "bin/grace_download",
27
+ ],
28
+ )
@@ -0,0 +1,5 @@
1
+ from tensorpotential.tensorpot import TensorPotential
2
+ from tensorpotential.tpmodel import TPModel
3
+ from tensorpotential.loss import LossFunction, L2Loss
4
+
5
+ __all__ = ['TensorPotential', 'TPModel', 'LossFunction', 'L2Loss']
@@ -0,0 +1,4 @@
1
+ from tensorpotential.calculator.asecalculator import TPCalculator
2
+ from tensorpotential.calculator.foundations_models import grace_fm
3
+
4
+ __all__ = ["TPCalculator", "grace_fm"]
@@ -0,0 +1,294 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ import numpy as np
5
+ import time
6
+
7
+ from tensorflow.data import Dataset
8
+
9
+ from typing import Any
10
+ from ase.calculators.calculator import Calculator, all_changes
11
+
12
+ from tensorpotential.tensorpot import TensorPotential
13
+ from tensorpotential.tpmodel import extract_cutoff_and_elements, TPModel
14
+ from tensorpotential.data.databuilder import construct_batches, GeometricalDataBuilder
15
+ from tensorpotential import constants
16
+
17
+
18
+ class TPCalculator(Calculator):
19
+ """
20
+ Atomic Simulation Environment (ASE) calculator for TensorPotential models.
21
+
22
+ Args:
23
+ model (Any): The TensorPotential model. This can be:
24
+ - A path to a tf.saved_model file (string).
25
+ - An instance of a TPModel
26
+ cutoff (float, optional): The cutoff radius for potential interactions (default: 5).
27
+ pad_neighbors_fraction (float, optional): Fraction by which to extend
28
+ the neighbor list with fake neighbors (between 0 and 1, for XLA compiled models).
29
+ pad_atoms_number (int, optional): number of fake atoms to pad ( for XLA compiled models)
30
+ **kwargs: Additional keyword arguments passed to the base Calculator class.
31
+ """
32
+
33
+ implemented_properties = ["energy", "forces", "stress", "free_energy"]
34
+
35
+ def __init__(
36
+ self,
37
+ model: list[Any] | Any,
38
+ cutoff: float = None,
39
+ pad_neighbors_fraction: float = None,
40
+ pad_atoms_number: int = None,
41
+ min_dist=None,
42
+ **kwargs,
43
+ ):
44
+ Calculator.__init__(self, **kwargs)
45
+ self.cutoff = cutoff
46
+ # self.model_type = None
47
+ if pad_neighbors_fraction is not None:
48
+ assert (
49
+ 0 < pad_neighbors_fraction <= 1
50
+ ), f"pad_neighbors_fraction must be a fraction between 0 and 1"
51
+ self.pad_neighbors_fraction = pad_neighbors_fraction
52
+ self.current_max_neighbors = None
53
+
54
+ if pad_atoms_number is not None:
55
+ assert 0 < pad_atoms_number, f"pad_atoms_number must be larger than 0"
56
+ assert isinstance(
57
+ pad_atoms_number, int
58
+ ), f"pad_atoms_number must be an integer"
59
+ self.pad_atoms_number = pad_atoms_number
60
+ self.current_max_atoms = None
61
+ if self.pad_atoms_number is not None:
62
+ assert (
63
+ self.pad_neighbors_fraction is not None
64
+ ), f"Padding natoms only is not supported"
65
+
66
+ self.eval_time = 0
67
+ self.basis = None
68
+
69
+ self.min_dist = min_dist # minimal distance
70
+ self.compute_properties = ["energy", "forces", "free_energy", "stress"]
71
+
72
+ assert model is not None, ValueError(f'"model" parameter is not provided')
73
+ self.models = []
74
+ self.data_keys = []
75
+ if isinstance(model, list):
76
+ for modeli in model:
77
+ if isinstance(modeli, str):
78
+ modeli = TensorPotential.load_model(modeli)
79
+ self.models.append(modeli)
80
+ i_data_keys = modeli.signatures["serving_default"]._arg_keywords
81
+ elif hasattr(modeli, "compute"):
82
+ assert callable(modeli.compute)
83
+ self.models.append(modeli)
84
+ i_data_keys = [k for k, v in modeli.compute_specs.items()]
85
+ else:
86
+ raise ValueError(f"model type is not recognized")
87
+ if len(self.data_keys) == 0:
88
+ self.data_keys = i_data_keys
89
+ else:
90
+ assert len(set(self.data_keys).intersection(i_data_keys)) == len(
91
+ self.data_keys
92
+ ), "Models have inconsistent data keys"
93
+ else:
94
+ if isinstance(model, str):
95
+ model = TensorPotential.load_model(model)
96
+ self.data_keys = model.signatures["serving_default"]._arg_keywords
97
+ elif hasattr(model, "compute"):
98
+ assert callable(model.compute)
99
+ self.data_keys = [k for k, v in model.compute_specs.items()]
100
+ else:
101
+ raise ValueError(f"model type is not recognized")
102
+ self.models.append(model)
103
+
104
+ cutoffs, element_maps = [], []
105
+ for model in self.models:
106
+ cutoff, element_map_symbols, element_map_index = (
107
+ extract_cutoff_and_elements(model.instructions)
108
+ )
109
+ cutoffs.append(cutoff)
110
+ element_maps.append(
111
+ {k: v for k, v in zip(element_map_symbols, element_map_index)}
112
+ )
113
+ cutoff = np.max(cutoffs)
114
+ assert all(
115
+ [ems == element_maps[0]] for ems in element_maps
116
+ ) # check that all maps are identical
117
+ self.element_map = element_maps[0]
118
+
119
+ if cutoff > 0:
120
+ if self.cutoff is not None and self.cutoff != cutoff:
121
+ print(
122
+ f"Cutoff of the potential {cutoff} A is different from calculator's {self.cutoff} A. "
123
+ f"Using the value from the potential."
124
+ )
125
+ self.cutoff = cutoff
126
+
127
+ else:
128
+ print(
129
+ f"Couldn't extract cutoff value from the model. Using the value from calculator: {self.cutoff}A"
130
+ )
131
+ self.data_builders = [
132
+ GeometricalDataBuilder(
133
+ elements_map=self.element_map,
134
+ cutoff=self.cutoff,
135
+ )
136
+ ]
137
+ if constants.ATOMIC_MAGMOM in self.data_keys:
138
+ from tensorpotential.experimental.mag.databuilder import MagMomDataBuilder
139
+
140
+ self.data_builders.append(MagMomDataBuilder())
141
+
142
+ def get_data(self, atoms):
143
+ current_symbs = atoms.symbols.species()
144
+ assert all([x in self.element_map for x in current_symbs]), (
145
+ f"This model is configured to process "
146
+ f"the following elements only: {list(self.element_map.keys())}, but the structure "
147
+ f"contains {current_symbs}"
148
+ )
149
+
150
+ if self.pad_neighbors_fraction is not None or self.pad_atoms_number is not None:
151
+ if self.current_max_neighbors is None or self.current_max_atoms is None:
152
+ data, stats = construct_batches(
153
+ [atoms],
154
+ self.data_builders,
155
+ verbose=False,
156
+ batch_size=1,
157
+ max_n_buckets=1,
158
+ return_padding_stats=True,
159
+ gc_collect=False,
160
+ )
161
+ max_nneigh = stats["nreal_neigh"]
162
+ max_at = stats["nreal_atoms"]
163
+
164
+ self.current_max_neighbors = np.ceil(
165
+ max_nneigh + max_nneigh * self.pad_neighbors_fraction
166
+ ).astype(int)
167
+
168
+ if self.pad_atoms_number is not None:
169
+ self.current_max_atoms = int(max_at + self.pad_atoms_number)
170
+ else:
171
+ self.current_max_atoms = max_at
172
+
173
+ # if self.current_max_neighbors is not None or self.current_max_atoms is not None:
174
+ data, stats = construct_batches(
175
+ [atoms],
176
+ self.data_builders,
177
+ verbose=False,
178
+ batch_size=1,
179
+ max_n_buckets=1,
180
+ return_padding_stats=True,
181
+ external_max_nneigh=self.current_max_neighbors,
182
+ external_max_nat=self.current_max_atoms,
183
+ gc_collect=False,
184
+ )
185
+ max_nneigh = stats["nreal_neigh"]
186
+ if max_nneigh > self.current_max_neighbors:
187
+ self.current_max_neighbors = np.ceil(
188
+ max_nneigh + max_nneigh * self.pad_neighbors_fraction
189
+ ).astype(int)
190
+
191
+ max_at = stats["nreal_atoms"]
192
+ if max_at > self.current_max_atoms:
193
+ self.current_max_atoms = np.array(
194
+ max_at + self.pad_atoms_number
195
+ ).astype(int)
196
+ else:
197
+ data = construct_batches(
198
+ [atoms],
199
+ self.data_builders,
200
+ verbose=False,
201
+ batch_size=1,
202
+ max_n_buckets=None,
203
+ gc_collect=False,
204
+ )
205
+
206
+ data = {k: v for k, v in data[0].items() if k in self.data_keys}
207
+ self.current_min_dist = np.min(
208
+ np.linalg.norm(data[constants.BOND_VECTOR], axis=1)
209
+ )
210
+ if self.min_dist is not None and self.current_min_dist < self.min_dist:
211
+ raise RuntimeError(
212
+ f"Minimal bond distance {self.current_min_dist} is smaller than {self.min_dist}"
213
+ )
214
+ self.data = Dataset.from_tensors(data).get_single_element()
215
+
216
+ def calculate(
217
+ self,
218
+ atoms=None,
219
+ properties=["energy", "forces", "stress"],
220
+ system_changes=all_changes,
221
+ ):
222
+ Calculator.calculate(self, atoms, properties, system_changes)
223
+
224
+ self.forces = np.empty((len(atoms), 3))
225
+ self.stress = np.empty((1, 3, 3))
226
+ self.energy = 0.0
227
+ results = {}
228
+
229
+ self.get_data(atoms)
230
+
231
+ t0 = time.perf_counter()
232
+
233
+ outputs = []
234
+ energy_list = []
235
+ forces_list = []
236
+ stress_list = []
237
+ torques_list = []
238
+ n_model = len(self.models)
239
+
240
+ for model in self.models:
241
+ output = model.compute(self.data)
242
+ outputs.append(output)
243
+
244
+ for output in outputs:
245
+ if "energy" in self.compute_properties:
246
+ energy_list.append(output.get(constants.PREDICT_TOTAL_ENERGY).numpy())
247
+
248
+ if "forces" in self.compute_properties:
249
+ forces = output.get(constants.PREDICT_FORCES, None)
250
+ if forces is None:
251
+ forces = np.zeros((len(atoms), 3))
252
+ else:
253
+ forces = forces.numpy()
254
+ forces_list.append(forces)
255
+
256
+ if "stress" in self.compute_properties:
257
+ stress = output.get(constants.PREDICT_VIRIAL, None)
258
+ if stress is None or atoms.get_cell().rank == 0:
259
+ stress = np.zeros((6,))
260
+ else:
261
+ stress = -stress.numpy()[[0, 1, 2, 5, 4, 3]] / atoms.get_volume()
262
+ stress_list.append(stress)
263
+ if "torques" in self.compute_properties:
264
+ from tensorpotential.experimental.mag import constants as constants_mag
265
+
266
+ torques = output.get(constants_mag.PREDICT_TORQUES)
267
+ torques_list.append(torques)
268
+ self.eval_time = time.perf_counter() - t0
269
+
270
+ # energy_list = np.array(energy_list)
271
+ # forces_list = np.array(forces_list)
272
+ # stress_list = np.array(stress_list)
273
+
274
+ self.energy = np.mean(energy_list, axis=0).flatten()[0]
275
+
276
+ # ensure only real atoms have forces
277
+ self.forces = np.mean(forces_list, axis=0)[: len(atoms)]
278
+ self.stress = np.mean(stress_list, axis=0)
279
+
280
+ results["energy"] = self.energy
281
+ results["free_energy"] = results["energy"]
282
+ results["forces"] = self.forces
283
+ results["stress"] = self.stress
284
+
285
+ if "torques" in self.compute_properties:
286
+ self.torques = np.mean(torques_list, axis=0)
287
+ results["torques"] = self.torques
288
+
289
+ if n_model > 1:
290
+ results["energy_std"] = np.std(energy_list, axis=0).flatten()[0]
291
+ results["forces_std"] = np.std(forces_list, axis=0)
292
+ results["stress_std"] = np.std(stress_list, axis=0)
293
+
294
+ self.results = results
@@ -0,0 +1,89 @@
1
+ import os
2
+ import urllib
3
+ import tarfile
4
+ from tensorpotential.calculator.asecalculator import TPCalculator
5
+
6
+ MODELS_METADATA = {
7
+ "mp-1layer": {
8
+ "name": "train_1.5M_test_75_grace_1layer_v2_7Aug2024",
9
+ "url": "https://ruhr-uni-bochum.sciebo.de/s/pS62iMsFZuFrI5K/download",
10
+ },
11
+ "mp-1layer-shift": {
12
+ "url": "https://ruhr-uni-bochum.sciebo.de/s/ElIUhF6EOH5s8oA/download",
13
+ "name": "train_1.5M_test_75_grace_1L_AB_cont_10Aug24",
14
+ },
15
+ "mp-2layer": {
16
+ "url": "https://ruhr-uni-bochum.sciebo.de/s/TSBVN8P6vn0TbGw/download",
17
+ "name": "train_1.5M_test_75_grace_2layer_8Aug2024",
18
+ },
19
+ }
20
+
21
+ MODELS_NAME_LIST = list(MODELS_METADATA.keys())
22
+
23
+
24
+ def grace_fm(
25
+ model: str,
26
+ pad_neighbors_fraction: float = 0.05,
27
+ pad_atoms_number: int = 1,
28
+ min_dist=None,
29
+ ) -> TPCalculator:
30
+
31
+ assert model in MODELS_NAME_LIST, f"model must be in {MODELS_NAME_LIST}"
32
+
33
+ model_path = download_fm(model)
34
+
35
+ calc = TPCalculator(
36
+ model=model_path,
37
+ pad_neighbors_fraction=pad_neighbors_fraction,
38
+ pad_atoms_number=pad_atoms_number,
39
+ min_dist=min_dist,
40
+ )
41
+ return calc
42
+
43
+
44
+ def download_fm(model):
45
+ cache_dir = os.path.expanduser("~/.cache/grace")
46
+ model_path = os.path.join(cache_dir, MODELS_METADATA[model]["name"])
47
+ if not os.path.isdir(model_path):
48
+ # download model
49
+ checkpoint_url = MODELS_METADATA[model]["url"]
50
+ os.makedirs(cache_dir, exist_ok=True)
51
+ # download and save to disk
52
+ print(f"Downloading GRACE models from {checkpoint_url!r}")
53
+ # Define the file path
54
+ filename = os.path.join(cache_dir, "tmp.model.tar.gz")
55
+
56
+ local_filename, http_msg = urllib.request.urlretrieve(checkpoint_url, filename)
57
+ if "Content-Type: text/html" in http_msg:
58
+ raise RuntimeError(
59
+ f"Model download failed, please check the URL {checkpoint_url}"
60
+ )
61
+
62
+ # Unpack the .tar.gz file
63
+ print(f"Unpacking model from {checkpoint_url!r}")
64
+ with tarfile.open(local_filename, "r:gz") as tar:
65
+ tar.extractall(path=cache_dir)
66
+ os.remove(local_filename)
67
+ assert os.path.isdir(model_path), f"Model path {model_path} does not exist"
68
+ print(f"GRACE model downloaded to cache {model_path}")
69
+ else:
70
+ print(f"Using cached GRACE model from {model_path}")
71
+ return model_path
72
+
73
+
74
+ grace_fm.__doc__ = f"""
75
+ model: (str) One of {", ".join(MODELS_NAME_LIST)}
76
+ extend_fake_neighbors_fraction: (float) Fraction of atoms to extend (padding for JIT)
77
+ extend_fake_atoms_number: (int) Number of atoms to extend (padding for JIT)
78
+ min_dist: (float) Minimum distance. Raise exception if atoms are closer
79
+
80
+ Returns: ASE calculator (TPCalculator)
81
+ """
82
+
83
+ download_fm.__doc__ = f"""
84
+ Download foundation model
85
+ model: (str) One of {", ".join(MODELS_NAME_LIST)}
86
+
87
+ Returns:
88
+ model_path: (str)
89
+ """
File without changes