Exemplo n.º 1
0
def test_consistency_with_parsevasp(fresh_aiida_env, vasp_structure):
    """
    Compare the poscar-dict returned by parsevasp to the dict created by the PoscarParser.

    This tests purpose is to give a warning if we are overriding keys in parsevasps poscar-dict.
    """
    from aiida_vasp.parsers.file_parsers.poscar import parsevasp_to_aiida
    from parsevasp.poscar import Poscar

    path = data_path('poscar', 'POSCAR')
    poscar = Poscar(file_path=path, prec=12, conserve_order=True)

    poscar_dict = poscar.get_dict(direct=False)
    result_dict = parsevasp_to_aiida(poscar)['poscar-structure']
    compare_objects(poscar_dict, result_dict)
Exemplo n.º 2
0
def test_poscar_write(tmp_path, poscar_parser):
    """Test that the POSCAR writes correctly."""
    poscar = poscar_parser.get_dict()
    # Write it
    poscar_write_path = tmp_path / 'POSCAR'
    poscar_parser.write(file_path=poscar_write_path)
    # Then load same content again, but from the newly written file
    poscar_reloaded = Poscar(file_path=poscar_write_path).get_dict()
    compare_poscars(poscar, poscar_reloaded)
    # Check that handler also works for write by yet again writing a new POSCAR and comparing
    with open(poscar_write_path, 'w') as handler:
        poscar_parser.write(file_handler=handler)
    with open(poscar_write_path, 'r') as handler:
        poscar_reloaded = Poscar(file_handler=handler).get_dict()
    compare_poscars(poscar, poscar_reloaded)
Exemplo n.º 3
0
def test_poscar_cartesian(tmp_path, poscar_parser):
    """Test that the POSCAR writes and reads positional cartesian coordinates correctly."""
    poscar = poscar_parser.get_dict()
    # Write it
    poscar_write_path = tmp_path / 'POSCAR'
    poscar_parser.write(file_path=poscar_write_path)
    poscar_cartesian = None
    with open(poscar_write_path) as file_object:
        poscar_cartesian = file_object.readlines()
    assert poscar_cartesian[7] == 'Cartesian\n'
    assert poscar_cartesian[
        8] == '  2.254110000000   2.254110000000   2.254110000000\n'
    assert poscar_cartesian[
        9] == '  6.762340000000   6.762340000000   6.762340000000\n'
    assert poscar_cartesian[
        39] == '  7.529650000000   3.083180000000   4.508230000000\n'
    # Then load same content again, but from the newly written file, which should now be on cartesian form
    poscar_reloaded = Poscar(file_path=poscar_write_path).get_dict()
    # Comment entry is modified so need to remove that before comparing
    del poscar['comment']
    del poscar_reloaded['comment']
    # Compare
    assert np.allclose(poscar['unitcell'], poscar_reloaded['unitcell'])
    for index, site in enumerate(poscar['sites']):
        reloaded = poscar_reloaded['sites'][index]
        assert site['specie'] == reloaded['specie']
        assert np.allclose(site['position'], reloaded['position'])
        assert site['selective'] == reloaded['selective']
        assert site['velocities'] == reloaded['velocities']
        assert np.allclose(site['predictors'], reloaded['predictors'])
        assert site['direct'] == reloaded['direct']
Exemplo n.º 4
0
def poscar_parser(request):
    """Load POSCAR file.

    """

    testdir = os.path.dirname(__file__)
    poscarfile = testdir + '/POSCAR'
    poscar = Poscar(file_path=poscarfile, write_direct=request.param)

    return poscar
Exemplo n.º 5
0
def poscar_parser_vel():
    """Load POSCAR file.

    """

    testdir = os.path.dirname(__file__)
    poscarfile = testdir + '/POSCARVEL'
    poscar = Poscar(file_path=poscarfile)

    return poscar
Exemplo n.º 6
0
def poscar_parser_names():
    """Load POSCAR file.

    """

    testdir = os.path.dirname(__file__)
    poscarfile = testdir + "/POSCARNAMES"
    poscar = Poscar(file_path=poscarfile)

    return poscar
Exemplo n.º 7
0
    def _parsed_object(self):
        """Return the parsevasp object representing the POSCAR file."""

        try:
            return Poscar(poscar_dict=aiida_to_parsevasp(
                self._parsed_data['poscar-structure']),
                          prec=self.precision,
                          conserve_order=True)
        except SystemExit:
            return None
Exemplo n.º 8
0
def test_poscar_entries_dict():
    """Test to check inititialization using dict.

    """

    unitcell = np.array([[9.0164589999999993, 0., 0.],
                         [0., 9.0164589999999993, 0.],
                         [0., 0., 9.0164589999999993]])
    sites = []
    sites.append(
        Site('Co', np.array([0.0, 0.0, 0.0]), [True, True, True], None, None,
             True))
    poscar_dict = {
        'comment': 'Example file',
        'unitcell': unitcell,
        'sites': sites
    }
    poscar_parser = Poscar(poscar_dict=poscar_dict)
    poscar = poscar_parser.get_dict()
    assert poscar['comment'] == 'Example file'
    unitcell = poscar['unitcell']
    test = np.array([[9.0164589999999993, 0.,
                      0.], [0., 9.0164589999999993, 0.],
                     [0., 0., 9.0164589999999993]])
    np.testing.assert_allclose(unitcell, test)
    sites = poscar['sites']
    assert len(sites) == 1
    test = {
        'specie': 'Co',
        'position': np.array([0.0, 0.0, 0.0]),
        'selective': [True, True, True],
        'velocities': None,
        'predictors': None,
        'direct': True
    }
    np.testing.assert_allclose(sites[0]['position'], test['position'])
    assert sites[0]['specie'] == test['specie']
    assert sites[0]['selective'] == [True, True, True]
    assert sites[0]['velocities'] == None
    assert sites[0]['predictors'] == None
    assert sites[0]['direct']
Exemplo n.º 9
0
def poscar_parser_file_object():
    """Load POSCAR file using a file object.

    """

    testdir = os.path.dirname(__file__)
    poscarfile = testdir + '/POSCAR'
    poscar = None
    with open(poscarfile) as file_handler:
        poscar = Poscar(file_handler=file_handler)

    return poscar
Exemplo n.º 10
0
def test_poscar_scaling(tmp_path, poscar_parser):
    """Test that the scaling factor works when reading a POSCAR file."""
    poscar = poscar_parser.get_dict()
    # Locate scaling factor
    scaling = poscar['unitcell'][1, 1]
    poscar = poscar_parser.get_string()
    poscar_lines = poscar.splitlines()

    # First test scaling when positions are in direct coordinates
    # Prepare scaled unitcell, but direct coordinates
    poscar_lines[1] = str(scaling)
    for i in range(2, 5):
        poscar_lines[i] = ' '.join(
            [str(float(item) / scaling) for item in poscar_lines[i].split()])
    poscar_write_path = tmp_path / 'POSCAR'
    # Dump it to file
    with open(poscar_write_path, 'w') as file_object:
        file_object.write('\n'.join(poscar_lines))
    # Read it using a new Poscar instance
    poscar_scaled_direct = Poscar(file_path=poscar_write_path).get_dict()
    unitcell_test = np.array([[9.0164589999999993, 0., 0.],
                              [0., 9.0164589999999993, 0.],
                              [0., 0., 9.0164589999999993]])
    position_test = np.array([0.24999947, 0.24999947, 0.24999947])
    assert np.allclose(poscar_scaled_direct['sites'][0]['position'],
                       position_test)
    assert np.allclose(poscar_scaled_direct['unitcell'], unitcell_test)

    # Then test scaling when positions are in cartesian coordinates
    # Create a new Poscar instance where the write is in cartesian coordinates
    poscar_parser_temp = Poscar(poscar_string=poscar, write_direct=False)
    poscar_parser_temp.write(file_path=poscar_write_path)
    with open(poscar_write_path, 'r') as file_object:
        poscar_cart_unscaled = file_object.readlines()
    poscar_cart_unscaled[1] = str(scaling) + '\n'
    # Scale unitcell
    for i in range(2, 5):
        poscar_cart_unscaled[i] = ' '.join([
            str(float(item) / scaling)
            for item in poscar_cart_unscaled[i].split()
        ]) + '\n'
    # Scale positions
    for i in range(8, 40):
        poscar_cart_unscaled[i] = ' '.join([
            str(float(item) / scaling)
            for item in poscar_cart_unscaled[i].split()
        ]) + '\n'
    # Write file
    with open(poscar_write_path, 'w') as file_object:
        file_object.writelines(poscar_cart_unscaled)
    poscar_cart_scaled = Poscar(file_path=poscar_write_path).get_dict()
    unitcell_test = np.array([[9.0164589999999993, 0., 0.],
                              [0., 9.0164589999999993, 0.],
                              [0., 0., 9.0164589999999993]])
    position_test = np.array([0.24999947, 0.24999947, 0.24999947])
    assert np.allclose(poscar_scaled_direct['sites'][0]['position'],
                       position_test)
    assert np.allclose(poscar_scaled_direct['unitcell'], unitcell_test)
Exemplo n.º 11
0
    def _parsed_object(self):
        """Return the parsevasp object representing the POSCAR file."""

        if isinstance(self._data_obj, get_data_class('structure')):
            # _data_obj is StructureData, return the parsed version if possible.
            try:
                return Poscar(poscar_dict=self.aiida_to_parsevasp(
                    self._data_obj, options=self._options),
                              prec=self._precision,
                              conserve_order=True,
                              logger=self._logger)
            except SystemExit:
                return None
        # _data_obj is a SingleFile:
        return self._data_obj
Exemplo n.º 12
0
    def _parse_file(self, inputs):
        """Read POSCAR file format."""

        # check if structure have already been loaded, in that case just return
        if isinstance(self._data_obj, get_data_class('structure')):
            return {'poscar-structure': self._data_obj}

        # pass file path to parsevasp and try to load file
        try:
            poscar = Poscar(file_path=self._data_obj.path,
                            prec=self.precision,
                            conserve_order=True)
        except SystemExit:
            self._logger.warning("Parsevasp exited abnormally. "
                                 "Returning None.")
            return {'poscar-structure': None}

        result = parsevasp_to_aiida(poscar)

        return result
Exemplo n.º 13
0
def test_poscar_write(tmp_path, poscar_parser):
    """Test that the POSCAR writes correctly."""
    poscar = poscar_parser.get_dict()
    # Write it
    poscar_write_path = tmp_path / "POSCAR"
    poscar_parser.write(poscar_write_path)
    # Then load same content again, but from the newly written file
    poscar_reloaded = Poscar(file_path=poscar_write_path).get_dict()
    # Comment entry is modified so need to remove that before comparing
    del poscar['comment']
    del poscar_reloaded['comment']
    # Compare
    assert np.allclose(poscar['unitcell'], poscar_reloaded['unitcell'])
    for index, site in enumerate(poscar['sites']):
        reloaded = poscar_reloaded['sites'][index]
        assert site['specie'] == reloaded['specie']
        assert np.allclose(site['position'], reloaded['position'])
        assert site['selective'] == reloaded['selective']
        assert site['velocities'] == reloaded['velocities']
        assert np.allclose(site['predictors'], reloaded['predictors'])
        assert site['direct'] == reloaded['direct']