pdb-bfactor 0.1.0__tar.gz

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.
@@ -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,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
+ [![PyPI version](https://img.shields.io/pypi/v/pdb-bfactor)](https://pypi.org/project/pdb-bfactor/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](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,63 @@
1
+ # pdb-bfactor
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/pdb-bfactor)](https://pypi.org/project/pdb-bfactor/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ 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.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install pdb-bfactor
11
+ ```
12
+
13
+ ## Command-Line Usage
14
+
15
+ ### 1. Project CSV, TSV, or ConSurf Scores into PDB or mmCIF B-Factors
16
+
17
+ ```bash
18
+ pdb-bfactor map -i structure.pdb -s scores.csv -o colored.pdb
19
+ pdb-bfactor map -i model.cif -s scores.csv --pos-col position --score-col dcs -o colored.cif
20
+ pdb-bfactor map -i structure.pdb -s consurf_grades.txt --consurf -o consurf_colored.pdb
21
+ ```
22
+
23
+ ### 2. Swap or Permute Multimer Chains (Dimers, Trimers, or Arbitrary Oligomers)
24
+
25
+ ```bash
26
+ pdb-bfactor swap-chains -i dimer.pdb -o swapped_dimer.pdb --perm B,A
27
+ pdb-bfactor swap-chains -i trimer.pdb -o swapped_trimer.pdb --perm C,A,B --renumber-residues
28
+ ```
29
+
30
+ ### 3. Combine Protein, RNA, DNA, or Ligand PDB Files
31
+
32
+ ```bash
33
+ pdb-bfactor combine -i protein.pdb rna.pdb -o complex.pdb --chains A,B
34
+ ```
35
+
36
+ ### 4. Convert Between PDB Coordinates and FASTA or SEQRES Records
37
+
38
+ ```bash
39
+ pdb-bfactor seqres -i structure.pdb -o sequence.fasta
40
+ pdb-bfactor seqres -i sequence.fasta -o header_seqres.pdb --to-seqres --chain A
41
+ ```
42
+
43
+ ## Python API
44
+
45
+ ```python
46
+ from pdb_bfactor import (
47
+ load_score_table,
48
+ map_bfactors,
49
+ swap_pdb_chains,
50
+ combine_pdb_files,
51
+ pdb_to_fasta,
52
+ fasta_to_seqres,
53
+ )
54
+
55
+ scores = load_score_table("scores.csv", pos_col="pos", score_col="score")
56
+ map_bfactors("input.pdb", "colored.pdb", scores, chain="A", default_value=0.0)
57
+ swap_pdb_chains("dimer.pdb", "swapped.pdb", mapping={"A": "B", "B": "A"})
58
+ combine_pdb_files(["protein.pdb", "rna.pdb"], "complex.pdb", chain_ids=["A", "B"])
59
+ ```
60
+
61
+ ## License
62
+
63
+ Released under the MIT License.
@@ -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
+ ]
@@ -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()
@@ -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
+ [![PyPI version](https://img.shields.io/pypi/v/pdb-bfactor)](https://pypi.org/project/pdb-bfactor/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](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,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ pdb_bfactor/__init__.py
6
+ pdb_bfactor/cli.py
7
+ pdb_bfactor/core.py
8
+ pdb_bfactor.egg-info/PKG-INFO
9
+ pdb_bfactor.egg-info/SOURCES.txt
10
+ pdb_bfactor.egg-info/dependency_links.txt
11
+ pdb_bfactor.egg-info/entry_points.txt
12
+ pdb_bfactor.egg-info/top_level.txt
13
+ tests/test_pdb_bfactor.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pdb-bfactor = pdb_bfactor.cli:main
@@ -0,0 +1 @@
1
+ pdb_bfactor
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pdb-bfactor"
7
+ version = "0.1.0"
8
+ description = "Zero-dependency CLI and Python library for PDB/mmCIF B-factor score projection, multimer chain permutation, protein-RNA complex merging, and SEQRES conversion"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.8"
13
+ authors = [
14
+ { name = "Taner Karagöl", email = "karagolt@mit.edu" },
15
+ { name = "Alper Karagöl", email = "akaragol@mit.edu" },
16
+ ]
17
+ keywords = [
18
+ "pdb",
19
+ "mmcif",
20
+ "b-factor",
21
+ "pymol",
22
+ "chimerax",
23
+ "alphafold",
24
+ "structural-biology",
25
+ "conservation",
26
+ ]
27
+ classifiers = [
28
+ "Development Status :: 4 - Beta",
29
+ "Intended Audience :: Science/Research",
30
+ "Operating System :: OS Independent",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3.8",
33
+ "Programming Language :: Python :: 3.9",
34
+ "Programming Language :: Python :: 3.10",
35
+ "Programming Language :: Python :: 3.11",
36
+ "Programming Language :: Python :: 3.12",
37
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
38
+ ]
39
+ dependencies = []
40
+
41
+ [project.urls]
42
+ Homepage = "https://www.tanerkaragol.com/pdb-tools"
43
+ Repository = "https://github.com/karagol-taner/PDB-conservation-BFactor"
44
+
45
+ [project.scripts]
46
+ pdb-bfactor = "pdb_bfactor.cli:main"
47
+
48
+ [tool.setuptools.packages.find]
49
+ include = ["pdb_bfactor*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from setuptools import setup
2
+
3
+ if __name__ == "__main__":
4
+ setup()
@@ -0,0 +1,96 @@
1
+ import os
2
+ import tempfile
3
+ import unittest
4
+
5
+ from pdb_bfactor import (
6
+ combine_pdb_files,
7
+ fasta_to_seqres,
8
+ load_score_table,
9
+ map_bfactors,
10
+ pdb_to_fasta,
11
+ swap_pdb_chains,
12
+ )
13
+ from pdb_bfactor.cli import main as cli_main
14
+
15
+ SAMPLE_PDB = (
16
+ "ATOM 1 N MET A 1 11.104 13.207 10.000 1.00 20.00 N\n"
17
+ "ATOM 2 CA MET A 1 12.560 13.207 10.000 1.00 20.00 C\n"
18
+ "ATOM 3 N LYS A 2 13.104 14.207 10.000 1.00 20.00 N\n"
19
+ "ATOM 4 N VAL B 1 21.104 23.207 20.000 1.00 30.00 N\n"
20
+ "END\n"
21
+ )
22
+
23
+ SAMPLE_CIF = (
24
+ "data_demo\n"
25
+ "loop_\n"
26
+ "_atom_site.group_PDB\n"
27
+ "_atom_site.id\n"
28
+ "_atom_site.label_comp_id\n"
29
+ "_atom_site.auth_asym_id\n"
30
+ "_atom_site.label_seq_id\n"
31
+ "_atom_site.B_iso_or_equiv\n"
32
+ "ATOM 1 MET A 1 50.00\n"
33
+ "ATOM 2 LYS A 2 50.00\n"
34
+ "#\n"
35
+ )
36
+
37
+
38
+ class TestPdbBfactor(unittest.TestCase):
39
+ def test_map_pdb_and_cif_and_swap_and_combine(self):
40
+ with tempfile.TemporaryDirectory() as tmp:
41
+ pdb_in = os.path.join(tmp, "in.pdb")
42
+ cif_in = os.path.join(tmp, "in.cif")
43
+ csv_in = os.path.join(tmp, "scores.csv")
44
+ pdb_out = os.path.join(tmp, "out.pdb")
45
+ cif_out = os.path.join(tmp, "out.cif")
46
+ swap_out = os.path.join(tmp, "swap.pdb")
47
+ comb_out = os.path.join(tmp, "comb.pdb")
48
+ fa_out = os.path.join(tmp, "seq.fasta")
49
+ sr_out = os.path.join(tmp, "seqres.pdb")
50
+
51
+ with open(pdb_in, "w", encoding="utf-8") as fh:
52
+ fh.write(SAMPLE_PDB)
53
+ with open(cif_in, "w", encoding="utf-8") as fh:
54
+ fh.write(SAMPLE_CIF)
55
+ with open(csv_in, "w", encoding="utf-8") as fh:
56
+ fh.write("pos,score\n1,9.25\n2,3.50\n")
57
+
58
+ scores = load_score_table(csv_in)
59
+ self.assertEqual(scores[1], 9.25)
60
+
61
+ n_pdb = map_bfactors(pdb_in, pdb_out, scores, chain="A")
62
+ self.assertEqual(n_pdb, 3)
63
+ with open(pdb_out, encoding="utf-8") as fh:
64
+ lines = fh.readlines()
65
+ self.assertEqual(lines[0][60:66], " 9.25")
66
+ self.assertEqual(lines[2][60:66], " 3.50")
67
+ self.assertEqual(lines[3][60:66], " 30.00")
68
+
69
+ n_cif = map_bfactors(cif_in, cif_out, scores, chain="A")
70
+ self.assertEqual(n_cif, 2)
71
+ with open(cif_out, encoding="utf-8") as fh:
72
+ cif_txt = fh.read()
73
+ self.assertIn("ATOM 1 MET A 1 9.25", cif_txt)
74
+
75
+ swap_pdb_chains(pdb_in, swap_out, order=["B", "A"], renumber_residues=True)
76
+ with open(swap_out, encoding="utf-8") as fh:
77
+ swapped = [ln for ln in fh if ln.startswith("ATOM")]
78
+ self.assertEqual(swapped[0][21], "A")
79
+ self.assertIn("VAL", swapped[0])
80
+ self.assertEqual(swapped[1][21], "B")
81
+
82
+ combine_pdb_files([pdb_in, pdb_in], comb_out, chain_ids=["X", "Y"])
83
+ recs = pdb_to_fasta(comb_out)
84
+ self.assertEqual(len(recs), 2)
85
+ self.assertEqual(recs[0][1], "MKV")
86
+
87
+ sr = fasta_to_seqres("MKV", chain="A")
88
+ self.assertIn("SEQRES 1 A 3 MET LYS VAL", sr)
89
+
90
+ cli_main(["seqres", "-i", pdb_in, "-o", fa_out])
91
+ cli_main(["seqres", "-i", fa_out, "-o", sr_out, "--to-seqres"])
92
+ self.assertTrue(os.path.isfile(sr_out))
93
+
94
+
95
+ if __name__ == "__main__":
96
+ unittest.main()