forked from diffpy/diffpy.structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp_discus.py
More file actions
323 lines (287 loc) · 10.5 KB
/
p_discus.py
File metadata and controls
323 lines (287 loc) · 10.5 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
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
#!/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 DISCUS structure format."""
import sys
from functools import reduce
from diffpy.structure import Lattice, PDFFitStructure
from diffpy.structure.parsers import StructureParser
from diffpy.structure.structureerrors import StructureFormatError
class P_discus(StructureParser):
"""Parser for DISCUS structure format. The parser chokes on molecule
and generator records.
Attributes
----------
format : str
File format name, default "discus".
nl : int
Line number of the current line being parsed.
lines : list of str
List of lines from the input file.
line : str
Current line being parsed.
stru : PDFFitStructure
Structure being parsed.
ignored_lines : list of str
List of lines that were ignored during parsing.
cell_read : bool
``True`` if cell record processed.
ncell_read : bool
``True`` if ncell record processed.
"""
def __init__(self):
StructureParser.__init__(self)
self.format = "discus"
# helper variables
self.nl = None
self.lines = None
self.line = None
self.stru = None
self.ignored_lines = []
self.cell_read = False
self.ncell_read = False
return
def parseLines(self, lines):
"""Parse list of lines in DISCUS format.
Parameters
----------
lines : list of str
List of lines from the input file.
Returns
-------
PDFFitStructure
Parsed `PDFFitStructure` instance.
Raises
------
StructureFormatError
If the file is not in DISCUS format.
"""
self.lines = lines
ilines = self._linesIterator()
self.stru = PDFFitStructure()
record_parsers = {
"cell": self._parse_cell,
"format": self._parse_format,
"generator": self._parse_not_implemented,
"molecule": self._parse_not_implemented,
"ncell": self._parse_ncell,
"spcgr": self._parse_spcgr,
"symmetry": self._parse_not_implemented,
"title": self._parse_title,
"shape": self._parse_shape,
}
try:
# parse header
for self.line in ilines:
words = self.line.split()
if not words or words[0][0] == "#":
continue
if words[0] == "atoms":
break
rp = record_parsers.get(words[0], self._parse_unknown_record)
rp(words)
# check if cell has been defined
if not self.cell_read:
emsg = "%d: unit cell not defined" % self.nl
raise StructureFormatError(emsg)
# parse atoms
for self.line in ilines:
words = self.line.replace(",", " ").split()
if not words or words[0][0] == "#":
continue
self._parse_atom(words)
# self consistency check
exp_natoms = reduce(lambda x, y: x * y, self.stru.pdffit["ncell"])
# only check if ncell record exists
if self.ncell_read and exp_natoms != len(self.stru):
emsg = "Expected %d atoms, read %d." % (
exp_natoms,
len(self.stru),
)
raise StructureFormatError(emsg)
# take care of superlattice
if self.stru.pdffit["ncell"][:3] != [1, 1, 1]:
latpars = list(self.stru.lattice.abcABG())
superlatpars = [latpars[i] * self.stru.pdffit["ncell"][i] for i in range(3)] + latpars[3:]
superlattice = Lattice(*superlatpars)
self.stru.place_in_lattice(superlattice)
self.stru.pdffit["ncell"] = [1, 1, 1, exp_natoms]
except (ValueError, IndexError):
exc_type, exc_value, exc_traceback = sys.exc_info()
emsg = "%d: file is not in DISCUS format" % self.nl
e = StructureFormatError(emsg)
raise e.with_traceback(exc_traceback)
return self.stru
def toLines(self, stru):
"""Convert `Structure` stru to a list of lines in DISCUS format.
Parameters
----------
stru : Structure
Structure to be converted.
Returns
-------
list of str
List of lines in DISCUS format.
"""
self.stru = stru
# if necessary, convert self.stru to PDFFitStructure
if not isinstance(stru, PDFFitStructure):
self.stru = PDFFitStructure(stru)
# build the stru_pdffit dictionary initialized from the defaults
# in PDFFitStructure
stru_pdffit = PDFFitStructure().pdffit
if stru.pdffit:
stru_pdffit.update(stru.pdffit)
# here we can start
self.lines = lines = []
lines.append(("title " + self.stru.title).strip())
lines.append("spcgr " + stru_pdffit["spcgr"])
if stru_pdffit.get("spdiameter", 0.0) > 0.0:
line = "shape sphere, %g" % stru_pdffit["spdiameter"]
lines.append(line)
if stru_pdffit.get("stepcut", 0.0) > 0.0:
line = "shape stepcut, %g" % stru_pdffit["stepcut"]
lines.append(line)
lines.append("cell %9.6f, %9.6f, %9.6f, %9.6f, %9.6f, %9.6f" % self.stru.lattice.abcABG())
lines.append("ncell %9i, %9i, %9i, %9i" % (1, 1, 1, len(self.stru)))
lines.append("atoms")
for a in self.stru:
lines.append(
"%-4s %17.8f %17.8f %17.8f %12.4f"
% (
a.element.upper(),
a.xyz[0],
a.xyz[1],
a.xyz[2],
a.Bisoequiv,
)
)
return lines
def _linesIterator(self):
"""Iterator over `self.lines`, which increments `self.nl`"""
# ignore trailing empty lines
stop = len(self.lines)
while stop > 0 and self.lines[stop - 1].strip() == "":
stop -= 1
self.nl = 0
# read header of PDFFit file
for self.line in self.lines[:stop]:
self.nl += 1
yield self.line
pass
def _parse_cell(self, words):
"""Process the cell record from DISCUS structure file."""
# split again on spaces or commas
words = self.line.replace(",", " ").split()
latpars = [float(w) for w in words[1:7]]
try:
self.stru.lattice.set_latt_parms(*latpars)
except ZeroDivisionError:
emsg = "%d: Invalid lattice parameters - zero cell volume" % self.nl
raise StructureFormatError(emsg)
self.cell_read = True
return
def _parse_format(self, words):
"""Process the format record from DISCUS structure file."""
if words[1] == "pdffit":
emsg = "%d: file is not in DISCUS format" % self.nl
raise StructureFormatError(emsg)
return
def _parse_ncell(self, words):
"""Process the ncell record from DISCUS structure file."""
# split again on spaces or commas
words = self.line.replace(",", " ").split()
self.stru.pdffit["ncell"] = [int(w) for w in words[1:5]]
self.ncell_read = True
return
def _parse_spcgr(self, words):
"""Process the spcgr record from DISCUS structure file."""
self.stru.pdffit["spcgr"] = "".join(words[1:])
return
def _parse_title(self, words):
"""Process the title record from DISCUS structure file."""
self.stru.title = self.line.lstrip()[5:].strip()
return
def _parse_shape(self, words):
"""Process the shape record from DISCUS structure file.
Parameters
----------
words : list of str
List of words in the line.
Raises
------
StructureFormatError
Invalid type of particle shape correction.
"""
# strip away any commas
linefixed = " ".join(words).replace(",", " ")
wordsfixed = linefixed.split()
shapetype = wordsfixed[1]
if shapetype == "sphere":
self.stru.pdffit["spdiameter"] = float(words[2])
elif shapetype == "stepcut":
self.stru.pdffit["stepcut"] = float(words[2])
else:
emsg = "Invalid type of particle shape correction %r" % shapetype
raise StructureFormatError(emsg)
return
def _parse_atom(self, words):
"""Process atom records in DISCUS structure file."""
element = words[0][0:1].upper() + words[0][1:].lower()
xyz = [float(w) for w in words[1:4]]
Biso = float(words[4])
self.stru.add_new_atom(element, xyz)
a = self.stru.get_last_atom()
a.Bisoequiv = Biso
return
def _parse_unknown_record(self, words):
"""Process unknown record in DISCUS structure file.
Silently ignores the line and adds it to `self.ignored_lines`.
Parameters
----------
words : list of str
List of words in the line.
Raises
------
StructureFormatError
Unknown record.
"""
self.ignored_lines.append(self.line)
return
def _parse_not_implemented(self, words):
"""Process the unimplemented records from DISCUS structure file.
Parameters
----------
words : list of str
List of words in the line.
Raises
------
NotImplementedError
If the record is not implemented.
"""
emsg = "%d: reading of DISCUS record %r is not implemented." % (
self.nl,
words[0],
)
raise NotImplementedError(emsg)
# End of class P_pdffit
# Routines -------------------------------------------------------------------
def getParser():
"""Return new `parser` object for DISCUS format.
Returns
-------
P_discus
Instance of `P_discus`.
"""
return P_discus()