Skip to content

Commit 3edbc24

Browse files
authored
add xyz format (to) (#240)
This commit adds support for converting data to pure XYZ format. It's a quick way to visualize data using VMD or PyMol - these two software do support XYZ format file.
1 parent 25acc84 commit 3edbc24

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

dpdata/plugins/xyz.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,25 @@
1+
import numpy as np
2+
13
from dpdata.xyz.quip_gap_xyz import QuipGapxyzSystems
4+
from dpdata.xyz.xyz import coord_to_xyz
25
from dpdata.format import Format
36

7+
@Format.register("xyz")
8+
class XYZFormat(Format):
9+
"""XYZ foramt.
10+
11+
Examples
12+
--------
13+
>>> s.to("xyz", "a.xyz")
14+
"""
15+
def to_system(self, data, file_name, **kwargs):
16+
buff = []
17+
types = np.array(data['atom_names'])[data['atom_types']]
18+
for cc in data['coords']:
19+
buff.append(coord_to_xyz(cc, types))
20+
with open(file_name, 'w') as fp:
21+
fp.write("\n".join(buff))
22+
423

524
@Format.register("quip/gap/xyz")
625
@Format.register("quip/gap/xyz_file")

dpdata/xyz/xyz.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import numpy as np
2+
3+
def coord_to_xyz(coord: np.ndarray, types: list)->str:
4+
"""Convert coordinates and types to xyz format.
5+
6+
Parameters
7+
----------
8+
coord: np.ndarray
9+
coordinates, Nx3 array
10+
types: list
11+
list of types
12+
13+
Returns
14+
-------
15+
str
16+
xyz format string
17+
18+
Examples
19+
--------
20+
>>> coord_to_xyz(np.ones((1,3)), ["C"])
21+
1
22+
23+
C 1.000000 1.000000 1.000000
24+
"""
25+
buff = [str(len(types)), '']
26+
for at, cc in zip(types, coord):
27+
buff.append("{} {:.6f} {:.6f} {:.6f}".format(at, *cc))
28+
return "\n".join(buff)

tests/test_xyz.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import unittest
2+
import numpy as np
3+
import tempfile
4+
from context import dpdata
5+
6+
class TestXYZ(unittest.TestCase):
7+
def test_to_xyz(self):
8+
with tempfile.NamedTemporaryFile('r') as f_xyz:
9+
dpdata.System(data={
10+
"atom_names": ["C", "O"],
11+
"atom_numbs": [1, 1],
12+
"atom_types": np.array([0, 1]),
13+
"coords": np.arange(6).reshape((1,2,3)),
14+
"cells": np.zeros((1,3,3)),
15+
"orig": np.zeros(3),
16+
}).to("xyz", f_xyz.name)
17+
xyz0 = f_xyz.read().strip()
18+
xyz1 = "2\n\nC 0.000000 1.000000 2.000000\nO 3.000000 4.000000 5.000000"
19+
self.assertEqual(xyz0, xyz1)

0 commit comments

Comments
 (0)