├── MANIFEST.in ├── examples └── 00-hf_with_dftd3.py ├── .gitignore ├── README.md ├── pyscf └── dftd3 │ ├── __init__.py │ ├── test │ └── test_dftd3.py │ └── itrf.py ├── setup.py └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include MANIFEST.in 2 | include README.md setup.py CHANGELOG LICENSE 3 | 4 | prune pyscf/lib/build pyscf/build 5 | 6 | recursive-include pyscf *.dat *.so *.dylib 7 | recursive-exclude pyscf *.c *.h 8 | -------------------------------------------------------------------------------- /examples/00-hf_with_dftd3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Author: Qiming Sun 4 | # 5 | 6 | ''' 7 | A simple example of using solvent model in the mean-field calculations. 8 | ''' 9 | 10 | from pyscf import gto 11 | from pyscf import scf 12 | import dftd3.pyscf as d3 13 | 14 | mol = gto.Mole() 15 | mol.atom = ''' O 0.00000000 0.00000000 -0.11081188 16 | H -0.00000000 -0.84695236 0.59109389 17 | H -0.00000000 0.89830571 0.52404783 ''' 18 | mol.basis = 'cc-pvdz' 19 | mol.build() 20 | 21 | mf = d3.energy(scf.RHF(mol)) 22 | print(mf.kernel()) # -75.99396273778923 23 | 24 | mf.Gradients() 25 | mf.kernel() 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | *.dylib 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | bin/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | eggs/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | libdftd3/ 25 | 26 | # Local log files 27 | *~ 28 | 29 | # Calculation examples 30 | *.molden 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .cache 41 | nosetests.xml 42 | coverage.xml 43 | 44 | # Translations 45 | *.mo 46 | 47 | # Mr Developer 48 | .mr.developer.cfg 49 | .project 50 | .pydevproject 51 | 52 | # Rope 53 | .ropeproject 54 | 55 | # Django stuff: 56 | *.log 57 | *.pot 58 | 59 | CMakeCache.txt 60 | CMakeFiles 61 | Makefile 62 | cmake_install.cmake 63 | pyscf/lib/deps 64 | pyscf/lib/config.h 65 | 66 | settings.py 67 | 68 | # Memoization and caching 69 | tmp/ 70 | 71 | # IDEs 72 | .idea/ 73 | .vscode/ 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | DFT-D3 interface 2 | ================ 3 | 4 | pyscf-dftd3 extension is deprecated. It is recommended to use the newest DFTD3 5 | and DFTD4 interfaces hosted at https://github.com/dftd3/simple-dftd3 and 6 | https://github.com/dftd4/dftd4 . They can be installed via pypi packages 7 | 8 | ``` 9 | pip install dftd3 dftd4 10 | ``` 11 | 12 | dftd3 package provides a drop-in replacement of pyscf.dftd3.itrf. For example 13 | 14 | ``` 15 | from pyscf import gto 16 | import dftd3.pyscf as d3 17 | 18 | mol = gto.M( 19 | atom = ''' O 0.00000000 0.00000000 -0.11081188 20 | H -0.00000000 -0.84695236 0.59109389 21 | H -0.00000000 0.89830571 0.52404783 ''', 22 | basis = 'cc-pvdz') 23 | 24 | mf = d3.energy(mol.RHF()) 25 | print(mf.kernel()) 26 | 27 | mf.Gradients() 28 | mf.kernel() 29 | ``` 30 | 31 | See also discussions in https://github.com/pyscf/dftd3/issues/3 32 | and the instructions for dftd3 33 | https://dftd3.readthedocs.io/en/latest/api/pyscf.html 34 | and dftd4 35 | https://dftd4.readthedocs.io/en/latest/reference/pyscf.html 36 | -------------------------------------------------------------------------------- /pyscf/dftd3/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # Author: Qiming Sun 17 | # 18 | 19 | __version__ = '0.0.2' 20 | 21 | import warnings 22 | 23 | warnings.warn(''' 24 | pyscf-dftd3 extension is deprecated. It is recommended to use the newest DFTD3 25 | and DFTD4 interfaces hosted at https://github.com/dftd3/simple-dftd3 and 26 | https://github.com/dftd4/dftd4 . They can be installed via pypi packages 27 | 28 | pip install dftd3 dftd4 29 | 30 | See also discussions in https://github.com/pyscf/dftd3/issues/3 31 | ''') 32 | -------------------------------------------------------------------------------- /pyscf/dftd3/test/test_dftd3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import unittest 17 | from pyscf import lib 18 | from pyscf import gto, scf 19 | 20 | try: 21 | from pyscf.dftd3 import dftd3 22 | from pyscf.dftd3 import itrf 23 | except ImportError: 24 | dftd3 = False 25 | 26 | 27 | @unittest.skipIf(not dftd3, "library dftd3 not found.") 28 | class KnownValues(unittest.TestCase): 29 | 30 | @classmethod 31 | def setUpClass(cls): 32 | 33 | cls._h2o = gto.M(atom=''' 34 | O 0. 0. 0. 35 | H 0. -0.757 0.587 36 | H 0. 0.757 0.587 37 | ''', symmetry=True) 38 | 39 | cls._ch4 = gto.M(atom=''' 40 | H 0.000000000000 0.000000000000 0.000000000000 41 | C 0.000000000000 0.000000000000 1.087900000000 42 | H 1.025681956337 0.000000000000 1.450533333333 43 | H -0.512840978169 0.888266630391 1.450533333333 44 | H -0.512840978169 -0.888266630391 1.450533333333 45 | ''') 46 | 47 | def test_dftd3(self): 48 | d3 = itrf.DFTD3Dispersion(self._ch4) 49 | d3.xc = 'B3LYP' 50 | self.assertAlmostEqual(d3.kernel()[0], -0.0019136221730972761, delta=1.e-12) 51 | 52 | def test_dftd3_scf(self): 53 | mf = dftd3(scf.RHF(self._h2o)) 54 | self.assertAlmostEqual(mf.kernel(), -74.96757204541478, delta=1.e-8) 55 | 56 | def test_dftd3_scf_grad(self): 57 | mf = dftd3(scf.RHF(self._h2o)).run() 58 | mfs = mf.as_scanner() 59 | e1 = mfs(''' O 0. 0. 0.0001; H 0. -0.757 0.587; H 0. 0.757 0.587 ''') 60 | e2 = mfs(''' O 0. 0. -0.0001; H 0. -0.757 0.587; H 0. 0.757 0.587 ''') 61 | ref = (e1 - e2)/0.0002 * lib.param.BOHR 62 | g = mf.nuc_grad_method().kernel() 63 | # DFTD3 does not show high agreement between analytical gradients and 64 | # numerical gradients. not sure whether libdftd3 analytical gradients 65 | # have bug 66 | self.assertAlmostEqual(ref, g[0,2], 5) 67 | 68 | if __name__ == "__main__": 69 | print("Tests for dftd3") 70 | unittest.main() 71 | 72 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2014-2020 The PySCF Developers. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | NAME = 'pyscf-dftd3' 17 | DESCRIPTION = 'DFT-D3 python interface' 18 | SO_EXTENSIONS = { 19 | } 20 | DEPENDENCIES = ['pyscf', 'numpy'] 21 | 22 | ####################################################################### 23 | # Unless not working, nothing below needs to be changed. 24 | metadata = globals() 25 | import os 26 | import sys 27 | from setuptools import setup, find_namespace_packages, Extension 28 | from setuptools.command.build_ext import build_ext 29 | from distutils.errors import DistutilsExecError 30 | 31 | topdir = os.path.abspath(os.path.join(__file__, '..')) 32 | modules = find_namespace_packages(include=['pyscf.*']) 33 | def guess_version(): 34 | for module in modules: 35 | module_path = os.path.join(topdir, *module.split('.')) 36 | for version_file in ['__init__.py', '_version.py']: 37 | version_file = os.path.join(module_path, version_file) 38 | if os.path.exists(version_file): 39 | with open(version_file, 'r') as f: 40 | for line in f.readlines(): 41 | if line.startswith('__version__'): 42 | delim = '"' if '"' in line else "'" 43 | return line.split(delim)[1] 44 | raise ValueError("Version string not found") 45 | if not metadata.get('VERSION', None): 46 | VERSION = guess_version() 47 | 48 | 49 | class CustomBuildExt(build_ext): 50 | def run(self): 51 | commands = ''' 52 | git clone https://github.com/cuanto/libdftd3 53 | make -C libdftd3 54 | mv libdftd3/lib/libdftd3.so pyscf/dftd3/ 55 | ''' 56 | try: 57 | self.spawn(['bash', '-c', commands]) 58 | except DistutilsExecError: 59 | self.warn('Failed to compile dftd3-lib') 60 | raise 61 | 62 | from distutils.command.build import build 63 | build.sub_commands = ([c for c in build.sub_commands if c[0] == 'build_ext'] + 64 | [c for c in build.sub_commands if c[0] != 'build_ext']) 65 | 66 | settings = { 67 | 'name': metadata.get('NAME', None), 68 | 'version': VERSION, 69 | 'description': metadata.get('DESCRIPTION', None), 70 | 'author': metadata.get('AUTHOR', None), 71 | 'author_email': metadata.get('AUTHOR_EMAIL', None), 72 | 'install_requires': metadata.get('DEPENDENCIES', []), 73 | } 74 | setup( 75 | include_package_data=True, 76 | packages=modules, 77 | ext_modules=[Extension('pyscf_lib_placeholder', [])], 78 | cmdclass={'build_ext': CustomBuildExt}, 79 | **settings 80 | ) 81 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /pyscf/dftd3/itrf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2014-2019 The PySCF Developers. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | # Author: Qiming Sun 17 | # 18 | 19 | ''' 20 | DFT-D3 interface. 21 | 22 | This interface is based on the open source project 23 | https://github.com/cuanto/libdftd3 24 | ''' 25 | 26 | import os, sys 27 | import ctypes 28 | import numpy 29 | from pyscf import lib 30 | from pyscf import gto 31 | from pyscf.lib import logger 32 | 33 | libdftd3 = numpy.ctypeslib.load_library('libdftd3', os.path.dirname(__file__)) 34 | 35 | FUNC_CODE = { 36 | # mf.xc name in dftd3 library dftd3 versions 37 | 'BLYP' : ('b-lyp', (2,3,4,5,6)), 38 | 'B88,LYP' : ('b-lyp', (2,3,4,5,6)), 39 | 'BP86' : ('b-p', (2,3,4,5,6)), 40 | 'B88,P86' : ('b-p', (2,3,4,5,6)), 41 | 'B88B95' : ('b1b95', (3,4)), 42 | 'B1B95' : ('b1b95', (3,4)), 43 | 'B3LYP' : ('b3-lyp', (2,3,4,5,6)), 44 | 'B3LYP/631GD' : ('b3-lyp/6-31gd', (4,)), 45 | 'B3LYPG' : ('b3-lyp', (2,3,4,5,6)), 46 | 'B3PW91' : ('b3pw91', (3,4)), 47 | 'B97-D' : ('b97-d', (2,3,4,5,6)), 48 | 'BHANDHLYP' : ('bh-lyp', (3,4)), 49 | 'BMK,BMK' : ('bmk', (3,4)), 50 | 'BOP' : ('bop', (3,4)), 51 | 'B88,OP_B88' : ('bop', (3,4)), 52 | 'BPBE' : ('bpbe', (3,4)), 53 | 'B88,PBE' : ('bpbe', (3,4)), 54 | 'CAMB3LYP' : ('cam-b3lyp', (3,4)), 55 | 'CAM_B3LYP' : ('cam-b3lyp', (3,4)), 56 | #'' : ('dsd-blyp', (2,4)), 57 | #'' : ('dsd-blyp-fc', (4,)), 58 | 'HCTH-120' : ('hcth120', (3,4)), 59 | 'HF' : ('hf', (3,4)), 60 | #'' : ('hf/minis', (4,)), 61 | #'' : ('hf/mixed', (4,)), 62 | 'HF/SV' : ('hf/sv', (4,)), 63 | #'' : ('hf3c', (4,)), 64 | #'' : ('hf3cv', (4,)), 65 | 'HSE06' : ('hse06', (3,4)), 66 | 'HSE_SOL' : ('hsesol', (4,)), 67 | 'LRC-WPBE' : ('lc-wpbe', (3,4,5,6)), 68 | 'LRC-WPBEH' : ('lc-wpbe', (3,4,5,6)), 69 | 'M05' : ('m05', (3,)), 70 | 'M05,M05' : ('m05', (3,)), 71 | 'M05-2X' : ('m052x', (3,)), 72 | 'M06' : ('m06', (3,)), 73 | 'M06,M06' : ('m06', (3,)), 74 | 'M06-2X' : ('m062x', (3,)), 75 | 'M06_HF' : ('m06hf', (3,)), 76 | 'M06-L' : ('m06l', (3,)), 77 | #'' : ('mpw1b95', (3,4)), 78 | #'' : ('mpwb1k', (3,4)), 79 | #'' : ('mpwlyp', (3,4)), 80 | 'OLYP' : ('o-lyp', (3,4)), 81 | 'OPBE' : ('opbe', (3,4)), 82 | 'OTPSS_D' : ('otpss', (3,4)), 83 | 'OTPSS-D' : ('otpss', (3,4)), 84 | 'PBE' : ('pbe', (2,3,4,5,6)), 85 | 'PBE,PBE' : ('pbe', (2,3,4,5,6)), 86 | 'PBE0' : ('pbe0', (2,3,4,5,6)), 87 | 'PBEH' : ('pbe0', (2,3,4,5,6)), 88 | #'' : ('pbeh3c', (4,)), 89 | #'' : ('pbeh-3c', (4,)), 90 | 'PBESOL' : ('pbesol', (3,4)), 91 | #'' : ('ptpss', (3,4)), 92 | #'' : ('pw1pw', (4,)), 93 | #'' : ('pw6b95', (2,3,4)), 94 | #'' : ('pwb6k', (4,)), 95 | #'' : ('pwgga', (4,)), 96 | #'' : ('pwpb95', (3,4)), 97 | 'REVPBE' : ('revpbe', (2,3,4)), 98 | 'REVPBE0' : ('revpbe0', (3,4)), 99 | #'' : ('revpbe38', (3,4)), 100 | #'' : ('revssb', (3,4)), 101 | 'RPBE' : ('rpbe', (3,4)), 102 | 'RPBE,RPBE' : ('rpbe', (3,4)), 103 | 'RPW86,PBE' : ('rpw86-pbe', (3,4)), 104 | 'SLATER' : ('slater-dirac-exchange', (3,)), 105 | 'XALPHA' : ('slater-dirac-exchange', (3,)), 106 | 'SSB,PBE' : ('ssb', (3,4)), 107 | 'TPSS' : ('tpss', (2,3,4)), 108 | 'TPSS0' : ('tpss0', (3,4)), 109 | 'TPSSH' : ('tpssh', (3,4)), 110 | #'' : ('dftb3', (4,)), 111 | } 112 | 113 | 114 | def dftd3(scf_method): 115 | '''Apply DFT-D3 corrections to SCF or MCSCF methods 116 | 117 | Args: 118 | scf_method : a HF or DFT object 119 | 120 | Returns: 121 | Same method object as the input scf_method with DFT-D3 energy 122 | corrections 123 | 124 | Examples: 125 | 126 | >>> mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz', verbose=0) 127 | >>> mf = dftd3(dft.RKS(mol)) 128 | >>> mf.kernel() 129 | -101.940495711284 130 | ''' 131 | from pyscf.scf import hf 132 | from pyscf.mcscf import casci 133 | assert(isinstance(scf_method, hf.SCF) or 134 | isinstance(scf_method, casci.CASCI)) 135 | 136 | # Create the object of dftd3 interface wrapper 137 | with_dftd3 = DFTD3Dispersion(scf_method.mol) 138 | if isinstance(scf_method, casci.CASCI): 139 | with_dftd3.xc = 'hf' 140 | else: 141 | with_dftd3.xc = getattr(scf_method, 'xc', 'HF').upper().replace(' ', '') 142 | 143 | # DFT-D3 has been initialized, avoid to create the derived classes twice. 144 | if isinstance(scf_method, _DFTD3): 145 | scf_method.with_dftd3 = with_dftd3 146 | return scf_method 147 | 148 | method_class = scf_method.__class__ 149 | 150 | # A DFTD3 extension class is defined because other extensions are applied 151 | # based on the dynamic class. If DFT-D3 correction was applied by patching 152 | # the functions of object scf_method, these patches may not be realized by 153 | # other extensions. 154 | class DFTD3(_DFTD3, method_class): 155 | def __init__(self, method, with_dftd3): 156 | self.__dict__.update(method.__dict__) 157 | self.with_dftd3 = with_dftd3 158 | self._keys.update(['with_dftd3']) 159 | 160 | def dump_flags(self, verbose=None): 161 | method_class.dump_flags(self, verbose) 162 | if self.with_dftd3: 163 | self.with_dftd3.dump_flags(verbose) 164 | return self 165 | 166 | def energy_nuc(self): 167 | # Adding DFT D3 correction to nuclear part because it is computed 168 | # based on nuclear coordinates only. It does not depend on 169 | # quantum effects. 170 | enuc = method_class.energy_nuc(self) 171 | if self.with_dftd3: 172 | enuc += self.with_dftd3.kernel()[0] 173 | return enuc 174 | 175 | def reset(self, mol=None): 176 | self.with_dftd3.reset(mol) 177 | return method_class.reset(self, mol) 178 | 179 | def nuc_grad_method(self): 180 | scf_grad = method_class.nuc_grad_method(self) 181 | return grad(scf_grad) 182 | Gradients = lib.alias(nuc_grad_method, alias_name='Gradients') 183 | 184 | return DFTD3(scf_method, with_dftd3) 185 | 186 | def grad(scf_grad): 187 | '''Apply DFT-D3 corrections to SCF or MCSCF nuclear gradients methods 188 | 189 | Args: 190 | scf_grad : a HF or DFT gradient object (grad.HF or grad.RKS etc) 191 | Once this function is applied on the SCF object, it affects all 192 | post-HF calculations eg MP2, CCSD, MCSCF etc 193 | 194 | Returns: 195 | Same gradeints method object as the input scf_grad method 196 | 197 | Examples: 198 | 199 | >>> from pyscf import gto, scf, grad 200 | >>> mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz', verbose=0) 201 | >>> mf = mm_charge(scf.RHF(mol), [(0.5,0.6,0.8)], [-0.3]) 202 | >>> mf.kernel() 203 | -101.940495711284 204 | >>> hfg = mm_charge_grad(grad.hf.RHF(mf), coords, charges) 205 | >>> hfg.kernel() 206 | [[-0.25912357 -0.29235976 -0.38245077] 207 | [-1.70497052 -1.89423883 1.2794798 ]] 208 | ''' 209 | from pyscf.grad import rhf as rhf_grad 210 | assert(isinstance(scf_grad, rhf_grad.Gradients)) 211 | 212 | # Ensure that the zeroth order results include DFTD3 corrections 213 | if not getattr(scf_grad.base, 'with_dftd3', None): 214 | scf_grad.base = dftd3(scf_grad.base) 215 | 216 | grad_class = scf_grad.__class__ 217 | class DFTD3Grad(_DFTD3Grad, grad_class): 218 | def grad_nuc(self, mol=None, atmlst=None): 219 | nuc_g = grad_class.grad_nuc(self, mol, atmlst) 220 | with_dftd3 = getattr(self.base, 'with_dftd3', None) 221 | if with_dftd3: 222 | d3_g = with_dftd3.kernel()[1] 223 | if atmlst is not None: 224 | d3_g = d3_g[atmlst] 225 | nuc_g += d3_g 226 | return nuc_g 227 | mfgrad = DFTD3Grad.__new__(DFTD3Grad) 228 | mfgrad.__dict__.update(scf_grad.__dict__) 229 | return mfgrad 230 | 231 | 232 | class DFTD3Dispersion(lib.StreamObject): 233 | def __init__(self, mol): 234 | self.mol = mol 235 | self.verbose = mol.verbose 236 | self.xc = 'hf' 237 | self.version = 4 # 1..6 238 | self.libdftd3 = libdftd3 239 | self.edisp = None 240 | self.grads = None 241 | 242 | def dump_flags(self, verbose=None): 243 | logger.info(self, '** DFTD3 parameter **') 244 | logger.info(self, 'func %s', self.xc) 245 | logger.info(self, 'version %s', self.version) 246 | return self 247 | 248 | def kernel(self): 249 | mol = self.mol 250 | basis_type = _get_basis_type(mol) 251 | if self.xc in FUNC_CODE: 252 | func, supported_versions = FUNC_CODE[self.xc] 253 | if func == 'b3lyp' and basis_type == '6-31gd': 254 | func, supported_versions = FUNC_CODE['B3LYP/631GD'] 255 | elif func == 'hf' and basis_type == 'sv': 256 | func, supported_versions = FUNC_CODE['HF/SV'] 257 | else: 258 | raise RuntimeError('Functional %s not found' % self.xc) 259 | assert(self.version in supported_versions) 260 | 261 | # dft-d3 has special treatment for def2-TZ basis 262 | tz = (basis_type == 'def2-TZ') 263 | 264 | coords = numpy.asfortranarray(mol.atom_coords()) 265 | nuc_types = [gto.charge(mol.atom_symbol(ia)) 266 | for ia in range(mol.natm)] 267 | nuc_types = numpy.asarray(nuc_types, dtype=numpy.int32) 268 | 269 | edisp = ctypes.c_double(0) 270 | grads = numpy.zeros((mol.natm,3)) 271 | 272 | drv = self.libdftd3.wrapper 273 | drv(ctypes.c_int(mol.natm), 274 | coords.ctypes.data_as(ctypes.c_void_p), 275 | nuc_types.ctypes.data_as(ctypes.c_void_p), 276 | ctypes.c_char_p(func.encode('utf-8')), 277 | ctypes.c_int(self.version), 278 | ctypes.c_int(tz), 279 | ctypes.byref(edisp), 280 | grads.ctypes.data_as(ctypes.c_void_p)) 281 | self.edisp = edisp.value 282 | self.grads = grads 283 | return edisp.value, grads 284 | 285 | def reset(self, mol): 286 | '''Reset mol and clean up relevant attributes for scanner mode''' 287 | self.mol = mol 288 | return self 289 | 290 | class _DFTD3: 291 | pass 292 | 293 | class _DFTD3Grad: 294 | pass 295 | 296 | def _get_basis_type(mol): 297 | def classify(mol_basis): 298 | basis_type = 'other' 299 | if isinstance(mol_basis, str): 300 | mol_basis = gto.basis._format_basis_name(mol_basis) 301 | if mol_basis[:6] == 'def2tz': 302 | basis_type = 'def2-TZ' 303 | elif mol_basis[:6] == 'def2sv': 304 | basis_type = 'sv' 305 | elif mol_basis[:5] == '631g*': 306 | basis_type = '6-31gd' 307 | elif mol_basis[:4] == '631g' and 'd' in mol_basis: 308 | basis_type = '6-31gd' 309 | return basis_type 310 | 311 | if isinstance(mol.basis, dict): 312 | basis_types = [classify(b) for b in mol.basis.values()] 313 | basis_type = 'other' 314 | for bt in basis_types: 315 | if bt != 'other': 316 | basis_type = bt 317 | break 318 | if (len(basis_types) > 1 and 319 | all(b == basis_type for b in basis_types)): 320 | logger.warn(mol, 'Mutliple types of basis found in mol.basis. ' 321 | 'Type %s is applied\n', basis_type) 322 | else: 323 | basis_type = classify(mol.basis) 324 | return basis_type 325 | 326 | 327 | if __name__ == '__main__': 328 | from pyscf import scf 329 | mol = gto.Mole() 330 | mol.atom = ''' O 0.00000000 0.00000000 -0.11081188 331 | H -0.00000000 -0.84695236 0.59109389 332 | H -0.00000000 0.89830571 0.52404783 ''' 333 | mol.basis = 'cc-pvdz' 334 | mol.build() 335 | 336 | mf = dftd3(scf.RHF(mol)) 337 | print(mf.kernel() - -75.99396273778923) 338 | 339 | mfs = mf.as_scanner() 340 | e1 = mfs(''' O 0.00000000 0.00000000 -0.10981188 341 | H -0.00000000 -0.84695236 0.59109389 342 | H -0.00000000 0.89830571 0.52404783 ''') 343 | e2 = mfs(''' O -0.00000000 0.00000000 -0.11181188 344 | H -0.00000000 -0.84695236 0.59109389 345 | H -0.00000000 0.89830571 0.52404783 ''') 346 | g = mf.nuc_grad_method().kernel() 347 | print((e1 - e2)/0.002 * lib.param.BOHR - g[0, 2]) 348 | 349 | --------------------------------------------------------------------------------