pdb-bfactor 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pdb_bfactor/__init__.py +26 -0
- pdb_bfactor/cli.py +107 -0
- pdb_bfactor/core.py +364 -0
- pdb_bfactor-0.1.0.dist-info/METADATA +87 -0
- pdb_bfactor-0.1.0.dist-info/RECORD +9 -0
- pdb_bfactor-0.1.0.dist-info/WHEEL +5 -0
- pdb_bfactor-0.1.0.dist-info/entry_points.txt +2 -0
- pdb_bfactor-0.1.0.dist-info/licenses/LICENSE +21 -0
- pdb_bfactor-0.1.0.dist-info/top_level.txt +1 -0
pdb_bfactor/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from .core import (
|
|
2
|
+
PdbBfactorError,
|
|
3
|
+
combine_pdb_files,
|
|
4
|
+
fasta_to_seqres,
|
|
5
|
+
load_score_table,
|
|
6
|
+
map_bfactors,
|
|
7
|
+
map_cif_bfactors,
|
|
8
|
+
map_pdb_bfactors,
|
|
9
|
+
pdb_to_fasta,
|
|
10
|
+
swap_pdb_chains,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"__version__",
|
|
17
|
+
"PdbBfactorError",
|
|
18
|
+
"combine_pdb_files",
|
|
19
|
+
"fasta_to_seqres",
|
|
20
|
+
"load_score_table",
|
|
21
|
+
"map_bfactors",
|
|
22
|
+
"map_cif_bfactors",
|
|
23
|
+
"map_pdb_bfactors",
|
|
24
|
+
"pdb_to_fasta",
|
|
25
|
+
"swap_pdb_chains",
|
|
26
|
+
]
|
pdb_bfactor/cli.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from typing import Optional, Sequence
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
from .core import (
|
|
9
|
+
PdbBfactorError,
|
|
10
|
+
combine_pdb_files,
|
|
11
|
+
fasta_to_seqres,
|
|
12
|
+
load_score_table,
|
|
13
|
+
map_bfactors,
|
|
14
|
+
pdb_to_fasta,
|
|
15
|
+
swap_pdb_chains,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
20
|
+
ap = argparse.ArgumentParser(
|
|
21
|
+
prog="pdb-bfactor",
|
|
22
|
+
description="Coordinate utilities for PDB/mmCIF B-factor projection, chain permutation, complex merging, and SEQRES conversion.",
|
|
23
|
+
)
|
|
24
|
+
ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
25
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
26
|
+
|
|
27
|
+
p_map = sub.add_parser("map", help="Project per-residue scores into PDB or mmCIF B-factors")
|
|
28
|
+
p_map.add_argument("-i", "--input", required=True, help="Input .pdb or .cif/.mmcif file")
|
|
29
|
+
p_map.add_argument("-s", "--scores", required=True, help="Input CSV, TSV, whitespace, or ConSurf score file")
|
|
30
|
+
p_map.add_argument("-o", "--output", required=True, help="Output coordinate file")
|
|
31
|
+
p_map.add_argument("--pos-col", default=None, help="Residue number column name")
|
|
32
|
+
p_map.add_argument("--score-col", default=None, help="Score column name")
|
|
33
|
+
p_map.add_argument("--chain", default=None, help="Restrict mapping to one chain ID")
|
|
34
|
+
p_map.add_argument("--default", type=float, default=None, help="Fallback B-factor for unmapped residues")
|
|
35
|
+
p_map.add_argument("--consurf", action="store_true", help="Parse ConSurf grades text format")
|
|
36
|
+
|
|
37
|
+
p_swap = sub.add_parser("swap-chains", help="Swap or permute chain IDs across multimer PDB coordinates")
|
|
38
|
+
p_swap.add_argument("-i", "--input", required=True, help="Input PDB file")
|
|
39
|
+
p_swap.add_argument("-o", "--output", required=True, help="Output PDB file")
|
|
40
|
+
p_swap.add_argument("--perm", default=None, help="Comma-separated source chain order, e.g. B,A or C,A,B")
|
|
41
|
+
p_swap.add_argument("--renumber-residues", action="store_true", help="Renumber residues sequentially across output")
|
|
42
|
+
|
|
43
|
+
p_comb = sub.add_parser("combine", help="Merge protein, nucleic acid, or ligand PDB files")
|
|
44
|
+
p_comb.add_argument("-i", "--inputs", nargs="+", required=True, help="Two or more input PDB files")
|
|
45
|
+
p_comb.add_argument("-o", "--output", required=True, help="Output merged PDB file")
|
|
46
|
+
p_comb.add_argument("--chains", default=None, help="Comma-separated chain IDs for each input, e.g. A,B")
|
|
47
|
+
|
|
48
|
+
p_seq = sub.add_parser("seqres", help="Extract FASTA from PDB or convert FASTA to PDB SEQRES lines")
|
|
49
|
+
p_seq.add_argument("-i", "--input", required=True, help="Input PDB or FASTA file")
|
|
50
|
+
p_seq.add_argument("-o", "--output", required=True, help="Output FASTA or SEQRES text file")
|
|
51
|
+
p_seq.add_argument("--to-seqres", action="store_true", help="Convert FASTA input into PDB SEQRES header records")
|
|
52
|
+
p_seq.add_argument("--chain", default="A", help="Chain ID when writing SEQRES [default: A]")
|
|
53
|
+
return ap
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main(argv: Optional[Sequence[str]] = None) -> None:
|
|
57
|
+
ap = build_parser()
|
|
58
|
+
args = ap.parse_args(argv)
|
|
59
|
+
try:
|
|
60
|
+
if args.cmd == "map":
|
|
61
|
+
scores = load_score_table(
|
|
62
|
+
args.scores,
|
|
63
|
+
pos_col=args.pos_col,
|
|
64
|
+
score_col=args.score_col,
|
|
65
|
+
consurf=args.consurf,
|
|
66
|
+
)
|
|
67
|
+
n_atoms = map_bfactors(
|
|
68
|
+
args.input,
|
|
69
|
+
args.output,
|
|
70
|
+
scores,
|
|
71
|
+
chain=args.chain,
|
|
72
|
+
default_value=args.default,
|
|
73
|
+
)
|
|
74
|
+
print(f"Updated {n_atoms} atoms across {len(scores)} scored positions -> {args.output}")
|
|
75
|
+
elif args.cmd == "swap-chains":
|
|
76
|
+
perm = [x.strip() for x in args.perm.split(",") if x.strip()] if args.perm else None
|
|
77
|
+
n_atoms = swap_pdb_chains(
|
|
78
|
+
args.input,
|
|
79
|
+
args.output,
|
|
80
|
+
order=perm,
|
|
81
|
+
renumber_residues=args.renumber_residues,
|
|
82
|
+
)
|
|
83
|
+
print(f"Wrote {n_atoms} atoms -> {args.output}")
|
|
84
|
+
elif args.cmd == "combine":
|
|
85
|
+
chains = [x.strip() for x in args.chains.split(",") if x.strip()] if args.chains else None
|
|
86
|
+
n_atoms = combine_pdb_files(args.inputs, args.output, chain_ids=chains)
|
|
87
|
+
print(f"Merged {len(args.inputs)} files ({n_atoms} atoms) -> {args.output}")
|
|
88
|
+
elif args.cmd == "seqres":
|
|
89
|
+
if args.to_seqres:
|
|
90
|
+
with open(args.input, encoding="utf-8", errors="replace") as fh:
|
|
91
|
+
seq = "".join(ln.strip() for ln in fh if ln.strip() and not ln.startswith(">"))
|
|
92
|
+
text = fasta_to_seqres(seq, chain=args.chain)
|
|
93
|
+
with open(args.output, "w", encoding="utf-8") as fh:
|
|
94
|
+
fh.write(text)
|
|
95
|
+
else:
|
|
96
|
+
records = pdb_to_fasta(args.input)
|
|
97
|
+
with open(args.output, "w", encoding="utf-8") as fh:
|
|
98
|
+
for hdr, seq in records:
|
|
99
|
+
fh.write(f">{hdr}\n{seq}\n")
|
|
100
|
+
print(f"Wrote {args.output}")
|
|
101
|
+
except (PdbBfactorError, OSError) as exc:
|
|
102
|
+
print(f"[pdb-bfactor] Error: {exc}", file=sys.stderr)
|
|
103
|
+
sys.exit(1)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
main()
|
pdb_bfactor/core.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
THREE_TO_ONE = {
|
|
10
|
+
"ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C",
|
|
11
|
+
"GLN": "Q", "GLU": "E", "GLY": "G", "HIS": "H", "ILE": "I",
|
|
12
|
+
"LEU": "L", "LYS": "K", "MET": "M", "PHE": "F", "PRO": "P",
|
|
13
|
+
"SER": "S", "THR": "T", "TRP": "W", "TYR": "Y", "VAL": "V",
|
|
14
|
+
"MSE": "M", "SEC": "U", "PYL": "O",
|
|
15
|
+
}
|
|
16
|
+
ONE_TO_THREE = {v: k for k, v in THREE_TO_ONE.items() if k != "MSE"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PdbBfactorError(ValueError):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_score_table(
|
|
24
|
+
path: str,
|
|
25
|
+
pos_col: Optional[str] = None,
|
|
26
|
+
score_col: Optional[str] = None,
|
|
27
|
+
consurf: bool = False,
|
|
28
|
+
) -> Dict[int, float]:
|
|
29
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
30
|
+
raw_lines = [ln.rstrip("\r\n") for ln in fh if ln.strip() and not ln.lstrip().startswith("#")]
|
|
31
|
+
|
|
32
|
+
if not raw_lines:
|
|
33
|
+
raise PdbBfactorError(f"Empty score file: {path}")
|
|
34
|
+
|
|
35
|
+
if consurf:
|
|
36
|
+
scores: Dict[int, float] = {}
|
|
37
|
+
for ln in raw_lines:
|
|
38
|
+
parts = ln.split()
|
|
39
|
+
if len(parts) >= 4 and parts[0].isdigit():
|
|
40
|
+
cleaned = re.sub(r"[^0-9.\-+]", "", parts[3])
|
|
41
|
+
if cleaned:
|
|
42
|
+
try:
|
|
43
|
+
scores[int(parts[0])] = float(cleaned)
|
|
44
|
+
except ValueError:
|
|
45
|
+
continue
|
|
46
|
+
if not scores:
|
|
47
|
+
raise PdbBfactorError(f"No ConSurf grade rows parsed from {path}")
|
|
48
|
+
return scores
|
|
49
|
+
|
|
50
|
+
first = raw_lines[0]
|
|
51
|
+
delim = "\t" if "\t" in first else ("," if "," in first else None)
|
|
52
|
+
|
|
53
|
+
if delim is None:
|
|
54
|
+
scores = {}
|
|
55
|
+
for ln in raw_lines:
|
|
56
|
+
parts = ln.split()
|
|
57
|
+
if len(parts) >= 2 and parts[0].lstrip("+-").isdigit():
|
|
58
|
+
try:
|
|
59
|
+
scores[int(parts[0])] = float(parts[1])
|
|
60
|
+
except ValueError:
|
|
61
|
+
continue
|
|
62
|
+
if scores:
|
|
63
|
+
return scores
|
|
64
|
+
raise PdbBfactorError(f"Could not parse whitespace score table: {path}")
|
|
65
|
+
|
|
66
|
+
reader = csv.DictReader(raw_lines, delimiter=delim)
|
|
67
|
+
fields = reader.fieldnames or []
|
|
68
|
+
pcol = pos_col
|
|
69
|
+
if pcol is None:
|
|
70
|
+
for cand in ("pos", "position", "resseq", "residue", "ResNum", "Position", "POS"):
|
|
71
|
+
if cand in fields:
|
|
72
|
+
pcol = cand
|
|
73
|
+
break
|
|
74
|
+
if pcol is None and fields:
|
|
75
|
+
pcol = fields[0]
|
|
76
|
+
|
|
77
|
+
scol = score_col
|
|
78
|
+
if scol is None:
|
|
79
|
+
for cand in ("score", "bfactor", "value", "conservation", "dcs", "rcs", "grade", "Score"):
|
|
80
|
+
if cand in fields and cand != pcol:
|
|
81
|
+
scol = cand
|
|
82
|
+
break
|
|
83
|
+
if scol is None and len(fields) >= 2:
|
|
84
|
+
scol = fields[1]
|
|
85
|
+
|
|
86
|
+
if not pcol or not scol or pcol not in fields or scol not in fields:
|
|
87
|
+
raise PdbBfactorError(f"Columns ({pcol!r}, {scol!r}) not found in {fields}")
|
|
88
|
+
|
|
89
|
+
scores = {}
|
|
90
|
+
for row in reader:
|
|
91
|
+
p_raw = (row.get(pcol) or "").strip()
|
|
92
|
+
s_raw = (row.get(scol) or "").strip()
|
|
93
|
+
if not p_raw or not s_raw or s_raw in ("NA", "NaN", "nan"):
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
scores[int(float(p_raw))] = float(s_raw)
|
|
97
|
+
except ValueError:
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
if not scores:
|
|
101
|
+
raise PdbBfactorError(f"No numeric (position, score) pairs read from {path}")
|
|
102
|
+
return scores
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def map_pdb_bfactors(
|
|
106
|
+
input_pdb: str,
|
|
107
|
+
output_pdb: str,
|
|
108
|
+
scores: Dict[int, float],
|
|
109
|
+
chain: Optional[str] = None,
|
|
110
|
+
default_value: Optional[float] = None,
|
|
111
|
+
include_hetatm: bool = False,
|
|
112
|
+
) -> int:
|
|
113
|
+
rec_types = ("ATOM ", "HETATM") if include_hetatm else ("ATOM ",)
|
|
114
|
+
updated_atoms = 0
|
|
115
|
+
out_lines: List[str] = []
|
|
116
|
+
|
|
117
|
+
with open(input_pdb, encoding="utf-8", errors="replace") as fh:
|
|
118
|
+
for line in fh:
|
|
119
|
+
if line.startswith(rec_types) and len(line) >= 66:
|
|
120
|
+
ch = line[21].strip()
|
|
121
|
+
if chain is None or ch == chain:
|
|
122
|
+
try:
|
|
123
|
+
resseq = int(line[22:26].strip())
|
|
124
|
+
except ValueError:
|
|
125
|
+
out_lines.append(line)
|
|
126
|
+
continue
|
|
127
|
+
val = scores.get(resseq, default_value)
|
|
128
|
+
if val is not None:
|
|
129
|
+
bf_str = f"{val:6.2f}"
|
|
130
|
+
if len(bf_str) > 6:
|
|
131
|
+
bf_str = f"{val:6.1f}"[:6]
|
|
132
|
+
line = line[:60] + bf_str + line[66:]
|
|
133
|
+
updated_atoms += 1
|
|
134
|
+
out_lines.append(line)
|
|
135
|
+
|
|
136
|
+
with open(output_pdb, "w", encoding="utf-8") as fh:
|
|
137
|
+
fh.writelines(out_lines)
|
|
138
|
+
return updated_atoms
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def map_cif_bfactors(
|
|
142
|
+
input_cif: str,
|
|
143
|
+
output_cif: str,
|
|
144
|
+
scores: Dict[int, float],
|
|
145
|
+
chain: Optional[str] = None,
|
|
146
|
+
default_value: Optional[float] = None,
|
|
147
|
+
) -> int:
|
|
148
|
+
with open(input_cif, encoding="utf-8", errors="replace") as fh:
|
|
149
|
+
lines = fh.readlines()
|
|
150
|
+
|
|
151
|
+
out_lines: List[str] = []
|
|
152
|
+
i = 0
|
|
153
|
+
n = len(lines)
|
|
154
|
+
updated_atoms = 0
|
|
155
|
+
|
|
156
|
+
while i < n:
|
|
157
|
+
if lines[i].strip() == "loop_" and i + 1 < n and lines[i + 1].lstrip().startswith("_atom_site."):
|
|
158
|
+
out_lines.append(lines[i])
|
|
159
|
+
i += 1
|
|
160
|
+
headers: List[str] = []
|
|
161
|
+
while i < n and lines[i].lstrip().startswith("_atom_site."):
|
|
162
|
+
headers.append(lines[i].strip())
|
|
163
|
+
out_lines.append(lines[i])
|
|
164
|
+
i += 1
|
|
165
|
+
|
|
166
|
+
col_map = {h: idx for idx, h in enumerate(headers)}
|
|
167
|
+
b_idx = col_map.get("_atom_site.B_iso_or_equiv")
|
|
168
|
+
seq_idx = col_map.get("_atom_site.label_seq_id")
|
|
169
|
+
if seq_idx is None:
|
|
170
|
+
seq_idx = col_map.get("_atom_site.auth_seq_id")
|
|
171
|
+
ch_idx = col_map.get("_atom_site.auth_asym_id")
|
|
172
|
+
if ch_idx is None:
|
|
173
|
+
ch_idx = col_map.get("_atom_site.label_asym_id")
|
|
174
|
+
grp_idx = col_map.get("_atom_site.group_PDB")
|
|
175
|
+
|
|
176
|
+
while i < n:
|
|
177
|
+
stripped = lines[i].strip()
|
|
178
|
+
if not stripped or stripped.startswith("#") or stripped == "loop_" or stripped.startswith("_"):
|
|
179
|
+
break
|
|
180
|
+
tokens = stripped.split()
|
|
181
|
+
if (
|
|
182
|
+
b_idx is not None
|
|
183
|
+
and seq_idx is not None
|
|
184
|
+
and len(tokens) == len(headers)
|
|
185
|
+
and (grp_idx is None or tokens[grp_idx] == "ATOM")
|
|
186
|
+
):
|
|
187
|
+
ch_ok = True if (chain is None or ch_idx is None) else (tokens[ch_idx] == chain)
|
|
188
|
+
if ch_ok and tokens[seq_idx].lstrip("+-").isdigit():
|
|
189
|
+
resseq = int(tokens[seq_idx])
|
|
190
|
+
val = scores.get(resseq, default_value)
|
|
191
|
+
if val is not None:
|
|
192
|
+
tokens[b_idx] = f"{val:.2f}"
|
|
193
|
+
lines[i] = " ".join(tokens) + "\n"
|
|
194
|
+
updated_atoms += 1
|
|
195
|
+
out_lines.append(lines[i])
|
|
196
|
+
i += 1
|
|
197
|
+
continue
|
|
198
|
+
|
|
199
|
+
out_lines.append(lines[i])
|
|
200
|
+
i += 1
|
|
201
|
+
|
|
202
|
+
with open(output_cif, "w", encoding="utf-8") as fh:
|
|
203
|
+
fh.writelines(out_lines)
|
|
204
|
+
return updated_atoms
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def map_bfactors(
|
|
208
|
+
input_path: str,
|
|
209
|
+
output_path: str,
|
|
210
|
+
scores: Dict[int, float],
|
|
211
|
+
chain: Optional[str] = None,
|
|
212
|
+
default_value: Optional[float] = None,
|
|
213
|
+
) -> int:
|
|
214
|
+
ext = os.path.splitext(input_path)[1].lower()
|
|
215
|
+
if ext in (".cif", ".mmcif"):
|
|
216
|
+
return map_cif_bfactors(input_path, output_path, scores, chain=chain, default_value=default_value)
|
|
217
|
+
return map_pdb_bfactors(input_path, output_path, scores, chain=chain, default_value=default_value)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def swap_pdb_chains(
|
|
221
|
+
input_pdb: str,
|
|
222
|
+
output_pdb: str,
|
|
223
|
+
order: Optional[Sequence[str]] = None,
|
|
224
|
+
mapping: Optional[Dict[str, str]] = None,
|
|
225
|
+
renumber_residues: bool = False,
|
|
226
|
+
) -> int:
|
|
227
|
+
with open(input_pdb, encoding="utf-8", errors="replace") as fh:
|
|
228
|
+
lines = fh.readlines()
|
|
229
|
+
|
|
230
|
+
by_chain: Dict[str, List[str]] = {}
|
|
231
|
+
seen_chains: List[str] = []
|
|
232
|
+
for ln in lines:
|
|
233
|
+
if ln.startswith(("ATOM ", "HETATM")) and len(ln) >= 26:
|
|
234
|
+
ch = ln[21]
|
|
235
|
+
if ch not in by_chain:
|
|
236
|
+
by_chain[ch] = []
|
|
237
|
+
seen_chains.append(ch)
|
|
238
|
+
by_chain[ch].append(ln)
|
|
239
|
+
|
|
240
|
+
if not seen_chains:
|
|
241
|
+
raise PdbBfactorError(f"No ATOM/HETATM records found in {input_pdb}")
|
|
242
|
+
|
|
243
|
+
if mapping is not None:
|
|
244
|
+
source_to_target = [(src, mapping[src]) for src in seen_chains if src in mapping]
|
|
245
|
+
elif order is not None:
|
|
246
|
+
if len(order) > len(seen_chains):
|
|
247
|
+
raise PdbBfactorError(f"Requested order {order} exceeds chains present {seen_chains}")
|
|
248
|
+
target_labels = seen_chains[: len(order)]
|
|
249
|
+
source_to_target = list(zip(order, target_labels))
|
|
250
|
+
else:
|
|
251
|
+
if len(seen_chains) == 2:
|
|
252
|
+
source_to_target = [(seen_chains[1], seen_chains[0]), (seen_chains[0], seen_chains[1])]
|
|
253
|
+
elif len(seen_chains) == 3:
|
|
254
|
+
source_to_target = [
|
|
255
|
+
(seen_chains[2], seen_chains[0]),
|
|
256
|
+
(seen_chains[0], seen_chains[1]),
|
|
257
|
+
(seen_chains[1], seen_chains[2]),
|
|
258
|
+
]
|
|
259
|
+
else:
|
|
260
|
+
raise PdbBfactorError("Specify --perm (for example B,A) when input does not have 2 or 3 chains")
|
|
261
|
+
|
|
262
|
+
serial = 1
|
|
263
|
+
res_counter = 0
|
|
264
|
+
out_lines: List[str] = []
|
|
265
|
+
|
|
266
|
+
for src_ch, dst_ch in source_to_target:
|
|
267
|
+
if src_ch not in by_chain:
|
|
268
|
+
raise PdbBfactorError(f"Chain {src_ch!r} not found in {seen_chains}")
|
|
269
|
+
prev_res_key: Optional[str] = None
|
|
270
|
+
for ln in by_chain[src_ch]:
|
|
271
|
+
res_key = ln[22:27]
|
|
272
|
+
if renumber_residues:
|
|
273
|
+
if res_key != prev_res_key:
|
|
274
|
+
res_counter += 1
|
|
275
|
+
prev_res_key = res_key
|
|
276
|
+
res_field = f"{res_counter:>4d} "
|
|
277
|
+
else:
|
|
278
|
+
res_field = ln[22:27]
|
|
279
|
+
|
|
280
|
+
rebuilt = f"{ln[:6]}{serial:>5d}{ln[11:21]}{dst_ch[0]}{res_field}{ln[27:]}"
|
|
281
|
+
out_lines.append(rebuilt)
|
|
282
|
+
serial += 1
|
|
283
|
+
out_lines.append("TER\n")
|
|
284
|
+
|
|
285
|
+
out_lines.append("END\n")
|
|
286
|
+
with open(output_pdb, "w", encoding="utf-8") as fh:
|
|
287
|
+
fh.writelines(out_lines)
|
|
288
|
+
return serial - 1
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def combine_pdb_files(
|
|
292
|
+
inputs: Sequence[str],
|
|
293
|
+
output_pdb: str,
|
|
294
|
+
chain_ids: Optional[Sequence[str]] = None,
|
|
295
|
+
) -> int:
|
|
296
|
+
if len(inputs) < 2:
|
|
297
|
+
raise PdbBfactorError("Provide at least two coordinate files to combine")
|
|
298
|
+
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
299
|
+
labels = list(chain_ids) if chain_ids else [alphabet[i] for i in range(len(inputs))]
|
|
300
|
+
if len(labels) != len(inputs):
|
|
301
|
+
raise PdbBfactorError("Number of --chains labels must match number of input files")
|
|
302
|
+
|
|
303
|
+
serial = 1
|
|
304
|
+
out_lines: List[str] = []
|
|
305
|
+
for path, ch in zip(inputs, labels):
|
|
306
|
+
res_num = 0
|
|
307
|
+
prev_origin: Optional[Tuple[str, str]] = None
|
|
308
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
309
|
+
for ln in fh:
|
|
310
|
+
if ln.startswith(("ATOM ", "HETATM")) and len(ln) >= 27:
|
|
311
|
+
origin = (ln[21], ln[22:27])
|
|
312
|
+
if origin != prev_origin:
|
|
313
|
+
res_num += 1
|
|
314
|
+
prev_origin = origin
|
|
315
|
+
out_lines.append(f"{ln[:6]}{serial:>5d}{ln[11:21]}{ch[0]}{res_num:>4d} {ln[27:]}")
|
|
316
|
+
serial += 1
|
|
317
|
+
out_lines.append("TER\n")
|
|
318
|
+
out_lines.append("END\n")
|
|
319
|
+
|
|
320
|
+
with open(output_pdb, "w", encoding="utf-8") as fh:
|
|
321
|
+
fh.writelines(out_lines)
|
|
322
|
+
return serial - 1
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def pdb_to_fasta(input_pdb: str) -> List[Tuple[str, str]]:
|
|
326
|
+
chains_seqres: Dict[str, List[str]] = {}
|
|
327
|
+
chains_atom: Dict[str, List[str]] = {}
|
|
328
|
+
seen_res: Dict[str, set] = {}
|
|
329
|
+
|
|
330
|
+
with open(input_pdb, encoding="utf-8", errors="replace") as fh:
|
|
331
|
+
for ln in fh:
|
|
332
|
+
if ln.startswith("SEQRES") and len(ln) >= 19:
|
|
333
|
+
ch = ln[11].strip() or "A"
|
|
334
|
+
chains_seqres.setdefault(ch, [])
|
|
335
|
+
for res3 in ln[19:].split():
|
|
336
|
+
chains_seqres[ch].append(THREE_TO_ONE.get(res3.upper(), "X"))
|
|
337
|
+
elif ln.startswith("ATOM ") and len(ln) >= 27:
|
|
338
|
+
altloc = ln[16]
|
|
339
|
+
if altloc not in (" ", "A", "1"):
|
|
340
|
+
continue
|
|
341
|
+
ch = ln[21].strip() or "A"
|
|
342
|
+
res_id = ln[22:27]
|
|
343
|
+
seen_res.setdefault(ch, set())
|
|
344
|
+
if res_id not in seen_res[ch]:
|
|
345
|
+
seen_res[ch].add(res_id)
|
|
346
|
+
res3 = ln[17:20].strip().upper()
|
|
347
|
+
chains_atom.setdefault(ch, []).append(THREE_TO_ONE.get(res3, "X"))
|
|
348
|
+
|
|
349
|
+
source = chains_seqres if chains_seqres else chains_atom
|
|
350
|
+
base = os.path.splitext(os.path.basename(input_pdb))[0]
|
|
351
|
+
return [(f"{base}_chain_{ch}", "".join(res)) for ch, res in source.items()]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def fasta_to_seqres(sequence: str, chain: str = "A") -> str:
|
|
355
|
+
clean = re.sub(r"\s+", "", sequence).upper()
|
|
356
|
+
three = [ONE_TO_THREE.get(aa, "UNK") for aa in clean]
|
|
357
|
+
total = len(three)
|
|
358
|
+
lines: List[str] = []
|
|
359
|
+
ser = 1
|
|
360
|
+
for i in range(0, total, 13):
|
|
361
|
+
chunk = " ".join(f"{r:>3s}" for r in three[i : i + 13])
|
|
362
|
+
lines.append(f"SEQRES {ser:>3d} {chain[0]} {total:>4d} {chunk}\n")
|
|
363
|
+
ser += 1
|
|
364
|
+
return "".join(lines)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pdb-bfactor
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency CLI and Python library for PDB/mmCIF B-factor score projection, multimer chain permutation, protein-RNA complex merging, and SEQRES conversion
|
|
5
|
+
Author-email: Taner Karagöl <karagolt@mit.edu>, Alper Karagöl <akaragol@mit.edu>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.tanerkaragol.com/pdb-tools
|
|
8
|
+
Project-URL: Repository, https://github.com/karagol-taner/PDB-conservation-BFactor
|
|
9
|
+
Keywords: pdb,mmcif,b-factor,pymol,chimerax,alphafold,structural-biology,conservation
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
20
|
+
Requires-Python: >=3.8
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# pdb-bfactor
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/pdb-bfactor/) [](https://opensource.org/licenses/MIT)
|
|
28
|
+
|
|
29
|
+
Zero-dependency command-line utility and Python library for mapping per-residue scores (ConSurf conservation grades, RMSF, AlphaMissense, deep mutational scan values, ADEPT, or GapCheck tables) onto PDB and mmCIF B-factor columns for 3D visualization in PyMOL, ChimeraX, and 3Dmol.js, alongside multimer chain permutation, protein-nucleic acid coordinate merging, and FASTA/SEQRES conversion.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install pdb-bfactor
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Command-Line Usage
|
|
38
|
+
|
|
39
|
+
### 1. Project CSV, TSV, or ConSurf Scores into PDB or mmCIF B-Factors
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pdb-bfactor map -i structure.pdb -s scores.csv -o colored.pdb
|
|
43
|
+
pdb-bfactor map -i model.cif -s scores.csv --pos-col position --score-col dcs -o colored.cif
|
|
44
|
+
pdb-bfactor map -i structure.pdb -s consurf_grades.txt --consurf -o consurf_colored.pdb
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### 2. Swap or Permute Multimer Chains (Dimers, Trimers, or Arbitrary Oligomers)
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pdb-bfactor swap-chains -i dimer.pdb -o swapped_dimer.pdb --perm B,A
|
|
51
|
+
pdb-bfactor swap-chains -i trimer.pdb -o swapped_trimer.pdb --perm C,A,B --renumber-residues
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 3. Combine Protein, RNA, DNA, or Ligand PDB Files
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pdb-bfactor combine -i protein.pdb rna.pdb -o complex.pdb --chains A,B
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 4. Convert Between PDB Coordinates and FASTA or SEQRES Records
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pdb-bfactor seqres -i structure.pdb -o sequence.fasta
|
|
64
|
+
pdb-bfactor seqres -i sequence.fasta -o header_seqres.pdb --to-seqres --chain A
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Python API
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from pdb_bfactor import (
|
|
71
|
+
load_score_table,
|
|
72
|
+
map_bfactors,
|
|
73
|
+
swap_pdb_chains,
|
|
74
|
+
combine_pdb_files,
|
|
75
|
+
pdb_to_fasta,
|
|
76
|
+
fasta_to_seqres,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
scores = load_score_table("scores.csv", pos_col="pos", score_col="score")
|
|
80
|
+
map_bfactors("input.pdb", "colored.pdb", scores, chain="A", default_value=0.0)
|
|
81
|
+
swap_pdb_chains("dimer.pdb", "swapped.pdb", mapping={"A": "B", "B": "A"})
|
|
82
|
+
combine_pdb_files(["protein.pdb", "rna.pdb"], "complex.pdb", chain_ids=["A", "B"])
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
Released under the MIT License.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
pdb_bfactor/__init__.py,sha256=zdrTRqKZgCyr51zLVrt3djaw_SvVCt94eV43N9wlvPo,473
|
|
2
|
+
pdb_bfactor/cli.py,sha256=Lb8gTgEaUZlqzb82XRFPGab194J9_gIMy-1DaSs2uHE,5188
|
|
3
|
+
pdb_bfactor/core.py,sha256=Nam6sQT9uJZyoMinBK9OYITjo549xrw1nOOOizlkWpg,13234
|
|
4
|
+
pdb_bfactor-0.1.0.dist-info/licenses/LICENSE,sha256=TwnwSMmRa_btasSVj09d8LP5VpaoR0n_l9Y85DesrGo,1087
|
|
5
|
+
pdb_bfactor-0.1.0.dist-info/METADATA,sha256=2O9vIQoEAvpWirR_dD1UNjDxHFh_hmeTk7R1spo1NGk,3343
|
|
6
|
+
pdb_bfactor-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
pdb_bfactor-0.1.0.dist-info/entry_points.txt,sha256=RD-oeaN0ttryNPXzkqUZNAAzROLH8rSgU3y57_m3ZJU,53
|
|
8
|
+
pdb_bfactor-0.1.0.dist-info/top_level.txt,sha256=8Va-VmGwhh3re_rLY0cqorGvdAxLEuqw2UdwAw_ryGk,12
|
|
9
|
+
pdb_bfactor-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Taner Karagöl, Alper Karagöl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pdb_bfactor
|