File: test_castep_interface.py

package info (click to toggle)
python-ase 3.22.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 14,344 kB
  • sloc: python: 126,379; xml: 946; makefile: 111; javascript: 47
file content (350 lines) | stat: -rw-r--r-- 11,273 bytes parent folder | download
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
import os

import pytest
import numpy as np
import ase
import ase.lattice.cubic
from ase.calculators.castep import (Castep, CastepOption,
                                    CastepParam, CastepCell,
                                    make_cell_dict, make_param_dict,
                                    CastepKeywords)

calc = pytest.mark.calculator

# We use 'fake keywords' to test all the generic CastepOptions and
# whether they work
kw_types = ['Real', 'String', 'Defined', 'Integer Vector',
            'Boolean (Logical)', 'Integer', 'Real Vector',
            'Block', 'Physical']
kw_levels = ['Dummy', 'Intermediate', 'Expert', 'Basic']


@pytest.fixture
def testing_keywords():

    kw_data = {}

    for kwt in kw_types:
        kwtlow = kwt.lower().replace(' ', '_')
        if 'Boolean' in kwt:
            kwtlow = 'boolean'
        kw = 'test_{0}_kw'.format(kwtlow)

        kw_data[kw] = {
            'docstring': 'A fake {0} keyword'.format(kwt),
            'option_type': kwt,
            'keyword': kw,
            'level': 'Dummy'
        }

    # Add the special ones for cell and param that have custom parsers

    # Special keywords for the CastepParam object
    param_kws = [('continuation', 'String'), ('reuse', 'String')]

    param_kw_data = {}
    for (pkw, t) in param_kws:
        param_kw_data[pkw] = {
            'docstring': 'Dummy {0} keyword'.format(pkw),
            'option_type': t,
            'keyword': pkw,
            'level': 'Dummy'
        }
    param_kw_data.update(kw_data)

    # Special keywords for the CastepCell object
    cell_kws = [('species_pot', 'Block'),
                ('symmetry_ops', 'Block'),
                ('positions_abs_intermediate', 'Block'),
                ('positions_abs_product', 'Block'),
                ('positions_frac_intermediate', 'Block'),
                ('positions_frac_product', 'Block'),
                ('kpoint_mp_grid', 'Integer Vector'),
                ('kpoint_mp_offset', 'Real Vector'),
                ('kpoint_list', 'Block'),
                ('bs_kpoint_list', 'Block')]

    cell_kw_data = {}
    for (ckw, t) in cell_kws:
        cell_kw_data[ckw] = {
            'docstring': 'Dummy {0} keyword'.format(ckw),
            'option_type': t,
            'keyword': ckw,
            'level': 'Dummy'
        }
    cell_kw_data.update(kw_data)

    param_dict = make_param_dict(param_kw_data)
    cell_dict = make_cell_dict(cell_kw_data)

    return CastepKeywords(param_dict, cell_dict, kw_types, kw_levels,
                          'Castep v.Fake')


@pytest.fixture
def pspot_tmp_path(tmp_path):

    path = os.path.join(tmp_path, 'ppots')
    os.mkdir(path)

    for el in ase.data.chemical_symbols:
        with open(os.path.join(path, '{0}_test.usp'.format(el)), 'w') as fd:
            fd.write('Fake PPOT')

    return path


@pytest.fixture
def testing_calculator(testing_keywords, tmp_path, pspot_tmp_path):
    castep_path = os.path.join(tmp_path, 'CASTEP')
    os.mkdir(castep_path)

    return Castep(castep_keywords=testing_keywords, directory=castep_path,
                  castep_pp_path=pspot_tmp_path)


def test_fundamental_params():
    # Start by testing the fundamental parts of a CastepCell/CastepParam object
    boolOpt = CastepOption('test_bool', 'basic', 'defined')
    boolOpt.value = 'TRUE'
    assert boolOpt.raw_value is True

    float3Opt = CastepOption('test_float3', 'basic', 'real vector')
    float3Opt.value = '1.0 2.0 3.0'
    assert np.isclose(float3Opt.raw_value, [1, 2, 3]).all()

    # Generate a mock keywords object
    mock_castep_keywords = CastepKeywords(make_param_dict(), make_cell_dict(),
                                          [], [], 0)
    mock_cparam = CastepParam(mock_castep_keywords, keyword_tolerance=2)
    mock_ccell = CastepCell(mock_castep_keywords, keyword_tolerance=2)

    # Test special parsers
    mock_cparam.continuation = 'default'
    with pytest.warns(UserWarning):
        mock_cparam.reuse = 'default'
    assert mock_cparam.reuse.value is None

    mock_ccell.species_pot = ('Si', 'Si.usp')
    mock_ccell.species_pot = ('C', 'C.usp')
    assert 'Si Si.usp' in mock_ccell.species_pot.value
    assert 'C C.usp' in mock_ccell.species_pot.value
    symops = (np.eye(3)[None], np.zeros(3)[None])
    mock_ccell.symmetry_ops = symops
    assert """1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
0.0 0.0 0.0""" == mock_ccell.symmetry_ops.value.strip()


def test_castep_option(testing_keywords):

    # check if the CastepOption assignment and comparison mechanisms work
    p1 = CastepParam(testing_keywords)
    p2 = CastepParam(testing_keywords)

    assert p1._options == p2._options

    # Set some values
    p1.test_real_kw = 3.0
    p1.test_string_kw = 'PBE'
    p1.test_defined_kw = True
    p1.test_integer_kw = 10
    p1.test_integer_vector_kw = [3, 3, 3]
    p1.test_real_vector_kw = [3.0, 3.0, 3.0]
    p1.test_boolean_kw = False
    p1.test_physical_kw = '3.0 ang'

    assert p1.test_real_kw.value == '3.0'
    assert p1.test_string_kw.value == 'PBE'
    assert p1.test_defined_kw.value == 'TRUE'
    assert p1.test_integer_kw.value == '10'
    assert p1.test_integer_vector_kw.value == '3 3 3'
    assert p1.test_real_vector_kw.value == '3.0 3.0 3.0'
    assert p1.test_boolean_kw.value == 'FALSE'
    assert p1.test_physical_kw.value == '3.0 ang'

    assert p1._options != p2._options


def test_castep_cell(testing_keywords):

    ccell = CastepCell(testing_keywords, keyword_tolerance=2)

    # Here we test the special keywords exclusive to cell

    # 1. species_pot
    ccell.species_pot = ('H', 'H_test.usp')  # Setting with a single value
    assert ccell.species_pot.value == """
H H_test.usp"""

    ccell.species_pot = [('H', 'H_test.usp'), ('He', 'He_test.usp')]  # Two
    assert ccell.species_pot.value == """
H H_test.usp
He He_test.usp"""

    # 2. symmetry_ops
    # Create for example the P-1 spacegroup
    R = np.array([np.eye(3), -np.eye(3)])
    T = np.zeros((2, 3))
    ccell.symmetry_ops = (R, T)
    strblock = [l.strip() for l in ccell.symmetry_ops.value.split('\n')
                if l.strip() != '']
    fblock = np.array([list(map(float, l.split())) for l in strblock])

    assert np.isclose(fblock[:3], R[0]).all()
    assert np.isclose(fblock[3], T[0]).all()
    assert np.isclose(fblock[4:7], R[1]).all()
    assert np.isclose(fblock[7], T[1]).all()

    # 3. transition state blocks (postponed until fix is merged)
    a = ase.Atoms('H', positions=[[0, 0, 1]], cell=np.eye(3) * 2)

    ccell.positions_abs_product = a
    ccell.positions_abs_intermediate = a

    def parse_posblock(pblock, has_units=False):

        lines = pblock.split('\n')

        units = None
        if has_units:
            units = lines.pop(0).strip()

        pos_lines = []
        while len(lines) > 0:
            l = lines.pop(0).strip()
            if l == '':
                continue
            el, x, y, z = l.split()
            xyz = np.array(list(map(float, [x, y, z])))
            pos_lines.append((el, xyz))

        return units, pos_lines

    pap = parse_posblock(ccell.positions_abs_product.value, True)
    pai = parse_posblock(ccell.positions_abs_intermediate.value, True)

    assert pap[0] == 'ang'
    assert pap[1][0][0] == 'H'
    assert np.isclose(pap[1][0][1], a.get_positions()[0]).all()

    assert pai[0] == 'ang'
    assert pai[1][0][0] == 'H'
    assert np.isclose(pai[1][0][1], a.get_positions()[0]).all()

    ccell.positions_frac_product = a
    ccell.positions_frac_intermediate = a

    pfp = parse_posblock(ccell.positions_frac_product.value)
    pfi = parse_posblock(ccell.positions_frac_intermediate.value)

    assert pfp[1][0][0] == 'H'
    assert np.isclose(pfp[1][0][1], a.get_scaled_positions()[0]).all()

    assert pfi[1][0][0] == 'H'
    assert np.isclose(pfi[1][0][1], a.get_scaled_positions()[0]).all()

    # Test example conflict
    ccell.kpoint_mp_grid = '3 3 3'
    with pytest.warns(UserWarning):
        ccell.kpoint_mp_spacing = 10.0


def test_castep_param(testing_keywords):

    cparam = CastepParam(testing_keywords, keyword_tolerance=2)

    # Special keywords for param

    # 1. continuation and reuse
    cparam.continuation = True
    with pytest.warns(UserWarning):
        cparam.reuse = False   # This conflicts with the previous one
    cparam.continuation = None
    cparam.reuse = True
    with pytest.warns(UserWarning):
        cparam.continuation = True   # This conflicts with the previous one

    # Test conflict
    cparam.cut_off_energy = 500
    with pytest.warns(UserWarning):
        cparam.basis_precision = 'FINE'


def test_workflow(testing_calculator):
    c = testing_calculator
    c._build_missing_pspots = False
    c._find_pspots = True
    c.set_label('test_label_pspots')

    atoms = ase.build.bulk('Ag')
    atoms.calc = c

    # Should find them automatically!
    c._fetch_pspots()

    assert os.path.isfile(os.path.join(c._directory, 'Ag_test.usp'))

    # Try creating input files
    c.prepare_input_files()

    assert os.path.isfile(os.path.join(c._directory, c._label + '.cell'))
    assert os.path.isfile(os.path.join(c._directory, c._label + '.param'))


def test_set_kpoints(testing_calculator):

    c = testing_calculator

    c.set_kpts([(0.0, 0.0, 0.0, 1.0)])
    assert c.cell.kpoint_list.value == '0.0 0.0 0.0 1.0'
    c.set_kpts(((0.0, 0.0, 0.0, 0.25), (0.25, 0.25, 0.3, 0.75)))
    assert (c.cell.kpoint_list.value ==
            '0.0 0.0 0.0 0.25\n0.25 0.25 0.3 0.75')
    c.set_kpts(c.cell.kpoint_list.value.split('\n'))
    assert (c.cell.kpoint_list.value ==
            '0.0 0.0 0.0 0.25\n0.25 0.25 0.3 0.75')
    c.set_kpts([3, 3, 2])
    assert c.cell.kpoint_mp_grid.value == '3 3 2'
    c.set_kpts(None)
    assert c.cell.kpoints_list.value is None
    assert c.cell.kpoint_list.value is None
    assert c.cell.kpoint_mp_grid.value is None
    c.set_kpts('2 2 3')
    assert c.cell.kpoint_mp_grid.value == '2 2 3'
    c.set_kpts({'even': True, 'gamma': True})
    assert c.cell.kpoint_mp_grid.value == '2 2 2'
    assert c.cell.kpoint_mp_offset.value == '0.25 0.25 0.25'
    c.set_kpts({'size': (2, 2, 4), 'even': False})
    assert c.cell.kpoint_mp_grid.value == '3 3 5'
    assert c.cell.kpoint_mp_offset.value == '0.0 0.0 0.0'
    atoms = ase.build.bulk('Ag')
    atoms.calc = c
    c.set_kpts({'density': 10, 'gamma': False, 'even': None})
    assert c.cell.kpoint_mp_grid.value == '27 27 27'
    assert c.cell.kpoint_mp_offset.value == '0.018519 0.018519 0.018519'
    c.set_kpts({'spacing': (1 / (np.pi * 10)),
                'gamma': False, 'even': True})
    assert c.cell.kpoint_mp_grid.value == '28 28 28'
    assert c.cell.kpoint_mp_offset.value == '0.0 0.0 0.0'


def test_band_structure_setup(testing_calculator):

    c = testing_calculator

    from ase.dft.kpoints import BandPath

    atoms = ase.build.bulk('Ag')
    bp = BandPath(cell=atoms.cell,
                  path='GX',
                  special_points={'G': [0, 0, 0], 'X': [0.5, 0, 0.5]})
    bp = bp.interpolate(npoints=10)

    c.set_bandpath(bp)

    kpt_list = c.cell.bs_kpoint_list.value.split('\n')
    assert len(kpt_list) == 10
    assert list(map(float, kpt_list[0].split())) == [0., 0., 0.]
    assert list(map(float, kpt_list[-1].split())) == [0.5, 0.0, 0.5]