File: pdb_tocif.py

package info (click to toggle)
pdb-tools 2.5.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,636 kB
  • sloc: python: 9,220; makefile: 13
file content (244 lines) | stat: -rw-r--r-- 6,768 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 João Pedro Rodrigues
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Rudimentarily converts the PDB file to mmCIF format.

Will convert only the coordinate section.

Usage:
    python pdb_tocif.py <pdb file>

Example:
    python pdb_tocif.py 1CTF.pdb

This program is part of the `pdb-tools` suite of utilities and should not be
distributed isolatedly. The `pdb-tools` were created to quickly manipulate PDB
files using the terminal, and can be used sequentially, with one tool streaming
data to another. They are based on old FORTRAN77 code that was taking too much
effort to maintain and compile. RIP.
"""

import os
import sys


__author__ = "Joao Rodrigues"
__email__ = "j.p.g.l.m.rodrigues@gmail.com"


def check_input(args):
    """Checks whether to read from stdin/file and validates user input/options.
    """

    # Defaults
    fh = sys.stdin  # file handle

    if not len(args):
        # Reading from pipe with default option
        if sys.stdin.isatty():
            sys.stderr.write(__doc__)
            sys.exit(1)

    elif len(args) == 1:
        if not os.path.isfile(args[0]):
            emsg = 'ERROR!! File not found or not readable: \'{}\'\n'
            sys.stderr.write(emsg.format(args[0]))
            sys.stderr.write(__doc__)
            sys.exit(1)

        fh = open(args[0], 'r')

    else:  # Whatever ...
        emsg = 'ERROR!! Script takes 1 argument, not \'{}\'\n'
        sys.stderr.write(emsg.format(len(args)))
        sys.stderr.write(__doc__)
        sys.exit(1)

    return fh


def pad_line(line):
    """Helper function to pad line to 80 characters in case it is shorter"""
    size_of_line = len(line)
    if size_of_line < 80:
        padding = 80 - size_of_line + 1
        line = line.strip('\n') + ' ' * padding + '\n'
    return line[:81]  # 80 + newline character


def run(fhandle, outname=None):
    """
    Convert a structure in PDB format to mmCIF format.

    This function is a generator.

    Parameters
    ----------
    fhandle : an iterable giving the PDB file line-by-line.

    outname : str
        The base name of the output files. If None is given, tries to
        extract a name from the `.name` attribute of `fhandler`. If
        `fhandler` has no attribute name, assigns `cell`.

    Yields
    ------
    str (line-by-line)
        The structure in mmCIF format.
    """
    _pad_line = pad_line

    # The spacing here is just aesthetic purposes when printing the file
    _a = '{:<6s} {:5d} {:2s} {:6s} {:1s} {:3s} {:3s} {:1s} {:5s} {:1s} '
    _a += '{:10.3f} {:10.3f} {:10.3f} {:10.3f} {:10.3f} {:1s} '
    _a += '{:5s} {:3s} {:1s} {:4s} {:1d}\n'

    yield '# Converted to mmCIF by pdb-tools\n'
    yield '#\n'

    # Headers
    _defname = 'cell'
    if outname is None:
        try:
            fn = fhandle.name
            outname = fn[:-4] if fn != '<stdin>' else _defname
        except AttributeError:
            outname = _defname

    fname_root = os.path.basename(outname)

    yield 'data_{}\n'.format(fname_root)

    yield '#\n'
    yield 'loop_\n'
    yield '_atom_site.group_PDB\n'
    yield '_atom_site.id\n'
    yield '_atom_site.type_symbol\n'
    yield '_atom_site.label_atom_id\n'
    yield '_atom_site.label_alt_id\n'
    yield '_atom_site.label_comp_id\n'
    yield '_atom_site.label_asym_id\n'
    yield '_atom_site.label_entity_id\n'
    yield '_atom_site.label_seq_id\n'
    yield '_atom_site.pdbx_PDB_ins_code\n'
    yield '_atom_site.Cartn_x\n'
    yield '_atom_site.Cartn_y\n'
    yield '_atom_site.Cartn_z\n'
    yield '_atom_site.occupancy\n'
    yield '_atom_site.B_iso_or_equiv\n'
    yield '_atom_site.pdbx_formal_charge\n'
    yield '_atom_site.auth_seq_id\n'
    yield '_atom_site.auth_comp_id\n'
    yield '_atom_site.auth_asym_id\n'
    yield '_atom_site.auth_atom_id\n'
    yield '_atom_site.pdbx_PDB_model_num\n'

    # Coordinate data
    model_no = 1
    serial = 0

    records = (('ATOM', 'HETATM'))
    for line in fhandle:
        if line.startswith(records):
            line = _pad_line(line)

            record = line[0:6].strip()
            serial += 1

            element = line[76:78].strip()
            if not element:
                element = '?'

            atname = line[12:16].strip()
            atname = atname.replace('"', "'")
            if "'" in atname:
                atname = '"{}"'.format(atname)

            altloc = line[16]
            if altloc == ' ':
                altloc = '?'

            resname = line[17:20]
            chainid = line[21]
            if chainid == ' ':
                chainid = '?'

            resnum = line[22:26].strip()
            icode = line[26]
            if icode == ' ':
                icode = '?'

            x = float(line[30:38])
            y = float(line[38:46])
            z = float(line[46:54])

            occ = float(line[54:60])
            bfac = float(line[60:66])

            charge = line[78:80].strip()
            if charge == '':
                charge = '?'

            yield _a.format(record, serial, element, atname, altloc,
                            resname, chainid, '?', resnum, icode, x, y, z, occ,
                            bfac, charge, resnum, resname, chainid, atname,
                            model_no)

        elif line.startswith('ENDMDL'):
            model_no += 1
        else:
            continue

    yield '#'  # close block


convert_to_mmcif = run


def main():
    # Check Input
    pdbfh = check_input(sys.argv[1:])

    # Do the job
    new_cif = run(pdbfh)

    try:
        _buffer = []
        _buffer_size = 5000  # write N lines at a time
        for lineno, line in enumerate(new_cif):
            if not (lineno % _buffer_size):
                sys.stdout.write(''.join(_buffer))
                _buffer = []
            _buffer.append(line)

        sys.stdout.write(''.join(_buffer))
        sys.stdout.flush()
    except IOError:
        # This is here to catch Broken Pipes
        # for example to use 'head' or 'tail' without
        # the error message showing up
        pass

    # last line of the script
    # We can close it even if it is sys.stdin
    pdbfh.close()
    sys.exit(0)


if __name__ == '__main__':
    main()