forked from diffpy/diffpy.structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp_pdffit.py
More file actions
319 lines (292 loc) · 11.5 KB
/
p_pdffit.py
File metadata and controls
319 lines (292 loc) · 11.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
#!/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 PDFfit structure format."""
import sys
from functools import reduce
import numpy
from diffpy.structure import Lattice, PDFFitStructure
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_pdffit"
removal_version = "4.0.0"
parseLines_deprecation_msg = build_deprecation_message(
base,
"parseLines",
"parse_lines",
removal_version,
)
class P_pdffit(StructureParser):
"""Parser for PDFfit structure format.
Attributes
----------
format : str
Format name, default "pdffit".
ignored_lines : list
List of lines ignored during parsing.
stru : PDFFitStructure
Structure instance used for cif input or output.
"""
def __init__(self):
StructureParser.__init__(self)
self.format = "pdffit"
self.ignored_lines = []
self.stru = None
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_pdffit.parse_lines instead.
"""
return self.parse_lines(lines)
def parse_lines(self, lines):
"""Parse list of lines in PDFfit format.
Parameters
----------
lines : list of str
List of lines in PDB format.
Returns
-------
Structure
Parsed structure instance.
Raises
------
StructureFormatError
File not in PDFfit format.
"""
p_nl = 0
try:
self.stru = PDFFitStructure()
stru = self.stru
cell_line_read = False
stop = len(lines)
while stop > 0 and lines[stop - 1].strip() == "":
stop -= 1
ilines = iter(lines[:stop])
# read header of PDFFit file
for line in ilines:
p_nl += 1
words = line.split()
if len(words) == 0 or words[0][0] == "#":
continue
elif words[0] == "title":
stru.title = line.lstrip()[5:].strip()
elif words[0] == "scale":
stru.pdffit["scale"] = float(words[1])
elif words[0] == "sharp":
l1 = line.replace(",", " ")
sharp_pars = [float(w) for w in l1.split()[1:]]
if len(sharp_pars) < 4:
stru.pdffit["delta2"] = sharp_pars[0]
stru.pdffit["sratio"] = sharp_pars[1]
stru.pdffit["rcut"] = sharp_pars[2]
else:
stru.pdffit["delta2"] = sharp_pars[0]
stru.pdffit["delta1"] = sharp_pars[1]
stru.pdffit["sratio"] = sharp_pars[2]
stru.pdffit["rcut"] = sharp_pars[3]
elif words[0] == "spcgr":
key = "spcgr"
start = line.find(key) + len(key)
value = line[start:].strip()
stru.pdffit["spcgr"] = value
elif words[0] == "shape":
self._parse_shape(line)
elif words[0] == "cell":
cell_line_read = True
l1 = line.replace(",", " ")
latpars = [float(w) for w in l1.split()[1:7]]
stru.lattice = Lattice(*latpars)
elif words[0] == "dcell":
l1 = line.replace(",", " ")
stru.pdffit["dcell"] = [float(w) for w in l1.split()[1:7]]
elif words[0] == "ncell":
l1 = line.replace(",", " ")
stru.pdffit["ncell"] = [int(w) for w in l1.split()[1:5]]
elif words[0] == "format":
if words[1] != "pdffit":
emsg = "%d: file is not in PDFfit format" % p_nl
raise StructureFormatError(emsg)
elif words[0] == "atoms" and cell_line_read:
break
else:
self.ignored_lines.append(line)
# Header reading finished, check if required lines were present.
if not cell_line_read:
emsg = "%d: file is not in PDFfit format" % p_nl
raise StructureFormatError(emsg)
# Load data from atom entries.
p_natoms = reduce(lambda x, y: x * y, stru.pdffit["ncell"])
# we are now inside data block
for line in ilines:
p_nl += 1
wl1 = line.split()
element = wl1[0][0].upper() + wl1[0][1:].lower()
xyz = [float(w) for w in wl1[1:4]]
occ = float(wl1[4])
stru.add_new_atom(element, xyz=xyz, occupancy=occ)
a = stru.get_last_atom()
p_nl += 1
wl2 = next(ilines).split()
a.sigxyz = [float(w) for w in wl2[0:3]]
a.sigo = float(wl2[3])
p_nl += 1
wl3 = next(ilines).split()
p_nl += 1
wl4 = next(ilines).split()
p_nl += 1
wl5 = next(ilines).split()
p_nl += 1
wl6 = next(ilines).split()
U = numpy.zeros((3, 3), dtype=float)
sigU = numpy.zeros((3, 3), dtype=float)
U[0, 0] = float(wl3[0])
U[1, 1] = float(wl3[1])
U[2, 2] = float(wl3[2])
sigU[0, 0] = float(wl4[0])
sigU[1, 1] = float(wl4[1])
sigU[2, 2] = float(wl4[2])
U[0, 1] = U[1, 0] = float(wl5[0])
U[0, 2] = U[2, 0] = float(wl5[1])
U[1, 2] = U[2, 1] = float(wl5[2])
sigU[0, 1] = sigU[1, 0] = float(wl6[0])
sigU[0, 2] = sigU[2, 0] = float(wl6[1])
sigU[1, 2] = sigU[2, 1] = float(wl6[2])
a.anisotropy = stru.lattice.isanisotropic(U)
a.U = U
a.sigU = sigU
if len(stru) != p_natoms:
emsg = "expected %d atoms, read %d" % (p_natoms, len(stru))
raise StructureFormatError(emsg)
if stru.pdffit["ncell"][:3] != [1, 1, 1]:
superlatpars = [latpars[i] * stru.pdffit["ncell"][i] for i in range(3)] + latpars[3:]
superlattice = Lattice(*superlatpars)
stru.place_in_lattice(superlattice)
stru.pdffit["ncell"] = [1, 1, 1, p_natoms]
except (ValueError, IndexError):
emsg = "%d: file is not in PDFfit format" % p_nl
exc_type, exc_value, exc_traceback = sys.exc_info()
e = StructureFormatError(emsg)
raise e.with_traceback(exc_traceback)
return stru
def toLines(self, stru):
"""Convert `Structure` stru to a list of lines in PDFfit format.
Parameters
----------
stru : Structure
Structure to be converted.
Returns
-------
list of str
List of lines in PDFfit format.
"""
# build the stru_pdffit dictionary initialized from the defaults
# in PDFFitStructure
stru_pdffit = PDFFitStructure().pdffit
if stru.pdffit:
stru_pdffit.update(stru.pdffit)
lines = []
# default values of standard deviations
d_sigxyz = numpy.zeros(3, dtype=float)
d_sigo = 0.0
d_sigU = numpy.zeros((3, 3), dtype=float)
# here we can start
line = "title " + stru.title
lines.append(line.strip())
lines.append("format pdffit")
lines.append("scale %9.6f" % stru_pdffit["scale"])
lines.append(
"sharp %9.6f, %9.6f, %9.6f, %9.6f"
% (
stru_pdffit["delta2"],
stru_pdffit["delta1"],
stru_pdffit["sratio"],
stru_pdffit["rcut"],
)
)
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)
lat = stru.lattice
lines.append(
"cell %9.6f, %9.6f, %9.6f, %9.6f, %9.6f, %9.6f"
% (lat.a, lat.b, lat.c, lat.alpha, lat.beta, lat.gamma)
)
lines.append("dcell %9.6f, %9.6f, %9.6f, %9.6f, %9.6f, %9.6f" % tuple(stru_pdffit["dcell"]))
lines.append("ncell %9i, %9i, %9i, %9i" % (1, 1, 1, len(stru)))
lines.append("atoms")
for a in stru:
ad = a.__dict__
lines.append(
"%-4s %17.8f %17.8f %17.8f %12.4f"
% (
a.element.upper(),
a.xyz[0],
a.xyz[1],
a.xyz[2],
a.occupancy,
)
)
sigmas = numpy.concatenate((ad.get("sigxyz", d_sigxyz), [ad.get("sigo", d_sigo)]))
lines.append(" %18.8f %17.8f %17.8f %12.4f" % tuple(sigmas))
sigU = ad.get("sigU", d_sigU)
Uii = (a.U[0][0], a.U[1][1], a.U[2][2])
Uij = (a.U[0][1], a.U[0][2], a.U[1][2])
sigUii = (sigU[0][0], sigU[1][1], sigU[2][2])
sigUij = (sigU[0][1], sigU[0][2], sigU[1][2])
lines.append(" %18.8f %17.8f %17.8f" % Uii)
lines.append(" %18.8f %17.8f %17.8f" % sigUii)
lines.append(" %18.8f %17.8f %17.8f" % Uij)
lines.append(" %18.8f %17.8f %17.8f" % sigUij)
return lines
# Protected methods ------------------------------------------------------
def _parse_shape(self, line):
"""Process shape line from PDFfit file and update self.stru.
Parameters
----------
line : str
Line containing data for particle shape correction.
Raises
------
StructureFormatError
Invalid type of particle shape correction.
"""
line_nocommas = line.replace(",", " ")
words = line_nocommas.split()
assert words[0] == "shape"
shapetype = words[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
# End of class P_pdffit
# Routines -------------------------------------------------------------------
def getParser():
"""Return new `parser` object for PDFfit format.
Returns
-------
P_pdffit
Instance of `P_pdffit`.
"""
return P_pdffit()