Coverage for ase/io/proteindatabank.py: 91.03%
145 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""Module to read and write atoms in PDB file format.
3See::
5 http://www.wwpdb.org/documentation/file-format
7Note: The PDB format saves cell lengths and angles; hence the absolute
8orientation is lost when saving. Saving and loading a file will
9conserve the scaled positions, not the absolute ones.
10"""
12import warnings
14import numpy as np
16from ase.atoms import Atoms
17from ase.cell import Cell
18from ase.io.espresso import label_to_symbol
19from ase.utils import reader, writer
22def read_atom_line(line_full):
23 """
24 Read atom line from pdb format
25 HETATM 1 H14 ORTE 0 6.301 0.693 1.919 1.00 0.00 H
26 """
27 line = line_full.rstrip('\n')
28 type_atm = line[0:6]
29 if type_atm == 'ATOM ' or type_atm == 'HETATM':
30 name = line[12:16].strip()
32 altloc = line[16]
33 resname = line[17:21].strip()
34 # chainid = line[21] # Not used
36 seq = line[22:26].split()
37 if len(seq) == 0:
38 resseq = 1
39 else:
40 resseq = int(seq[0]) # sequence identifier
41 # icode = line[26] # insertion code, not used
43 # atomic coordinates
44 try:
45 coord = np.array(
46 [float(line[30:38]), float(line[38:46]), float(line[46:54])],
47 dtype=np.float64,
48 )
49 except ValueError:
50 raise ValueError('Invalid or missing coordinate(s)')
52 # occupancy & B factor
53 try:
54 occupancy = float(line[54:60])
55 except ValueError:
56 occupancy = None # Rather than arbitrary zero or one
58 if occupancy is not None and occupancy < 0:
59 warnings.warn('Negative occupancy in one or more atoms')
61 try:
62 bfactor = float(line[60:66])
63 except ValueError:
64 # The PDB use a default of zero if the data is missing
65 bfactor = 0.0
67 # segid = line[72:76] # not used
68 symbol = line[76:78].strip().upper()
70 else:
71 raise ValueError('Only ATOM and HETATM supported')
73 return symbol, name, altloc, resname, coord, occupancy, bfactor, resseq
76@reader
77def read_proteindatabank(fileobj, index=-1, read_arrays=True):
78 """Read PDB files."""
79 images = []
80 orig = np.identity(3)
81 trans = np.zeros(3)
82 occ = []
83 bfactor = []
84 residuenames = []
85 residuenumbers = []
86 atomtypes = []
88 symbols = []
89 positions = []
90 cell = None
91 pbc = None
93 def build_atoms():
94 atoms = Atoms(symbols=symbols, cell=cell, pbc=pbc, positions=positions)
96 if not read_arrays:
97 return atoms
99 info = {
100 'occupancy': occ,
101 'bfactor': bfactor,
102 'residuenames': residuenames,
103 'atomtypes': atomtypes,
104 'residuenumbers': residuenumbers,
105 }
106 for name, array in info.items():
107 if len(array) == 0:
108 pass
109 elif len(array) != len(atoms):
110 warnings.warn(
111 'Length of {} array, {}, '
112 'different from number of atoms {}'.format(
113 name, len(array), len(atoms)
114 )
115 )
116 else:
117 atoms.set_array(name, np.array(array))
118 return atoms
120 for line in fileobj.readlines():
121 if line.startswith('CRYST1'):
122 cellpar = [
123 float(line[6:15]), # a
124 float(line[15:24]), # b
125 float(line[24:33]), # c
126 float(line[33:40]), # alpha
127 float(line[40:47]), # beta
128 float(line[47:54]),
129 ] # gamma
130 cell = Cell.new(cellpar)
131 pbc = True
132 for c in range(3):
133 if line.startswith('ORIGX' + '123'[c]):
134 orig[c] = [
135 float(line[10:20]),
136 float(line[20:30]),
137 float(line[30:40]),
138 ]
139 trans[c] = float(line[45:55])
141 if line.startswith('ATOM') or line.startswith('HETATM'):
142 # Atom name is arbitrary and does not necessarily
143 # contain the element symbol. The specification
144 # requires the element symbol to be in columns 77+78.
145 # Fall back to Atom name for files that do not follow
146 # the spec, e.g. packmol.
148 # line_info = symbol, name, altloc, resname, coord, occupancy,
149 # bfactor, resseq
150 line_info = read_atom_line(line)
152 try:
153 symbol = label_to_symbol(line_info[0])
154 except (KeyError, IndexError):
155 symbol = label_to_symbol(line_info[1])
157 position = np.dot(orig, line_info[4]) + trans
158 atomtypes.append(line_info[1])
159 residuenames.append(line_info[3])
160 if line_info[5] is not None:
161 occ.append(line_info[5])
162 bfactor.append(line_info[6])
163 residuenumbers.append(line_info[7])
165 symbols.append(symbol)
166 positions.append(position)
168 if line.startswith('END'):
169 # End of configuration reached
170 # According to the latest PDB file format (v3.30),
171 # this line should start with 'ENDMDL' (not 'END'),
172 # but in this way PDB trajectories from e.g. CP2K
173 # are supported (also VMD supports this format).
174 atoms = build_atoms()
175 images.append(atoms)
176 occ = []
177 bfactor = []
178 residuenames = []
179 residuenumbers = []
180 atomtypes = []
181 symbols = []
182 positions = []
183 cell = None
184 pbc = None
186 if len(images) == 0:
187 atoms = build_atoms()
188 images.append(atoms)
189 return images[index]
192@writer
193def write_proteindatabank(fileobj, images, write_arrays=True):
194 """Write images to PDB-file."""
195 rot_t = None
196 if hasattr(images, 'get_positions'):
197 images = [images]
199 # 1234567 123 6789012345678901 89 67 456789012345678901234567 890
200 format = (
201 'ATOM %5d %4s %4s %4d %8.3f%8.3f%8.3f%6.2f%6.2f %2s \n'
202 )
204 # RasMol complains if the atom index exceeds 100000. There might
205 # be a limit of 5 digit numbers in this field.
206 MAXNUM = 100000
208 symbols = images[0].get_chemical_symbols()
209 natoms = len(symbols)
211 for n, atoms in enumerate(images):
212 if atoms.get_pbc().any():
213 currentcell = atoms.get_cell()
214 cellpar = currentcell.cellpar()
215 _, rot_t = currentcell.standard_form()
216 # ignoring Z-value, using P1 since we have all atoms defined
217 # explicitly
218 cellformat = 'CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f P 1\n'
219 fileobj.write(
220 cellformat
221 % (
222 cellpar[0],
223 cellpar[1],
224 cellpar[2],
225 cellpar[3],
226 cellpar[4],
227 cellpar[5],
228 )
229 )
230 fileobj.write('MODEL ' + str(n + 1) + '\n')
231 p = atoms.get_positions()
232 if rot_t is not None:
233 p = p.dot(rot_t.T)
234 occupancy = np.ones(len(atoms))
235 bfactor = np.zeros(len(atoms))
236 residuenames = ['MOL '] * len(atoms)
237 residuenumbers = np.ones(len(atoms))
238 names = atoms.get_chemical_symbols()
239 if write_arrays:
240 if 'occupancy' in atoms.arrays:
241 occupancy = atoms.get_array('occupancy')
242 if 'bfactor' in atoms.arrays:
243 bfactor = atoms.get_array('bfactor')
244 if 'residuenames' in atoms.arrays:
245 residuenames = atoms.get_array('residuenames')
246 if 'residuenumbers' in atoms.arrays:
247 residuenumbers = atoms.get_array('residuenumbers')
248 if 'atomtypes' in atoms.arrays:
249 names = atoms.get_array('atomtypes')
250 for a in range(natoms):
251 x, y, z = p[a]
252 occ = occupancy[a]
253 bf = bfactor[a]
254 resname = residuenames[a].ljust(4)
255 resseq = residuenumbers[a]
256 name = names[a]
257 fileobj.write(
258 format
259 % (
260 (a + 1) % MAXNUM,
261 name,
262 resname,
263 resseq,
264 x,
265 y,
266 z,
267 occ,
268 bf,
269 symbols[a].upper(),
270 )
271 )
272 fileobj.write('ENDMDL\n')