1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """Parser for raw XYZ file format. Raw XYZ is a 3 or 4 column text
16 file with cartesian coordinates of atoms and an optional first column
17 for atom types.
18 """
19
20 __id__ = "$Id: P_rawxyz.py 2825 2009-03-09 04:33:12Z juhas $"
21
22 import sys
23
24 from diffpy.Structure import Structure, Lattice, Atom
25 from diffpy.Structure import StructureFormatError
26 from diffpy.Structure.utils import isfloat
27 from diffpy.Structure.Parsers import StructureParser
28
30 """Parser --> StructureParser subclass for RAWXYZ format"""
31
36
38 """Parse list of lines in RAWXYZ format.
39
40 Return Structure object or raise StructureFormatError.
41 """
42 linefields = [l.split() for l in lines]
43
44 stru = Structure()
45
46 start = 0
47 for field in linefields:
48 if len(field) == 0 or field[0] == "#":
49 start += 1
50 else:
51 break
52
53 stop = len(lines)
54 while stop > start and len(linefields[stop-1]) == 0:
55 stop -= 1
56
57 if start >= stop:
58 return stru
59
60
61 floatfields = [ isfloat(f) for f in linefields[start] ]
62 nfields = len(linefields[start])
63 if nfields not in (3, 4):
64 emsg = ("%d: invalid RAWXYZ format, expected 3 or 4 columns" %
65 (start + 1))
66 raise StructureFormatError(emsg)
67 if floatfields[:3] == [True, True, True]:
68 el_idx, x_idx = (None, 0)
69 elif floatfields[:4] == [False, True, True, True]:
70 el_idx, x_idx = (0, 1)
71 else:
72 emsg = "%d: invalid RAWXYZ format" % (start + 1)
73 raise StructureFormatError(emsg)
74
75 try:
76 p_nl = start
77 for fields in linefields[start:] :
78 p_nl += 1
79 if fields == []:
80 continue
81 elif len(fields) != nfields:
82 emsg = ('%d: all lines must have ' +
83 'the same number of columns') % p_nl
84 raise StructureFormatError, emsg
85 element = el_idx is not None and fields[el_idx] or ""
86 xyz = [ float(f) for f in fields[x_idx:x_idx+3] ]
87 if len(xyz) == 2:
88 xyz.append(0.0)
89 stru.addNewAtom(element, xyz=xyz)
90 except ValueError:
91 emsg = "%d: invalid number" % p_nl
92 exc_type, exc_value, exc_traceback = sys.exc_info()
93 raise StructureFormatError, emsg, exc_traceback
94 return stru
95
96
98 """Convert Structure stru to a list of lines in XYZ format.
99
100 Return list of strings.
101 """
102 lines = []
103 for a in stru:
104 rc = a.xyz_cartn
105 s = "%s %g %g %g" % (a.element, rc[0], rc[1], rc[2])
106 lines.append(s.lstrip())
107 return lines
108
109
110
111
112
113
116
117
118