def create_from_phonopy(self, request):
     material, subdir, phonopy_args, json_file = request.param
     phonopy_args['path'] = get_phonopy_path(material, subdir)
     qpt_freqs = QpointFrequencies.from_phonopy(**phonopy_args)
     json_path = os.path.join(get_qpt_freqs_dir(material), json_file)
     expected_qpt_freqs = ExpectedQpointFrequencies(json_path)
     return qpt_freqs, expected_qpt_freqs
Example #2
0
 def test_calculate_dos(self, material, qpt_ph_modes_file,
                        expected_dos_json, ebins):
     if qpt_ph_modes_file.endswith('.phonon'):
         qpt_ph_modes = QpointPhononModes.from_castep(
             get_castep_path(material, qpt_ph_modes_file))
     else:
         qpt_ph_modes = QpointPhononModes.from_phonopy(
             phonon_name=get_phonopy_path(material, qpt_ph_modes_file))
     dos = qpt_ph_modes.calculate_dos(ebins)
     expected_dos = get_expected_spectrum1d(expected_dos_json)
     check_spectrum1d(dos, expected_dos)
Example #3
0
    def test_calculate_debye_waller(self, material, qpt_ph_modes_file,
                                    expected_dw_json, temperature, kwargs):
        if qpt_ph_modes_file.endswith('.phonon'):
            qpt_ph_modes = QpointPhononModes.from_castep(
                get_castep_path(material, qpt_ph_modes_file))
        else:
            qpt_ph_modes = QpointPhononModes.from_phonopy(
                phonon_name=get_phonopy_path(material, qpt_ph_modes_file))

        dw = qpt_ph_modes.calculate_debye_waller(temperature * ureg('K'),
                                                 **kwargs)
        expected_dw = get_expected_dw(material, expected_dw_json)
        check_debye_waller(dw, expected_dw, dw_atol=1e-12)
    def test_create_from_phonopy_without_installed_modules_raises_err(
            self, material, subdir, phonopy_args, mocker):
        phonopy_args['path'] = get_phonopy_path(material, subdir)
        # Mock import of yaml, h5py to raise ModuleNotFoundError
        import builtins
        real_import = builtins.__import__

        def mocked_import(name, *args, **kwargs):
            if name == 'h5py' or name == 'yaml':
                raise ModuleNotFoundError
            return real_import(name, *args, **kwargs)

        mocker.patch('builtins.__import__', side_effect=mocked_import)
        with pytest.raises(ImportPhonopyReaderError):
            QpointFrequencies.from_phonopy(**phonopy_args)
Example #5
0
    def test_create_from_phonopy_without_cloader_is_ok(self, material,
                                                       phonopy_args, mocker):
        # Mock 'from yaml import CLoader as Loader' to raise ImportError
        import builtins
        real_import = builtins.__import__

        def mocked_import(name, globals, locals, fromlist, level):
            if name == 'yaml':
                if fromlist is not None and fromlist[0] == 'CSafeLoader':
                    raise ImportError
            return real_import(name, globals, locals, fromlist, level)

        mocker.patch('builtins.__import__', side_effect=mocked_import)

        phonopy_args['path'] = get_phonopy_path(material, '')
        fc = ForceConstants.from_phonopy(**phonopy_args)
        expected_fc = get_expected_fc(material)
        check_force_constants(fc, expected_fc)
    def test_create_from_phonopy_without_cloader_is_ok(self, material, subdir,
                                                       phonopy_args, json_file,
                                                       mocker):
        # Mock 'from yaml import CLoader as Loader' to raise ImportError
        import builtins
        real_import = builtins.__import__

        def mocked_import(name, globals, locals, fromlist, level):
            if name == 'yaml':
                if fromlist is not None and fromlist[0] == 'CSafeLoader':
                    raise ImportError
            return real_import(name, globals, locals, fromlist, level)

        mocker.patch('builtins.__import__', side_effect=mocked_import)

        phonopy_args['path'] = get_phonopy_path(material, subdir)
        qpt_freqs = QpointFrequencies.from_phonopy(**phonopy_args)
        json_path = os.path.join(get_qpt_freqs_dir(material), json_file)
        expected_qpt_freqs = ExpectedQpointFrequencies(json_path)
        check_qpt_freqs(qpt_freqs, expected_qpt_freqs)
 def test_create_from_phonopy_with_bad_inputs_raises_err(
         self, material, subdir, phonopy_args, err):
     phonopy_args['path'] = get_phonopy_path(material, subdir)
     with pytest.raises(err):
         QpointFrequencies.from_phonopy(**phonopy_args)
Example #8
0
import os
import json
from unittest.mock import patch

import pytest
import numpy.testing as npt
# Required for mocking
import matplotlib.pyplot

from tests_and_analysis.test.utils import get_data_path, get_castep_path, get_phonopy_path
from tests_and_analysis.test.script_tests.utils import (
    get_script_test_data_path, get_current_plot_image_data, args_to_key)
import euphonic.cli.powder_map

graphite_fc_file = get_castep_path('graphite', 'graphite.castep_bin')
nacl_prim_fc_file = get_phonopy_path('NaCl_prim', 'phonopy_nacl.yaml')
powder_map_output_file = os.path.join(get_script_test_data_path(),
                                      'powder-map.json')

quick_calc_params = ['--npts=10', '--npts-min=10', '--q-spacing=1']
powder_map_params = [
    [nacl_prim_fc_file], [nacl_prim_fc_file, *quick_calc_params],
    [nacl_prim_fc_file, '--temperature=1000', *quick_calc_params],
    [
        nacl_prim_fc_file, '--temperature=1000', '--weights=coherent',
        *quick_calc_params
    ], [nacl_prim_fc_file, '--v-min=0', '--v-max=1e-10', *quick_calc_params],
    [nacl_prim_fc_file, '--energy-unit=meV', *quick_calc_params],
    [nacl_prim_fc_file, '--weights=coherent', '--cmap=bone'],
    [
        graphite_fc_file, '-w', 'dos', '--y-label=DOS', '--title=DOS TITLE',
 def get_cahgo2_qpt_ph_modes():
     return QpointPhononModes.from_phonopy(
         path=get_phonopy_path('CaHgO2', ''),
         summary_name='mp-7041-20180417.yaml',
         phonon_name='qpoints.yaml')
 def get_cahgo2_qpt_ph_modes(self, request):
     fc = ForceConstants.from_phonopy(
         path=get_phonopy_path('CaHgO2', ''),
         summary_name='mp-7041-20180417.yaml')
     kwargs = self.get_multithreaded_kwargs(request.param)
     return fc.calculate_qpoint_phonon_modes(get_test_qpts(), **kwargs)
class TestForceConstantsCalculateQPointPhononModes:
    def get_lzo_fc():
        return ForceConstants.from_castep(
            get_castep_path('LZO', 'La2Zr2O7.castep_bin'))

    lzo_params = [
        (get_lzo_fc(), 'LZO', [get_test_qpts(),
                               {}], 'LZO_no_asr_qpoint_phonon_modes.json'),
        (get_lzo_fc(), 'LZO', [get_test_qpts(), {
            'asr': 'realspace'
        }], 'LZO_realspace_qpoint_phonon_modes.json'),
        (get_lzo_fc(), 'LZO', [get_test_qpts(), {
            'asr': 'reciprocal'
        }], 'LZO_reciprocal_qpoint_phonon_modes.json')
    ]

    def get_si2_fc():
        return ForceConstants.from_castep(
            get_castep_path('Si2-sc-skew', 'Si2-sc-skew.castep_bin'))

    si2_params = [
        (get_si2_fc(), 'Si2-sc-skew', [get_test_qpts(), {}],
         'Si2-sc-skew_no_asr_qpoint_phonon_modes.json'),
        (get_si2_fc(), 'Si2-sc-skew', [get_test_qpts(), {
            'asr': 'realspace'
        }], 'Si2-sc-skew_realspace_qpoint_phonon_modes.json'),
        (get_si2_fc(), 'Si2-sc-skew', [get_test_qpts(), {
            'asr': 'reciprocal'
        }], 'Si2-sc-skew_reciprocal_qpoint_phonon_modes.json')
    ]

    def get_quartz_fc():
        return ForceConstants.from_castep(
            get_castep_path('quartz', 'quartz.castep_bin'))

    quartz_params = [
        (get_quartz_fc(), 'quartz',
         [get_test_qpts(), {
             'asr': 'reciprocal',
             'splitting': False
         }], 'quartz_reciprocal_qpoint_phonon_modes.json'),
        (get_quartz_fc(), 'quartz', [
            get_test_qpts(), {
                'asr': 'reciprocal',
                'splitting': False,
                'eta_scale': 0.75
            }
        ], 'quartz_reciprocal_qpoint_phonon_modes.json'),
        (get_quartz_fc(), 'quartz', [
            get_test_qpts('split'), {
                'asr': 'reciprocal',
                'splitting': True,
                'insert_gamma': False
            }
        ], 'quartz_split_reciprocal_qpoint_phonon_modes.json'),
        (get_quartz_fc(), 'quartz', [
            get_test_qpts('split_insert_gamma'), {
                'asr': 'reciprocal',
                'splitting': True,
                'insert_gamma': True
            }
        ], 'quartz_split_reciprocal_qpoint_phonon_modes.json')
    ]

    nacl_params = [
        (ForceConstants.from_phonopy(path=get_phonopy_path('NaCl', ''),
                                     summary_name='phonopy_nacl.yaml'), 'NaCl',
         [get_test_qpts(), {
             'asr': 'reciprocal'
         }], 'NaCl_reciprocal_qpoint_phonon_modes.json')
    ]

    cahgo2_params = [
        (ForceConstants.from_phonopy(path=get_phonopy_path('CaHgO2', ''),
                                     summary_name='mp-7041-20180417.yaml'),
         'CaHgO2', [get_test_qpts(), {
             'asr': 'reciprocal'
         }], 'CaHgO2_reciprocal_qpoint_phonon_modes.json')
    ]

    @pytest.mark.parametrize(
        'fc, material, all_args, expected_qpoint_phonon_modes_file',
        lzo_params + quartz_params + nacl_params + si2_params + cahgo2_params)
    @pytest.mark.parametrize('reduce_qpts, n_threads', [(False, 0), (True, 0),
                                                        (True, 1), (True, 2)])
    def test_calculate_qpoint_phonon_modes(self, fc, material, all_args,
                                           expected_qpoint_phonon_modes_file,
                                           reduce_qpts, n_threads):
        func_kwargs = all_args[1]
        func_kwargs['reduce_qpts'] = reduce_qpts
        if n_threads == 0:
            func_kwargs['use_c'] = False
        else:
            func_kwargs['use_c'] = True
            func_kwargs['n_threads'] = n_threads
        qpoint_phonon_modes = fc.calculate_qpoint_phonon_modes(
            all_args[0], **func_kwargs)
        expected_qpoint_phonon_modes = ExpectedQpointPhononModes(
            os.path.join(get_qpt_ph_modes_dir(material),
                         expected_qpoint_phonon_modes_file))
        # Only give gamma-acoustic modes special treatment if the acoustic
        # sum rule has been applied
        if not 'asr' in func_kwargs.keys():
            gamma_atol = None
        else:
            gamma_atol = 0.5
        check_qpt_ph_modes(qpoint_phonon_modes,
                           expected_qpoint_phonon_modes,
                           frequencies_atol=1e-4,
                           frequencies_rtol=2e-5,
                           acoustic_gamma_atol=gamma_atol)

    @pytest.mark.parametrize(
        ('fc, material, all_args, expected_qpoint_phonon_modes_file, '
         'expected_modw_file'), [(get_quartz_fc(), 'quartz', [
             mp_grid([5, 5, 4]), {
                 'asr': 'reciprocal',
                 'return_mode_widths': True
             }
         ], 'quartz_554_full_qpoint_phonon_modes.json',
                                  'quartz_554_full_mode_widths.json'),
                                 (get_lzo_fc(), 'LZO', [
                                     mp_grid([2, 2, 2]), {
                                         'asr': 'reciprocal',
                                         'return_mode_widths': True
                                     }
                                 ], 'lzo_222_full_qpoint_phonon_modes.json',
                                  'lzo_222_full_mode_widths.json')])
    @pytest.mark.parametrize('n_threads', [0, 2])
    def test_calculate_qpoint_phonon_modes_with_mode_widths(
            self, fc, material, all_args, expected_qpoint_phonon_modes_file,
            expected_modw_file, n_threads):
        func_kwargs = all_args[1]
        if n_threads == 0:
            func_kwargs['use_c'] = False
        else:
            func_kwargs['use_c'] = True
            func_kwargs['n_threads'] = n_threads
        qpoint_phonon_modes, modw = fc.calculate_qpoint_phonon_modes(
            all_args[0], **func_kwargs)

        with open(os.path.join(get_fc_dir(), expected_modw_file), 'r') as fp:
            modw_dict = json.load(fp)
        expected_modw = modw_dict['mode_widths'] * ureg(
            modw_dict['mode_widths_unit'])
        expected_qpoint_phonon_modes = ExpectedQpointPhononModes(
            os.path.join(get_qpt_ph_modes_dir(material),
                         expected_qpoint_phonon_modes_file))
        # Only give gamma-acoustic modes special treatment if the acoustic
        # sum rule has been applied
        if not 'asr' in func_kwargs.keys():
            gamma_atol = None
        else:
            gamma_atol = 0.5

        check_qpt_ph_modes(qpoint_phonon_modes,
                           expected_qpoint_phonon_modes,
                           frequencies_atol=1e-4,
                           frequencies_rtol=2e-5,
                           acoustic_gamma_atol=gamma_atol)
        assert modw.units == expected_modw.units
        npt.assert_allclose(modw.magnitude,
                            expected_modw.magnitude,
                            atol=2e-4,
                            rtol=5e-5)

    # ForceConstants stores some values (supercell image list, vectors
    # for the Ewald sum) so check repeated calculations give the same
    # result
    def test_repeated_calculate_qpoint_phonon_modes_doesnt_change_result(self):
        fc = get_fc('quartz')
        qpt_ph_modes1 = fc.calculate_qpoint_phonon_modes(get_test_qpts(),
                                                         asr='realspace')
        qpt_ph_modes2 = fc.calculate_qpoint_phonon_modes(get_test_qpts(),
                                                         asr='realspace')
        check_qpt_ph_modes(qpt_ph_modes1, qpt_ph_modes2)

    @pytest.mark.parametrize(
        'fc, material, qpt, kwargs, expected_qpt_ph_modes_file',
        [(get_fc('quartz'), 'quartz', np.array([[1., 1., 1.]]), {
            'splitting': True
        }, 'quartz_single_qpoint_phonon_modes.json')])
    def test_calculate_qpoint_phonon_modes_single_qpt(
            self, fc, material, qpt, kwargs, expected_qpt_ph_modes_file):
        qpoint_phonon_modes = fc.calculate_qpoint_phonon_modes(qpt, **kwargs)
        expected_qpoint_phonon_modes = ExpectedQpointPhononModes(
            os.path.join(get_qpt_ph_modes_dir(material),
                         expected_qpt_ph_modes_file))
        check_qpt_ph_modes(qpoint_phonon_modes,
                           expected_qpoint_phonon_modes,
                           frequencies_atol=1e-4,
                           frequencies_rtol=2e-5)

    weights = np.array([0.1, 0.05, 0.05, 0.2, 0.2, 0.15, 0.15, 0.2, 0.1])
    weights_output_split_gamma = np.array([
        0.1, 0.05, 0.025, 0.025, 0.2, 0.1, 0.1, 0.075, 0.075, 0.075, 0.075,
        0.2, 0.1
    ])

    @pytest.mark.parametrize(
        'fc, qpts, weights, expected_weights, kwargs',
        [(get_fc('quartz'), get_test_qpts(), weights, weights, {}),
         (get_fc('quartz'), get_test_qpts('split_insert_gamma'), weights,
          weights_output_split_gamma, {
              'insert_gamma': True
          })])
    def test_calculate_qpoint_phonon_modes_with_weights_sets_weights(
            self, fc, qpts, weights, expected_weights, kwargs):
        qpt_ph_modes_weighted = fc.calculate_qpoint_phonon_modes(
            qpts, weights=weights, **kwargs)
        npt.assert_allclose(qpt_ph_modes_weighted.weights, expected_weights)

    @pytest.mark.parametrize(
        'fc, qpts, weights, expected_weights, kwargs',
        [(get_fc('quartz'), get_test_qpts(), weights, weights, {}),
         (get_fc('quartz'), get_test_qpts('split_insert_gamma'), weights,
          weights_output_split_gamma, {
              'insert_gamma': True
          })])
    def test_calculate_qpoint_phonon_modes_with_weights_doesnt_change_result(
            self, fc, qpts, weights, expected_weights, kwargs):
        qpt_ph_modes_weighted = fc.calculate_qpoint_phonon_modes(
            qpts, weights=weights, **kwargs)
        qpt_ph_modes_unweighted = fc.calculate_qpoint_phonon_modes(
            qpts, **kwargs)
        qpt_ph_modes_unweighted.weights = expected_weights
        check_qpt_ph_modes(qpt_ph_modes_weighted, qpt_ph_modes_unweighted)

    @pytest.mark.parametrize('asr', ['realspace', 'reciprocal'])
    def test_calc_qpt_ph_mds_asr_with_nonsense_fc_raises_warning(self, asr):
        fc = ForceConstants.from_json_file(
            os.path.join(get_fc_dir(), 'quartz_random_force_constants.json'))
        with pytest.warns(UserWarning):
            fc.calculate_qpoint_phonon_modes(get_test_qpts(), asr=asr)
Example #12
0
 def create_from_phonopy(self, request):
     material, phonopy_args = request.param
     phonopy_args['path'] = get_phonopy_path(material, '')
     fc = ForceConstants.from_phonopy(**phonopy_args)
     expected_fc = get_expected_fc(material)
     return fc, expected_fc
Example #13
0
class TestForceConstantsCreation:
    @pytest.fixture(params=[
        get_expected_fc('quartz'),
        get_expected_fc('LZO'),
        get_expected_fc('NaCl')
    ])
    def create_from_constructor(self, request):
        expected_fc = request.param
        args, kwargs = expected_fc.to_constructor_args()
        fc = ForceConstants(*args, **kwargs)
        return fc, expected_fc

    @pytest.fixture(params=[('LZO', 'La2Zr2O7.castep_bin'),
                            ('graphite', 'graphite.castep_bin'),
                            ('Si2-sc-skew', 'Si2-sc-skew.castep_bin'),
                            ('quartz', 'quartz.castep_bin')])
    def create_from_castep(self, request):
        material, castep_bin_file = request.param
        expected_fc = get_expected_fc(material)
        castep_filepath = get_castep_path(material, castep_bin_file)
        fc = ForceConstants.from_castep(castep_filepath)
        return fc, expected_fc

    @pytest.fixture(
        params=['LZO', 'graphite', 'Si2-sc-skew', 'quartz', 'CaHgO2', 'NaCl'])
    def create_from_json(self, request):
        material = request.param
        expected_fc = get_expected_fc(material)
        fc = ForceConstants.from_json_file(get_json_file(material))
        return fc, expected_fc

    @pytest.fixture(params=['LZO', 'graphite', 'quartz'])
    def create_from_dict(self, request):
        material = request.param
        expected_fc = get_expected_fc(material)
        fc = ForceConstants.from_dict(expected_fc.to_dict())
        return fc, expected_fc

    @pytest.fixture(params=[
        # Test all combinations of reading from .yaml with/without force
        # constants/born and different file formats. Extra files (e.g.
        # FORCE_CONSTANTS) have been renamed from their defaults to
        # avoid a false positive
        ('NaCl', {
            'summary_name': 'phonopy_nacl.yaml'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_full_fc.yaml'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'FORCE_CONSTANTS_nacl'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'FULL_FORCE_CONSTANTS'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'FULL_FORCE_CONSTANTS_single_number'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'full_force_constants.hdf5'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'force_constants.hdf5'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'force_constants_hdf5.test',
            'fc_format': 'hdf5'
        }),
        ('NaCl', {
            'summary_name': 'phonopy_nofc_noborn.yaml',
            'fc_name': 'FORCE_CONSTANTS_nacl',
            'born_name': 'BORN_nacl'
        }),
        # Explicitly test the default behaviour (if fc/born aren't found
        # in phonopy.yaml they should be read from BORN, FORCE_CONSTANTS).
        # This must be done in a separate directory to the above tests,
        # again to avoid false positives
        ('NaCl_default', {}),
        ('NaCl_prim', {
            'summary_name': 'phonopy_nacl.yaml'
        }),
        ('CaHgO2', {
            'summary_name': 'mp-7041-20180417.yaml'
        }),
        ('CaHgO2', {
            'summary_name': 'phonopy_fullfc.yaml'
        }),
        ('CaHgO2', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'FULL_FORCE_CONSTANTS'
        }),
        ('CaHgO2', {
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'full_force_constants.hdf5'
        })
    ])
    def create_from_phonopy(self, request):
        material, phonopy_args = request.param
        phonopy_args['path'] = get_phonopy_path(material, '')
        fc = ForceConstants.from_phonopy(**phonopy_args)
        expected_fc = get_expected_fc(material)
        return fc, expected_fc

    @pytest.mark.parametrize(('force_constants_creator'), [
        pytest.lazy_fixture('create_from_constructor'),
        pytest.lazy_fixture('create_from_dict'),
        pytest.lazy_fixture('create_from_json'),
        pytest.lazy_fixture('create_from_phonopy'),
        pytest.lazy_fixture('create_from_castep')
    ])
    def test_correct_object_creation(self, force_constants_creator):
        force_constants, expected_force_constants = force_constants_creator
        check_force_constants(force_constants, expected_force_constants)

    @pytest.fixture(params=[
        ('sc_matrix', get_expected_fc('quartz').sc_matrix[:2], ValueError),
        ('cell_origins', get_expected_fc('quartz').sc_matrix, ValueError),
        ('force_constants', get_expected_fc('quartz').force_constants[:2],
         ValueError), ('born', get_expected_fc('quartz').born[:2], ValueError),
        ('dielectric', get_expected_fc('quartz').dielectric[:2], ValueError),
        ('sc_matrix', list(get_expected_fc('quartz').sc_matrix), TypeError),
        ('cell_origins', get_expected_fc('quartz').sc_matrix * ureg.meter,
         TypeError), ('crystal', get_crystal('LZO'), ValueError),
        ('force_constants',
         get_expected_fc('quartz').force_constants.magnitude, TypeError),
        ('born', list(get_expected_fc('quartz').born.magnitude), TypeError),
        ('dielectric', get_expected_fc('quartz').dielectric.shape, TypeError)
    ])
    def inject_faulty_elements(self, request):
        faulty_arg, faulty_value, expected_exception = request.param
        expected_fc = get_expected_fc('quartz')
        # Inject the faulty value and get a tuple of constructor arguments
        args, kwargs = expected_fc.to_constructor_args(
            **{faulty_arg: faulty_value})
        return args, kwargs, expected_exception

    def test_faulty_object_creation(self, inject_faulty_elements):
        faulty_args, faulty_kwargs, expected_exception = inject_faulty_elements
        with pytest.raises(expected_exception):
            ForceConstants(*faulty_args, **faulty_kwargs)

    @pytest.mark.parametrize('phonopy_args',
                             [({
                                 'summary_name': 'phonopy_nofc.yaml',
                                 'fc_name': 'force_constants.hdf5',
                                 'path': get_phonopy_path('NaCl', '')
                             })])
    def test_create_from_phonopy_without_installed_modules_raises_err(
            self, phonopy_args, mocker):
        # Mock import of yaml, h5py to raise ModuleNotFoundError
        import builtins
        real_import = builtins.__import__

        def mocked_import(name, *args, **kwargs):
            if name == 'h5py' or name == 'yaml':
                raise ModuleNotFoundError
            return real_import(name, *args, **kwargs)

        mocker.patch('builtins.__import__', side_effect=mocked_import)
        with pytest.raises(ImportPhonopyReaderError):
            ForceConstants.from_phonopy(**phonopy_args)

    @pytest.mark.parametrize(
        'phonopy_args, err',
        [({
            'summary_name': 'phonopy_nofc.yaml',
            'fc_name': 'force_constants.hdf5',
            'path': get_phonopy_path('NaCl', ''),
            'fc_format': 'nonsense'
        }, ValueError),
         ({
             'summary_name': '../CaHgO2/phonopy_nofc.yaml',
             'fc_name': 'force_constants.hdf5',
             'path': get_phonopy_path('NaCl', '')
         }, ValueError)])
    def test_create_from_phonopy_with_bad_inputs_raises_err(
            self, phonopy_args, err):
        with pytest.raises(err):
            ForceConstants.from_phonopy(**phonopy_args)

    def test_create_from_castep_with_no_fc_raises_runtime_error(self):
        with pytest.raises(RuntimeError):
            ForceConstants.from_castep(
                get_castep_path('h-BN', 'h-BN_no_force_constants.castep_bin'))

    @pytest.mark.parametrize('material, phonopy_args',
                             [('CaHgO2', {
                                 'summary_name': 'mp-7041-20180417.yaml'
                             })])
    def test_create_from_phonopy_without_cloader_is_ok(self, material,
                                                       phonopy_args, mocker):
        # Mock 'from yaml import CLoader as Loader' to raise ImportError
        import builtins
        real_import = builtins.__import__

        def mocked_import(name, globals, locals, fromlist, level):
            if name == 'yaml':
                if fromlist is not None and fromlist[0] == 'CSafeLoader':
                    raise ImportError
            return real_import(name, globals, locals, fromlist, level)

        mocker.patch('builtins.__import__', side_effect=mocked_import)

        phonopy_args['path'] = get_phonopy_path(material, '')
        fc = ForceConstants.from_phonopy(**phonopy_args)
        expected_fc = get_expected_fc(material)
        check_force_constants(fc, expected_fc)
Example #14
0
import os
import json
from unittest.mock import patch

import pytest
import numpy.testing as npt
# Required for mocking
import matplotlib.pyplot

from tests_and_analysis.test.utils import (get_data_path, get_castep_path,
                                           get_phonopy_path)
from tests_and_analysis.test.script_tests.utils import (
    get_script_test_data_path, get_current_plot_line_data, args_to_key)
import euphonic.cli.dispersion

cahgo2_fc_file = get_phonopy_path('CaHgO2', 'mp-7041-20180417.yaml')
lzo_fc_file = os.path.join(get_data_path(), 'force_constants',
                           'LZO_force_constants.json')
nacl_fc_file = get_phonopy_path('NaCl_cli_test', 'force_constants.hdf5')
nacl_phonon_file = os.path.join(get_phonopy_path('NaCl', 'band'), 'band.yaml')
nacl_phonon_hdf5_file = os.path.join(get_phonopy_path('NaCl', 'band'),
                                     'band.hdf5')
quartz_phonon_file = os.path.join(
    get_data_path(), 'qpoint_phonon_modes', 'quartz',
    'quartz_bandstructure_qpoint_phonon_modes.json')
disp_output_file = os.path.join(get_script_test_data_path(), 'dispersion.json')
disp_params = [[cahgo2_fc_file], [cahgo2_fc_file, '--energy-unit=hartree'],
               [
                   cahgo2_fc_file, '--x-label=wavenumber',
                   '--y-label=Energy (meV)', '--title=CaHgO2'
               ], [cahgo2_fc_file, '--reorder'],