forked from diffpy/diffpy.structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp_xyz.py
More file actions
214 lines (185 loc) · 6.16 KB
/
p_xyz.py
File metadata and controls
214 lines (185 loc) · 6.16 KB
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
#!/usr/bin/env python
##############################################################################
#
# diffpy.structure by DANSE Diffraction group
# Simon J. L. Billinge
# (c) 2007 trustees of the Michigan State University.
# All rights reserved.
#
# File coded by: Pavol Juhas
#
# See AUTHORS.txt for a list of people who contributed.
# See LICENSE_DANSE.txt for license information.
#
##############################################################################
"""Parser for XYZ file format, where.
* First line gives number of atoms.
* Second line has optional title.
* Remaining lines contain element, `x, y, z`.
"""
import sys
from diffpy.structure import Structure
from diffpy.structure.parsers import StructureParser
from diffpy.structure.structureerrors import StructureFormatError
from diffpy.utils._deprecator import build_deprecation_message, deprecated
base = "diffpy.structure.P_xyz"
removal_version = "4.0.0"
parseLines_deprecation_msg = build_deprecation_message(
base,
"parseLines",
"parse_lines",
removal_version,
)
toLines_deprecation_msg = build_deprecation_message(
base,
"toLines",
"to_lines",
removal_version,
)
class P_xyz(StructureParser):
"""Parser for standard XYZ structure format.
Attributes
----------
format : str
Format name, default "xyz".
"""
def __init__(self):
StructureParser.__init__(self)
self.format = "xyz"
return
@deprecated(parseLines_deprecation_msg)
def parseLines(self, lines):
"""This function has been deprecated and will be removed in
version 4.0.0.
Please use diffpy.structure.P_xyz.parse_lines instead.
"""
return self.parse_lines(lines)
def parse_lines(self, lines):
"""Parse list of lines in XYZ format.
Parameters
----------
lines : list of str
List of lines in XYZ format.
Returns
-------
Structure
Parsed structure instance.
Raises
------
StructureFormatError
Invalid XYZ format.
"""
linefields = [line.split() for line in lines]
# prepare output structure
stru = Structure()
# find first valid record
start = 0
for field in linefields:
if len(field) == 0 or field[0] == "#":
start += 1
else:
break
# first valid line gives number of atoms
try:
lfs = linefields[start]
w1 = linefields[start][0]
if len(lfs) == 1 and str(int(w1)) == w1:
p_natoms = int(w1)
stru.title = lines[start + 1].strip()
start += 2
else:
emsg = "%d: invalid XYZ format, missing number of atoms" % (start + 1)
raise StructureFormatError(emsg)
except (IndexError, ValueError):
exc_type, exc_value, exc_traceback = sys.exc_info()
emsg = "%d: invalid XYZ format, missing number of atoms" % (start + 1)
e = StructureFormatError(emsg)
raise e.with_traceback(exc_traceback)
# find the last valid record
stop = len(lines)
while stop > start and len(linefields[stop - 1]) == 0:
stop -= 1
# get out for empty structure
if p_natoms == 0 or start >= stop:
return stru
# here we have at least one valid record line
nfields = len(linefields[start])
if nfields != 4:
emsg = "%d: invalid XYZ format, expected 4 columns" % (start + 1)
raise StructureFormatError(emsg)
# now try to read all record lines
try:
p_nl = start
for fields in linefields[start:]:
p_nl += 1
if fields == []:
continue
elif len(fields) != nfields:
emsg = ("%d: all lines must have " + "the same number of columns") % p_nl
raise StructureFormatError(emsg)
element = fields[0]
element = element[0].upper() + element[1:].lower()
xyz = [float(f) for f in fields[1:4]]
stru.add_new_atom(element, xyz=xyz)
except ValueError:
exc_type, exc_value, exc_traceback = sys.exc_info()
emsg = "%d: invalid number format" % p_nl
e = StructureFormatError(emsg)
raise e.with_traceback(exc_traceback)
# finally check if all the atoms have been read
if p_natoms is not None and len(stru) != p_natoms:
emsg = "expected %d atoms, read %d" % (p_natoms, len(stru))
raise StructureFormatError(emsg)
return stru
@deprecated(toLines_deprecation_msg)
def toLines(self, stru):
"""This function has been deprecated and will be removed in
version 4.0.0.
Please use diffpy.structure.P_xyz.to_lines instead.
"""
return self.to_lines(stru)
def to_lines(self, stru):
"""Convert Structure stru to a list of lines in XYZ format.
Parameters
----------
stru : Structure
Structure to be converted.
Returns
-------
list of str
List of lines in XYZ format.
"""
lines = []
lines.append(str(len(stru)))
lines.append(stru.title)
for a in stru:
rc = a.xyz_cartn
s = "%-3s %g %g %g" % (a.element, rc[0], rc[1], rc[2])
lines.append(s)
return lines
# End of class P_xyz
# Routines -------------------------------------------------------------------
parsers_base = "diffpy.structure"
getParser_deprecation_msg = build_deprecation_message(
parsers_base,
"getParser",
"get_parser",
removal_version,
)
@deprecated(getParser_deprecation_msg)
def getParser():
"""Return new `parser` object for XYZ format.
Returns
-------
P_xcfg
Instance of `P_xyz`.
"""
return get_parser()
def get_parser():
"""Return new `parser` object for XYZ format.
Returns
-------
P_xcfg
Instance of `P_xyz`.
"""
return P_xyz()