File: test_doscollection.py

package info (click to toggle)
python-ase 3.26.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,484 kB
  • sloc: python: 148,112; xml: 2,728; makefile: 110; javascript: 47
file content (412 lines) | stat: -rw-r--r-- 17,180 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
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
# fmt: off
from typing import Iterable

import numpy as np
import pytest

from ase.spectrum.doscollection import (
    DOSCollection,
    GridDOSCollection,
    RawDOSCollection,
)
from ase.spectrum.dosdata import DOSData, GridDOSData, RawDOSData


class MinimalDOSCollection(DOSCollection):
    """Inherit from abstract base class to check its features"""

    def __init__(self, dos_series: Iterable[DOSData]) -> None:
        super().__init__(dos_series)


class YetAnotherDOSCollection(DOSCollection):
    """Inherit from abstract base class to check its features"""

    def __init__(self, dos_series: Iterable[DOSData]) -> None:
        super().__init__(dos_series)


class TestDOSCollection:
    @pytest.fixture()
    def rawdos(self):
        return RawDOSData([1., 2., 4.], [2., 3., 2.],
                          info={'my_key': 'my_value'})

    @pytest.fixture()
    def another_rawdos(self):
        return RawDOSData([3., 2., 5.], [1., 0., 2.],
                          info={'other_key': 'other_value'})

    @pytest.fixture()
    def mindoscollection(self, rawdos, another_rawdos):
        return MinimalDOSCollection([rawdos, another_rawdos])

    @pytest.mark.parametrize('n_entries', [0, 1, 3])
    def test_sequence(self, rawdos, n_entries):
        dc = MinimalDOSCollection([rawdos] * n_entries)
        assert len(dc) == n_entries
        for i in range(n_entries):
            assert dc[i] == rawdos

        with pytest.raises(IndexError):
            dc[n_entries + 1]
        with pytest.raises(TypeError):
            dc['hello']

    linewidths = [1, 5, None]

    @pytest.mark.usefixtures("figure")
    @pytest.mark.parametrize('linewidth', linewidths)
    def test_plot(self, mindoscollection, figure, linewidth):
        npts = 20

        if linewidth is None:
            mplargs = None
        else:
            mplargs = {'linewidth': linewidth}

        ax = figure.add_subplot(111)

        with pytest.warns(UserWarning):  # Default width is small for npts=20
            ax_out = mindoscollection.plot(npts=npts, ax=ax, mplargs=mplargs)
        assert ax_out == ax

        assert ([line.get_label() for line in ax.get_legend().get_lines()]
                == ['my_key: my_value', 'other_key: other_value'])

    def test_slicing(self, rawdos, another_rawdos):
        dc = MinimalDOSCollection([rawdos, another_rawdos, rawdos])
        assert dc[1:]._almost_equals(
            MinimalDOSCollection([another_rawdos, rawdos]))
        assert dc[:-1]._almost_equals(
            MinimalDOSCollection([rawdos, another_rawdos]))

    # It would be much nicer if this test could be done with parameterization,
    # but creating equality_data as a parameter list requires the lazy_fixtures
    # pytest plugin.
    def test_collection_equality(self, rawdos, another_rawdos):
        equality_data = [([], [], True),
                         ([rawdos], [rawdos], True),
                         ([rawdos, another_rawdos],
                          [rawdos, another_rawdos], True),
                         ([], [rawdos], False),
                         ([rawdos], [], False),
                         ([rawdos, another_rawdos], [rawdos], False),
                         ([rawdos, another_rawdos],
                         [another_rawdos, rawdos], False)]

        for series_1, series_2, isequal in equality_data:
            assert (MinimalDOSCollection(series_1)
                    ._almost_equals(MinimalDOSCollection(series_2)) == isequal)

    @pytest.mark.parametrize('other', [True, 1, 0.5, 'string', rawdos])
    def test_equality_wrongtype(self, rawdos, other):
        assert not MinimalDOSCollection([rawdos])._almost_equals(other)

    def test_addition(self, rawdos, another_rawdos):
        dc = MinimalDOSCollection([rawdos])

        double_dc = dc + dc
        assert len(double_dc) == 2
        assert double_dc[0]._almost_equals(rawdos)
        assert double_dc[1]._almost_equals(rawdos)

        assert (dc + MinimalDOSCollection([another_rawdos])
                )._almost_equals(dc + another_rawdos)

        with pytest.raises(TypeError):
            MinimalDOSCollection([rawdos]) + YetAnotherDOSCollection([rawdos])
        with pytest.raises(TypeError):
            MinimalDOSCollection([rawdos]) + 'string'

    @pytest.mark.parametrize('options', [{'energies': [1., 1.1, 1.2],
                                          'width': 1.3,
                                          'smearing': 'Gauss'},
                                         {'energies': [1.7, 2.1, 2.0],
                                          'width': 3.4,
                                          'smearing': 'Gauss'}])
    def test_sample(self, rawdos, another_rawdos, options):
        dc = MinimalDOSCollection([rawdos, another_rawdos])
        sampled_data = dc._sample(**options)
        for i, data in enumerate((rawdos, another_rawdos)):
            # Check consistency with individual DOSData objects
            newdos_weights = data._sample(**options)
            assert np.allclose(sampled_data[i, :], newdos_weights)
            # Check we aren't trivially comparing zeros
            assert np.all(sampled_data)

    sample_grid_options = [{'npts': 10, 'xmin': -2, 'xmax': 10,
                            'padding': 3, 'width': 1},
                           {'npts': 12, 'xmin': 0, 'xmax': 4,
                            'padding': 2.1, 'width': 2.3}]

    @pytest.mark.parametrize('options', sample_grid_options)
    def test_sample_grid(self, rawdos, another_rawdos, options):
        ref_min = min(rawdos.get_energies())
        ref_max = max(another_rawdos.get_energies())

        # Check auto minimum
        dc = MinimalDOSCollection([rawdos, another_rawdos])
        dos = dc.sample_grid(10, xmax=options['xmax'],
                             padding=options['padding'],
                             width=options['width'])
        energies = dos.get_energies()

        assert (pytest.approx(energies[0])
                == ref_min - options['padding'] * options['width'])
        assert pytest.approx(energies[-1]) == options['xmax']

        # Check auto maximum
        dos = dc.sample_grid(10, xmin=options['xmin'],
                             padding=options['padding'],
                             width=options['width'])
        energies = dos.get_energies()
        assert pytest.approx(energies[0]) == options['xmin']
        assert (pytest.approx(energies[-1])
                == ref_max + options['padding'] * options['width'])

        # Check values
        dos = dc.sample_grid(**options)
        energies = dos.get_energies()
        weights = dos.get_all_weights()
        for i, data in enumerate((rawdos, another_rawdos)):
            tmp_dos = data.sample_grid(**options)
            tmp_weights = tmp_dos.get_weights()
            assert np.allclose(weights[i, :], tmp_weights)

    def test_sample_empty(self):
        empty_dc = MinimalDOSCollection([])
        with pytest.raises(IndexError):
            empty_dc._sample(10)
        with pytest.raises(IndexError):
            empty_dc.sample_grid(10)

    @pytest.mark.parametrize('x, weights, bad_info',
                             [([1, 2, 4, 5],
                               [[0, 1, 1, 0], [2, 1, 2, 1]],
                               [{'notenough': 'entries'}]),
                              ([3.1, 2.4, 1.1],
                               [[2, 1., 3.12]],
                               [{'too': 'many'}, {'entries': 'here'}])
                              ])
    def test_from_data(self, x, weights, bad_info):
        dc = DOSCollection.from_data(x, weights)

        for i, dos_data in enumerate(dc):
            assert dos_data.info == {}
            assert np.allclose(dos_data.get_energies(), x)
            assert np.allclose(dos_data.get_weights(), weights[i])

        with pytest.raises(ValueError):
            dc = DOSCollection.from_data(x, weights, info=bad_info)

    collection_data = [[([1., 2., 3.], [1., 1., 2.])],
                       [([1., 2., 3.], [1., 1., 2.]),
                        ([2., 3.5], [0.5, 1.])],
                       [([1., 2., 3.], [1., 1., 2.]),
                        ([2., 3.5], [0.5, 1.]),
                        ([1.], [0.25])]]
    collection_info = [[{'el': 'C', 'index': '1'}],
                       [{'el': 'C', 'index': '1'},
                        {'el': 'C', 'index': '2'}],
                       [{'el': 'C', 'index': '1'},
                        {'el': 'C', 'index': '2'},
                        {'el': 'C', 'index': '2'}]]
    expected_sum = [([1., 2., 3.], [1., 1., 2.],
                     {'el': 'C', 'index': '1'}),
                    ([1., 2., 3., 2., 3.5], [1., 1., 2., 0.5, 1.],
                     {'el': 'C'}),
                    ([1., 2., 3., 2., 3.5, 1.], [1., 1., 2., 0.5, 1., 0.25],
                     {'el': 'C'})]

    @pytest.mark.parametrize('collection_data, collection_info, expected',
                             zip(collection_data, collection_info,
                                 expected_sum))
    def test_sum_all(self, collection_data, collection_info, expected):
        dc = DOSCollection([RawDOSData(*item, info=info)
                            for item, info in zip(collection_data,
                                                  collection_info)])
        summed_dc = dc.sum_all()
        energies, weights, ref_info = expected
        assert np.allclose(summed_dc.get_energies(), energies)
        assert np.allclose(summed_dc.get_weights(), weights)
        assert summed_dc.info == ref_info

    def test_sum_empty(self):
        dc = DOSCollection([])
        with pytest.raises(IndexError):
            dc.sum_all()

    @pytest.mark.parametrize('collection_data, collection_info',
                             zip(collection_data, collection_info))
    def test_total(self, collection_data, collection_info):
        dc = DOSCollection([RawDOSData(*item, info=info)
                            for item, info in zip(collection_data,
                                                  collection_info)])
        summed = dc.sum_all()
        total = dc.total()
        assert np.allclose(summed.get_energies(), total.get_energies())
        assert np.allclose(summed.get_weights(), total.get_weights())
        assert (set(total.info.items()) - set(summed.info.items())
                == {('label', 'Total')})

    select_info = [[{'a': '1', 'b': '1'}, {'a': '2'}],
                   [{'a': '1', 'b': '1'}, {'a': '1', 'b': '2'}],
                   [{'a': '1'}, {'a': '2'}],
                   [{'a': '1', 'b': '1', 'c': '1'},
                    {'a': '1', 'b': '1', 'c': '2'},
                    {'a': '1', 'b': '2', 'c': '3'}]]

    select_query = [{'a': '1'},
                    {'a': '1'},
                    {'a': '0'},
                    {'a': '1', 'b': '1'}]

    select_result = [[{'a': '1', 'b': '1'}],
                     [{'a': '1', 'b': '1'}, {'a': '1', 'b': '2'}],
                     None,
                     [{'a': '1', 'b': '1', 'c': '1'},
                      {'a': '1', 'b': '1', 'c': '2'}]]
    select_not_result = [[{'a': '2'}],
                         None,
                         [{'a': '1'}, {'a': '2'}],
                         [{'a': '1', 'b': '2', 'c': '3'}]]

    sum_by_result = [[{'a': '1', 'b': '1'}, {'a': '2'}],
                     [{'a': '1'}],
                     [{'a': '1'}, {'a': '2'}],
                     [{'a': '1', 'b': '1'}, {'a': '1', 'b': '2', 'c': '3'}]]

    @pytest.mark.parametrize(
        'select_info, select_query, '
        'select_result, select_not_result, sum_by_result',
        zip(select_info, select_query,
            select_result, select_not_result, sum_by_result))
    def test_select(self, select_info, select_query,
                    select_result, select_not_result, sum_by_result):
        dc = DOSCollection([RawDOSData([0.], [0.], info=info)
                            for info in select_info])

        if select_result is None:
            assert dc.select(**select_query)._almost_equals(DOSCollection([]))
        else:
            assert select_result == [data.info for data in
                                     dc.select(**select_query)]

        if select_not_result is None:
            assert (dc.select_not(**select_query)
                    ._almost_equals(DOSCollection([])))
        else:
            assert select_not_result == [data.info for data in
                                         dc.select_not(**select_query)]

        assert sum_by_result == [data.info for data in
                                 dc.sum_by(*sorted(select_query.keys()))]


class TestRawDOSCollection:
    @pytest.fixture()
    def griddos(self):
        energies = np.linspace(1, 10, 7)
        weights = np.sin(energies)
        return GridDOSData(energies, weights, info={'my_key': 'my_value'})

    def test_init(self, griddos):
        with pytest.raises(TypeError):
            RawDOSCollection([griddos])


class TestGridDOSCollection:
    @pytest.fixture()
    def griddos(self):
        energies = np.linspace(1, 10, 7)
        weights = np.sin(energies)
        return GridDOSData(energies, weights, info={'my_key': 'my_value'})

    @pytest.fixture()
    def another_griddos(self):
        energies = np.linspace(1, 10, 7)
        weights = np.cos(energies)
        return GridDOSData(energies, weights, info={'my_key': 'other_value'})

    @pytest.fixture()
    def griddoscollection(self, griddos, another_griddos):
        return GridDOSCollection([griddos, another_griddos])

    def test_init_errors(self, griddos):
        with pytest.raises(TypeError):
            GridDOSCollection([RawDOSData([1.], [1.])])
        with pytest.raises(ValueError):
            energies = np.linspace(1, 10, 7) + 1
            GridDOSCollection([griddos,
                               GridDOSData(energies, np.sin(energies))])
        with pytest.raises(ValueError):
            energies = np.linspace(1, 10, 6)
            GridDOSCollection([griddos,
                               GridDOSData(energies, np.sin(energies))])
        with pytest.raises(ValueError):
            GridDOSCollection([], energies=None)
        with pytest.raises(ValueError):
            GridDOSCollection([griddos], energies=np.linspace(1, 10, 6))

    def test_select(self, griddos, another_griddos):
        gdc = GridDOSCollection([griddos, another_griddos])
        assert (gdc.select(my_key='my_value')
                ._almost_equals(GridDOSCollection([griddos])))
        assert (gdc.select(my_key='not_present')._almost_equals(
            GridDOSCollection([], energies=griddos.get_energies())))
        assert (gdc.select_not(my_key='my_value')
                ._almost_equals(GridDOSCollection([another_griddos])))
        assert (gdc.select(my_key='my_value').select_not(my_key='my_value')
                ._almost_equals(
                    GridDOSCollection([], energies=griddos.get_energies())))

    def test_sequence(self, griddos, another_griddos):
        gdc = GridDOSCollection([griddos, another_griddos])

        for i, (coll_dosdata, dosdata) in enumerate(zip(gdc,
                                                        [griddos,
                                                         another_griddos])):
            assert coll_dosdata._almost_equals(dosdata)
            assert gdc[i]._almost_equals(dosdata)

    def test_slicing(self, griddos, another_griddos):
        gdc = GridDOSCollection([griddos, another_griddos, griddos])

        assert gdc[1:]._almost_equals(
            GridDOSCollection([another_griddos, griddos]))
        assert gdc[:-1]._almost_equals(
            GridDOSCollection([griddos, another_griddos]))

        with pytest.raises(TypeError):
            gdc['string']

    @pytest.mark.parametrize(
        'x, weights, info, error',
        [(np.linspace(1, 10, 12), [np.linspace(4, 1, 12), np.sin(range(12))],
          [{'entry': '1'}, {'entry': '2'}], None),
         (np.linspace(1, 5, 7), [np.sqrt(range(7))], [{'entry': '1'}], None),
         (np.linspace(1, 5, 7), [np.ones((3, 3))], None, IndexError),
         (np.linspace(1, 5, 7), np.array([]).reshape(0, 7), None, IndexError),
         (np.linspace(1, 5, 7), np.ones((2, 6)), None, IndexError)])
    def test_from_data(self, x, weights, info, error):
        if error is not None:
            with pytest.raises(error):
                dc = GridDOSCollection.from_data(x, weights, info=info)
        else:
            dc = GridDOSCollection.from_data(x, weights, info=info)

            for i, dos_data in enumerate(dc):
                assert dos_data.info == info[i]
                assert np.allclose(dos_data.get_energies(), x)
                assert np.allclose(dos_data.get_weights(), weights[i])

    @pytest.mark.usefixtures("figure")
    def test_plot_no_resample(self, griddoscollection, figure):
        ax = figure.add_subplot(111)
        griddoscollection.plot(ax=ax)

        assert np.allclose(ax.get_lines()[0].get_xdata(),
                           griddoscollection[0].get_energies())
        assert np.allclose(ax.get_lines()[1].get_ydata(),
                           griddoscollection[1].get_weights())