prodigy-prot 2.3.0__tar.gz → 2.5.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.
Files changed (38) hide show
  1. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/.github/workflows/ci.yml +1 -1
  2. prodigy_prot-2.5.0/.github/workflows/stale.yml +27 -0
  3. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/PKG-INFO +19 -10
  4. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/README.md +16 -7
  5. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/pyproject.toml +2 -2
  6. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/cli.py +87 -15
  7. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/modules/aa_properties.py +26 -0
  8. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/modules/freesasa_tools.py +8 -2
  9. prodigy_prot-2.5.0/src/prodigy_prot/modules/parsers.py +204 -0
  10. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/modules/prodigy.py +53 -50
  11. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/test_parsers.py +17 -5
  12. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/test_prodigy.py +49 -40
  13. prodigy_prot-2.3.0/src/prodigy_prot/modules/parsers.py +0 -166
  14. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/.github/workflows/docker-publish.yml +0 -0
  15. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/.github/workflows/publish.yml +0 -0
  16. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/.gitignore +0 -0
  17. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/.howfairis.yml +0 -0
  18. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/CITATION.cff +0 -0
  19. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/CODE_OF_CONDUCT.md +0 -0
  20. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/CONTRIBUTING.md +0 -0
  21. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/DEVELOPMENT.md +0 -0
  22. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/Dockerfile +0 -0
  23. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/LICENSE +0 -0
  24. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/MANIFEST.in +0 -0
  25. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/examples/3BZD.ic_model +0 -0
  26. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/examples/3BZD.pdb +0 -0
  27. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/examples/3bzd.cif +0 -0
  28. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/__init__.py +0 -0
  29. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/data/naccess.config +0 -0
  30. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/modules/__init__.py +0 -0
  31. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/modules/models.py +0 -0
  32. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/src/prodigy_prot/modules/utils.py +0 -0
  33. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/__init__.py +0 -0
  34. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/test_data/2oob.cif +0 -0
  35. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/test_data/2oob.pdb +0 -0
  36. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/test_data/dataset.json +0 -0
  37. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/test_data/dataset.tgz +0 -0
  38. {prodigy_prot-2.3.0 → prodigy_prot-2.5.0}/tests/test_utils.py +0 -0
@@ -7,7 +7,7 @@ jobs:
7
7
  runs-on: ubuntu-latest
8
8
  strategy:
9
9
  matrix:
10
- python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
10
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
11
11
  fail-fast: false
12
12
 
13
13
  steps:
@@ -0,0 +1,27 @@
1
+ name: "Close stale issues and PRs"
2
+ on:
3
+ schedule:
4
+ - cron: "30 1 * * *"
5
+ workflow_dispatch:
6
+
7
+ jobs:
8
+ stale:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ contents: write
12
+ issues: write
13
+ pull-requests: write
14
+ actions: write
15
+ steps:
16
+ - uses: actions/stale@v10
17
+ with:
18
+ stale-pr-message: "This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days."
19
+ stale-issue-message: "This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days."
20
+ close-pr-message: 'This PR was closed because it has been stalled for 5 days with no activity.'
21
+ close-issue-message: 'This issue was closed because it has been stalled for 5 days with no activity.'
22
+ days-before-stale: 30
23
+ days-before-close: 5
24
+ exempt-issue-labels: "bug"
25
+ exempt-pr-labels: "bug"
26
+ remove-stale-when-updated: true
27
+ operations-per-run: 100
@@ -1,19 +1,19 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: prodigy-prot
3
- Version: 2.3.0
3
+ Version: 2.5.0
4
4
  Summary: PROtein binDIng enerGY prediction
5
5
  Author: Anna Vangone, Joao Rodrigues, Joerg Schaarschmidt
6
6
  Maintainer-email: BonvinLab <bonvinlab.support@uu.nl>
7
7
  License-Expression: Apache-2.0
8
8
  License-File: LICENSE
9
9
  Classifier: Development Status :: 5 - Production/Stable
10
- Classifier: Programming Language :: Python :: 3.9
11
10
  Classifier: Programming Language :: Python :: 3.10
12
11
  Classifier: Programming Language :: Python :: 3.11
13
12
  Classifier: Programming Language :: Python :: 3.12
14
13
  Classifier: Programming Language :: Python :: 3.13
15
14
  Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
16
15
  Classifier: Topic :: Scientific/Engineering :: Chemistry
16
+ Requires-Python: >=3.10
17
17
  Requires-Dist: biopython>=1.80
18
18
  Requires-Dist: freesasa>=2.2.1
19
19
  Requires-Dist: numpy>=2
@@ -65,13 +65,20 @@ Or in a directory containing multiple molecules:
65
65
  prodigy <directory_with_molecules>
66
66
  ```
67
67
 
68
- To get a list of all the possible options.
68
+ Or using a multi-model input PDB file (an ensemble)
69
69
 
70
70
  ```bash
71
+ prodigy <multi_model.pdb>
72
+ ```
71
73
 
74
+ > If you are running several structures, try using the `-np` argument to run
75
+ > in multiple processors
76
+
77
+ To get a list of all the possible options.
78
+
79
+ ```bash
72
80
  $ prodigy -h
73
- usage: prodigy [-h] [--distance-cutoff DISTANCE_CUTOFF] [--acc-threshold ACC_THRESHOLD]
74
- [--temperature TEMPERATURE] [--contact_list] [--pymol_selection] [-q]
81
+ usage: prodigy [-h] [--distance-cutoff DISTANCE_CUTOFF] [--acc-threshold ACC_THRESHOLD] [--temperature TEMPERATURE] [--contact_list] [--pymol_selection] [-q] [-np NUMBER_OF_PROCESSORS]
75
82
  [--selection A B [A,B C ...]]
76
83
  input_path
77
84
 
@@ -93,6 +100,9 @@ options:
93
100
  --contact_list Output a list of contacts
94
101
  --pymol_selection Output a script to highlight the interface (pymol)
95
102
  -q, --quiet Outputs only the predicted affinity value
103
+ -s, --showall Outputs all original prodigy features but BSA (mutually exclusive with `-q`)
104
+ -np, --number-of-processors NUMBER_OF_PROCESSORS
105
+ Number of processors to use (default: 1)
96
106
 
97
107
  Selection Options:
98
108
 
@@ -110,8 +120,6 @@ Selection Options:
110
120
  --selection A B => Contacts calculated (only) between chains A and B.
111
121
  --selection A,B C => Contacts calculated (only) between chains A and C; and B and C.
112
122
  --selection A B C => Contacts calculated (only) between chains A and B; B and C; and A and C.
113
-
114
- --selection A B [A,B C ...]
115
123
  ```
116
124
 
117
125
  ## Example single structure
@@ -154,10 +162,11 @@ curl -o input/2oob.pdb https://files.rcsb.org/download/2OOB.pdb
154
162
  curl -o input/1ppe.pdb https://files.rcsb.org/download/1PPE.pdb
155
163
  ```
156
164
 
157
- Run `prodigy` with the `quiet` option, so it is easier to parse the output later:
165
+ Run `prodigy` with the `quiet` option, so it is easier to parse the output later
166
+ and run it with 2 processors via the `np` option.
158
167
 
159
168
  ```bash
160
- $ prodigy -q input/
169
+ $ prodigy -q -np 2 input/
161
170
  3bzd -9.373
162
171
  2oob -6.230
163
172
  1ppe -14.727
@@ -38,13 +38,20 @@ Or in a directory containing multiple molecules:
38
38
  prodigy <directory_with_molecules>
39
39
  ```
40
40
 
41
- To get a list of all the possible options.
41
+ Or using a multi-model input PDB file (an ensemble)
42
42
 
43
43
  ```bash
44
+ prodigy <multi_model.pdb>
45
+ ```
44
46
 
47
+ > If you are running several structures, try using the `-np` argument to run
48
+ > in multiple processors
49
+
50
+ To get a list of all the possible options.
51
+
52
+ ```bash
45
53
  $ prodigy -h
46
- usage: prodigy [-h] [--distance-cutoff DISTANCE_CUTOFF] [--acc-threshold ACC_THRESHOLD]
47
- [--temperature TEMPERATURE] [--contact_list] [--pymol_selection] [-q]
54
+ usage: prodigy [-h] [--distance-cutoff DISTANCE_CUTOFF] [--acc-threshold ACC_THRESHOLD] [--temperature TEMPERATURE] [--contact_list] [--pymol_selection] [-q] [-np NUMBER_OF_PROCESSORS]
48
55
  [--selection A B [A,B C ...]]
49
56
  input_path
50
57
 
@@ -66,6 +73,9 @@ options:
66
73
  --contact_list Output a list of contacts
67
74
  --pymol_selection Output a script to highlight the interface (pymol)
68
75
  -q, --quiet Outputs only the predicted affinity value
76
+ -s, --showall Outputs all original prodigy features but BSA (mutually exclusive with `-q`)
77
+ -np, --number-of-processors NUMBER_OF_PROCESSORS
78
+ Number of processors to use (default: 1)
69
79
 
70
80
  Selection Options:
71
81
 
@@ -83,8 +93,6 @@ Selection Options:
83
93
  --selection A B => Contacts calculated (only) between chains A and B.
84
94
  --selection A,B C => Contacts calculated (only) between chains A and C; and B and C.
85
95
  --selection A B C => Contacts calculated (only) between chains A and B; B and C; and A and C.
86
-
87
- --selection A B [A,B C ...]
88
96
  ```
89
97
 
90
98
  ## Example single structure
@@ -127,10 +135,11 @@ curl -o input/2oob.pdb https://files.rcsb.org/download/2OOB.pdb
127
135
  curl -o input/1ppe.pdb https://files.rcsb.org/download/1PPE.pdb
128
136
  ```
129
137
 
130
- Run `prodigy` with the `quiet` option, so it is easier to parse the output later:
138
+ Run `prodigy` with the `quiet` option, so it is easier to parse the output later
139
+ and run it with 2 processors via the `np` option.
131
140
 
132
141
  ```bash
133
- $ prodigy -q input/
142
+ $ prodigy -q -np 2 input/
134
143
  3bzd -9.373
135
144
  2oob -6.230
136
145
  1ppe -14.727
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "prodigy-prot"
3
3
  license = "Apache-2.0"
4
- version = "2.3.0"
4
+ version = "2.5.0"
5
5
  description = "PROtein binDIng enerGY prediction"
6
6
  authors = [
7
7
  { name = "Anna Vangone" },
@@ -10,9 +10,9 @@ authors = [
10
10
  ]
11
11
  maintainers = [{ name = "BonvinLab", email = "bonvinlab.support@uu.nl" }]
12
12
  readme = "README.md"
13
+ requires-python = ">=3.10"
13
14
  classifiers = [
14
15
  "Development Status :: 5 - Production/Stable",
15
- "Programming Language :: Python :: 3.9",
16
16
  "Programming Language :: Python :: 3.10",
17
17
  "Programming Language :: Python :: 3.11",
18
18
  "Programming Language :: Python :: 3.12",
@@ -6,12 +6,13 @@ import argparse
6
6
  import logging
7
7
  import sys
8
8
  from argparse import RawTextHelpFormatter
9
+ from concurrent.futures import ProcessPoolExecutor, as_completed
10
+ from io import StringIO
9
11
  from pathlib import Path
10
12
 
11
- from Bio.PDB.Structure import Structure
13
+ from Bio.PDB.Model import Model
12
14
 
13
- from prodigy_prot.modules.parsers import (get_parser, parse_structure,
14
- validate_structure)
15
+ from prodigy_prot.modules.parsers import parse_structure
15
16
  from prodigy_prot.modules.prodigy import Prodigy
16
17
 
17
18
  # setup logging
@@ -54,6 +55,20 @@ ap.add_argument(
54
55
  action="store_true",
55
56
  help="Outputs only the predicted affinity value",
56
57
  )
58
+ ap.add_argument(
59
+ "-s",
60
+ "--showall",
61
+ action="store_true",
62
+ help="Outputs all original prodigy features but BSA (mutually exclusive with `-q`)",
63
+ )
64
+ ap.add_argument(
65
+ "-np",
66
+ "--number-of-processors",
67
+ type=int,
68
+ action="store",
69
+ help="Number of processors to use (default: 1)",
70
+ default=1,
71
+ )
57
72
  _co_help = """
58
73
  By default, all intermolecular contacts are taken into consideration,
59
74
  a molecule being defined as an isolated group of amino acids sharing
@@ -80,6 +95,11 @@ def main():
80
95
  args = ap.parse_args()
81
96
  log.setLevel(logging.ERROR if args.quiet else logging.INFO)
82
97
 
98
+ if args.quiet and args.showall:
99
+ log.error("Error: --quiet (-q) and --showall (-s) are mutually exclusive arguments")
100
+ sys.exit(1)
101
+ log.setLevel(logging.ERROR if args.quiet else logging.INFO)
102
+
83
103
  struct_path = Path(args.input_path)
84
104
 
85
105
  input_list = []
@@ -99,28 +119,80 @@ def main():
99
119
  log.error(f"Input path {struct_path} is neither a valid file nor a directory")
100
120
  sys.exit(1)
101
121
 
122
+ # Collect all tasks
123
+ tasks = []
102
124
  for input_f in input_list:
103
- structure, n_chains, n_res = parse_structure(str(input_f))
125
+ models, _, _ = parse_structure(str(input_f))
126
+ struct_path = Path(input_f)
104
127
 
105
- if len(input_list) > 1:
106
- log.info("#" * 42)
128
+ for model in models:
129
+ identifier = f"{struct_path.stem}_model{model.id}"
130
+ tasks.append((model, identifier, args, struct_path))
107
131
 
132
+ # Execute in parallel
133
+ total_tasks = len(tasks)
134
+ if total_tasks == 0:
135
+ log.error("No valid structures found")
136
+ sys.exit(1)
137
+ max_workers = min(args.number_of_processors, total_tasks)
138
+ log.info(f"[+] Executing {total_tasks} task(s) in total")
139
+ if max_workers != args.number_of_processors:
140
+ log.info("[+] Adjusting number of processors based on number of tasks")
108
141
  log.info(
109
- "[+] Parsed structure file {0} ({1} chains, {2} residues)".format(
110
- structure.id, n_chains, n_res
111
- )
142
+ f"[+] Using {max_workers} processor(s) instead of {args.number_of_processors}"
143
+ )
144
+
145
+ # Execute and collect results
146
+ results = []
147
+ with ProcessPoolExecutor(max_workers=max_workers) as executor:
148
+ futures = [executor.submit(process_model, *task) for task in tasks]
149
+ for future in as_completed(futures):
150
+ try:
151
+ result = future.result()
152
+ results.append(result)
153
+ except Exception as e:
154
+ log.error(f"Error processing model: {e}")
155
+
156
+ # Sort by identifier, then model.id
157
+ results.sort(key=lambda x: (x[0], x[1]))
158
+ # Print all outputs sequentially
159
+ for identifier, _, output in results:
160
+ print(output, end="")
161
+
162
+
163
+ def process_model(model: Model, identifier: str, args: argparse.Namespace, struct_path):
164
+ """Process a single model"""
165
+ # Capture stdout
166
+ output_buffer = StringIO()
167
+
168
+ old_stdout = sys.stdout
169
+ sys.stdout = output_buffer
170
+ try:
171
+ if not args.quiet:
172
+ print("#" * 42)
173
+ print(f"[+] Processing structure {identifier}")
174
+ prodigy = Prodigy(
175
+ model=model,
176
+ name=identifier,
177
+ selection=args.selection,
178
+ temp=args.temperature,
112
179
  )
113
- prodigy = Prodigy(structure, args.selection, args.temperature)
114
180
  prodigy.predict(
115
181
  distance_cutoff=args.distance_cutoff, acc_threshold=args.acc_threshold
116
182
  )
117
- prodigy.print_prediction(quiet=args.quiet)
183
+ prodigy.print_prediction(quiet=args.quiet, showall=args.showall)
184
+ finally:
185
+ sys.stdout = old_stdout
186
+
187
+ if args.contact_list:
188
+ contact_list_f = struct_path.with_suffix(".ic")
189
+ prodigy.print_contacts(outfile=str(contact_list_f))
118
190
 
119
- if args.contact_list:
120
- prodigy.print_contacts(outfile=str(struct_path.with_suffix(".ic")))
191
+ if args.pymol_selection:
192
+ pymol_script_f = struct_path.with_suffix(".pml")
193
+ prodigy.print_pymol_script(outfile=str(pymol_script_f))
121
194
 
122
- if args.pymol_selection:
123
- prodigy.print_pymol_script(outfile=str(struct_path.with_suffix(".pml")))
195
+ return identifier, model.id, output_buffer.getvalue()
124
196
 
125
197
 
126
198
  if __name__ == "__main__":
@@ -49,6 +49,32 @@ aa_character_protorp: dict[str, str] = {
49
49
  "TYR": "P",
50
50
  }
51
51
 
52
+ # Taken from pre-original prodigy code
53
+ # B for hydrophoBic
54
+ # Y for hydrophiLic
55
+ aa_character_hydro: dict[str, str] = {
56
+ "ALA": "B", #+
57
+ "CYS": "B", #+
58
+ "GLU": "L", #+
59
+ "ASP": "L", #+
60
+ "GLY": "L", # Glycine was B in my initial classification
61
+ "PHE": "B", #+
62
+ "ILE": "B", #+
63
+ "HIS": "L", #+
64
+ "LYS": "L", #+
65
+ "MET": "B", #+
66
+ "LEU": "B", #+
67
+ "ASN": "L", #+
68
+ "GLN": "L", #+
69
+ "PRO": "L", # Proline was B my initial classification
70
+ "SER": "L", #+
71
+ "ARG": "L", #+
72
+ "THR": "L", #+
73
+ "TRP": "L", #+
74
+ "VAL": "B", #+
75
+ "TYR": "L", #+
76
+ }
77
+
52
78
  # Scaling factors for relative ASA
53
79
  # Calculated using extended ALA-X-ALA peptides
54
80
  # Taken from NACCESS
@@ -5,6 +5,7 @@ Functions to execute freesasa and parse its output.
5
5
  import os
6
6
 
7
7
  import freesasa
8
+ from Bio.PDB.Model import Model
8
9
  from Bio.PDB.Structure import Structure
9
10
  from freesasa import Classifier, calc, structureFromBioPDB
10
11
 
@@ -14,7 +15,7 @@ from prodigy_prot.modules.aa_properties import rel_asa
14
15
  freesasa.setVerbosity(freesasa.nowarnings)
15
16
 
16
17
 
17
- def execute_freesasa_api(structure: Structure) -> tuple[dict, dict]:
18
+ def execute_freesasa_api(model: Model) -> tuple[dict, dict]:
18
19
  """
19
20
  Calls freesasa using its Python API and returns
20
21
  per-residue accessibilities.
@@ -26,9 +27,14 @@ def execute_freesasa_api(structure: Structure) -> tuple[dict, dict]:
26
27
 
27
28
  classifier = Classifier(str(NACCESS_CONFIG))
28
29
 
30
+ # NOTE: `structureFromBioPDB` requires a Structure object
31
+ # so here build one from a model
32
+ s = Structure(model.id)
33
+ s.add(model)
34
+
29
35
  try:
30
36
  struct = structureFromBioPDB(
31
- structure,
37
+ s,
32
38
  classifier,
33
39
  )
34
40
  result = calc(struct)
@@ -0,0 +1,204 @@
1
+ """
2
+ Functions to read PDB/mmCIF files
3
+ """
4
+
5
+ import logging
6
+ import sys
7
+ import typing
8
+ import warnings
9
+ from pathlib import Path
10
+ from typing import Optional, Union
11
+
12
+ from Bio.PDB.Atom import DisorderedAtom
13
+ from Bio.PDB.Chain import Chain
14
+ from Bio.PDB.MMCIFParser import MMCIFParser
15
+ from Bio.PDB.Model import Model
16
+ from Bio.PDB.PDBExceptions import PDBConstructionWarning
17
+ from Bio.PDB.PDBParser import PDBParser
18
+ from Bio.PDB.Polypeptide import PPBuilder, is_aa
19
+ from Bio.PDB.Structure import Structure
20
+
21
+ warnings.filterwarnings("ignore", category=PDBConstructionWarning)
22
+ log = logging.getLogger("Prodigy")
23
+
24
+
25
+ def get_parser(input_f: Path) -> Union[PDBParser, MMCIFParser]:
26
+ if input_f.suffix == ".cif":
27
+ return MMCIFParser()
28
+ else:
29
+ return PDBParser()
30
+
31
+
32
+ def ignore(r):
33
+ return r.id[0][0] == "W" or r.id[0][0] == "H"
34
+
35
+
36
+ # Force-field (CHARMM, AMBER) names of standard residues
37
+ FORCEFIELD_RESNAMES = {
38
+ "HSD": "HIS",
39
+ "HSE": "HIS",
40
+ "HSP": "HIS",
41
+ "HID": "HIS",
42
+ "HIE": "HIS",
43
+ "HIP": "HIS",
44
+ "CYX": "CYS",
45
+ "CYM": "CYS",
46
+ "ASH": "ASP",
47
+ "GLH": "GLU",
48
+ "LYN": "LYS",
49
+ }
50
+
51
+
52
+ def validate_structure(
53
+ input_strcture_obj: Structure,
54
+ selection: Optional[list[str]] = None,
55
+ clean: bool = True,
56
+ ) -> list[Model]:
57
+
58
+ result: list[Model] = []
59
+ for model in [m for m in input_strcture_obj.child_list]:
60
+
61
+ # process selected chains
62
+ chains: list[Chain] = list(model.get_chains())
63
+ chain_ids = set([c.id for c in chains])
64
+
65
+ if selection:
66
+ sel_chains = []
67
+ # Match selected chain with structure
68
+ for sel in selection:
69
+ for c_str in sel.split(","):
70
+ sel_chains.append(c_str)
71
+ if c_str not in chain_ids:
72
+ raise ValueError(
73
+ f"Selected chain not present in provided structure: {c_str}"
74
+ )
75
+
76
+ # Remove unselected chains
77
+ def _ignore_helper(x) -> bool:
78
+ return x.id not in sel_chains
79
+
80
+ for c in chains:
81
+ if _ignore_helper(c):
82
+ if c.parent is not None:
83
+ c.parent.detach_child(c.id)
84
+
85
+ # Double occupancy check
86
+ for atom in list(model.get_atoms()):
87
+ if atom.is_disordered():
88
+ atom = typing.cast(DisorderedAtom, atom)
89
+ residue = atom.parent
90
+ assert residue is not None
91
+ sel_at = atom.selected_child
92
+ assert sel_at is not None
93
+ sel_at.altloc = " "
94
+ sel_at.disordered_flag = 0
95
+ residue.detach_child(atom.id)
96
+ residue.add(sel_at)
97
+
98
+ # Insertion code check
99
+ for c in chains:
100
+ for residue in c.get_residues():
101
+ if residue.get_id()[2] != " ":
102
+ c.detach_child(residue.id)
103
+
104
+ if clean:
105
+ # Remove HETATMs and solvent
106
+ res_list = list(model.get_residues())
107
+
108
+ for res in res_list:
109
+ res.resname = FORCEFIELD_RESNAMES.get(res.resname, res.resname)
110
+ if ignore(res):
111
+ chain = res.parent
112
+ assert chain is not None
113
+ chain.detach_child(res.id)
114
+ elif not is_aa(res, standard=True):
115
+ raise ValueError(
116
+ "Unsupported non-standard amino acid found: {0}".format(
117
+ res.resname
118
+ )
119
+ )
120
+
121
+ # Remove Hydrogens
122
+ atom_list = list(model.get_atoms())
123
+
124
+ def _ignore(x):
125
+ return x.element == "H"
126
+
127
+ for atom in atom_list:
128
+ if _ignore(atom):
129
+ residue = atom.parent
130
+ assert residue is not None
131
+ residue.detach_child(atom.name)
132
+
133
+ # Detect gaps and compare with no. of chains
134
+ pep_builder = PPBuilder()
135
+ peptides = pep_builder.build_peptides(model)
136
+ n_peptides = len(peptides)
137
+
138
+ if n_peptides != len(chain_ids):
139
+ message = "[!] Structure contains gaps:\n"
140
+ for i_pp, pp in enumerate(peptides):
141
+ message += (
142
+ "\t{1.parent.id} {1.resname}{1.id[1]} < Fragment {0} > "
143
+ "{2.parent.id} {2.resname}{2.id[1]}\n".format(i_pp, pp[0], pp[-1])
144
+ )
145
+ log.warning(message)
146
+
147
+ result.append(model)
148
+
149
+ return result
150
+
151
+
152
+ def parse_structure(path: str) -> tuple[list[Model], int, int]:
153
+ """Return a validated `Structure`, number of chains and number of residues"""
154
+
155
+ extension = Path(path).suffix
156
+ supported_extensions = [".pdb", ".cif", ".ent"]
157
+ if extension not in supported_extensions:
158
+ log.error(
159
+ f"[!] Structure format '{extension}' is "
160
+ "not supported. Use '.pdb' or '.cif'."
161
+ )
162
+ sys.exit(1)
163
+
164
+ parser = get_parser(Path(path))
165
+ structure_name = Path(path).stem
166
+ structure_path = Path(path)
167
+ try:
168
+ original_structure = parser.get_structure(structure_name, structure_path)
169
+ except Exception as e:
170
+ log.exception(e)
171
+ sys.exit(1)
172
+
173
+ assert isinstance(original_structure, Structure)
174
+
175
+ models: list[Model] = validate_structure(original_structure)
176
+
177
+ # Get number of chains
178
+ chain_dict = {}
179
+ res_dict = {}
180
+ for model in models:
181
+ chain_dict.update({c.id: c for c in model.get_chains()})
182
+ res_dict.update({r.id: r for r in model.get_residues()})
183
+
184
+ ## Make sure all models have the same chains
185
+ # Get chain sets for all models
186
+ chain_sets = [set(chain.id for chain in model.get_chains()) for model in models]
187
+
188
+ # Check if all sets are identical
189
+ if not all(chain_set == chain_sets[0] for chain_set in chain_sets):
190
+ raise ValueError(
191
+ "Not all models have the same chains. Found chain sets: "
192
+ + ", ".join(str(s) for s in chain_sets)
193
+ )
194
+
195
+ res_sets = [set(res.id for res in model.get_residues()) for model in models]
196
+
197
+ if not all(res_set == res_sets[0] for res_set in res_sets):
198
+ raise ValueError(
199
+ "Not all models have the same residues. Found residue sets: "
200
+ + ", ".join(str(s) for s in res_sets)
201
+ )
202
+
203
+ # structure, n_chains, n_res = parse_structure(path=str(struct_path))
204
+ return (models, len(chain_sets[0]), len(res_sets[0]))
@@ -2,8 +2,9 @@ import sys
2
2
  from io import TextIOWrapper
3
3
  from typing import Optional, TextIO, Union
4
4
 
5
+ from Bio.PDB.Model import Model
5
6
  from Bio.PDB.NeighborSearch import NeighborSearch
6
- from Bio.PDB.Structure import Structure
7
+ #from Bio.PDB.Structure import Structure
7
8
 
8
9
  from prodigy_prot.modules import aa_properties
9
10
  from prodigy_prot.modules.freesasa_tools import execute_freesasa_api
@@ -12,12 +13,12 @@ from prodigy_prot.modules.utils import dg_to_kd
12
13
 
13
14
 
14
15
  def calculate_ic(
15
- struct: Structure, d_cutoff: float = 5.5, selection: Optional[dict[str, int]] = None
16
+ model: Model, d_cutoff: float = 5.5, selection: Optional[dict[str, int]] = None
16
17
  ) -> list:
17
18
  """
18
19
  Calculates intermolecular contacts in a parsed struct object.
19
20
  """
20
- atom_list = list(struct.get_atoms())
21
+ atom_list = list(model.get_atoms())
21
22
  ns = NeighborSearch(atom_list)
22
23
  all_list = ns.search_all(radius=d_cutoff, level="R")
23
24
 
@@ -58,6 +59,9 @@ def analyse_contacts(contact_list: list) -> dict[str, float]:
58
59
  "AP": 0.0,
59
60
  "CP": 0.0,
60
61
  "AC": 0.0,
62
+ "LL": 0.0,
63
+ "BL": 0.0,
64
+ "BB": 0.0
61
65
  }
62
66
 
63
67
  _data = aa_properties.aa_character_ic
@@ -68,6 +72,14 @@ def analyse_contacts(contact_list: list) -> dict[str, float]:
68
72
  contact_type = "".join(sorted((i, j)))
69
73
  bins[contact_type] += 1
70
74
 
75
+ _data = aa_properties.aa_character_hydro
76
+ for res_i, res_j in contact_list:
77
+ i = _data.get(res_i.resname)
78
+ j = _data.get(res_j.resname)
79
+ if i is not None and j is not None:
80
+ contact_type = "".join(sorted((i, j)))
81
+ bins[contact_type] += 1
82
+
71
83
  return bins
72
84
 
73
85
 
@@ -94,7 +106,6 @@ def analyse_nis(sasa_dict: dict, acc_threshold: float = 0.05) -> list[float]:
94
106
  count[aa_index] += 1
95
107
 
96
108
  percentages = [100.0 * x / sum(count) for x in count]
97
- # print('[+] No. of buried interface residues: {0}'.format(sum(count)))
98
109
  return percentages
99
110
 
100
111
 
@@ -102,16 +113,18 @@ class Prodigy:
102
113
  # init parameters
103
114
  def __init__(
104
115
  self,
105
- struct_obj: Structure,
116
+ model: Model,
117
+ name: str = "",
106
118
  selection: Optional[list[str]] = None,
107
119
  temp: float = 25.0,
108
120
  ):
109
121
  self.temp = float(temp)
110
122
  if selection is None:
111
- self.selection = [chain.id for chain in struct_obj.get_chains()]
123
+ self.selection = [chain.id for chain in model.get_chains()]
112
124
  else:
113
125
  self.selection = selection
114
- self.structure = struct_obj
126
+ self.model = model
127
+ self.name = name
115
128
  self.ic_network: list = []
116
129
  self.bins: dict[str, float] = {
117
130
  "CC": 0.0,
@@ -120,10 +133,14 @@ class Prodigy:
120
133
  "PP": 0.0,
121
134
  "AP": 0.0,
122
135
  "AA": 0.0,
136
+ "LL": 0.0,
137
+ "BL": 0.0,
138
+ "BB": 0.0
123
139
  }
124
140
 
125
141
  self.nis_a = 0.0
126
142
  self.nis_c = 0.0
143
+ self.nis_p = 0.0
127
144
  self.ba_val = 0.0
128
145
  self.kd_val = 0.0
129
146
 
@@ -147,14 +164,13 @@ class Prodigy:
147
164
 
148
165
  # Contacts
149
166
  self.ic_network = calculate_ic(
150
- self.structure, d_cutoff=distance_cutoff, selection=selection_dict
167
+ self.model, d_cutoff=distance_cutoff, selection=selection_dict
151
168
  )
152
169
 
153
170
  self.bins = analyse_contacts(self.ic_network)
154
-
155
171
  # SASA
156
- _, cmplx_sasa = execute_freesasa_api(self.structure)
157
- self.nis_a, self.nis_c, _ = analyse_nis(cmplx_sasa, acc_threshold=acc_threshold)
172
+ _, cmplx_sasa = execute_freesasa_api(self.model)
173
+ self.nis_a, self.nis_c, self.nis_p = analyse_nis(cmplx_sasa, acc_threshold=acc_threshold)
158
174
 
159
175
  # Affinity Calculation
160
176
  self.ba_val = IC_NIS(
@@ -169,19 +185,20 @@ class Prodigy:
169
185
 
170
186
  def as_dict(self) -> dict:
171
187
  return_dict = {
172
- "structure": self.structure.id,
188
+ "model": self.model.id,
173
189
  "selection": self.selection,
174
190
  "temp": self.temp,
175
191
  "ICs": len(self.ic_network),
176
192
  "nis_a": self.nis_a,
177
193
  "nis_c": self.nis_c,
194
+ "nis_p": self.nis_p,
178
195
  "ba_val": self.ba_val,
179
196
  "kd_val": self.kd_val,
180
197
  }
181
198
  return_dict.update(self.bins)
182
199
  return return_dict
183
200
 
184
- def print_prediction(self, outfile: str = "", quiet: bool = False) -> None:
201
+ def print_prediction(self, outfile: str = "", quiet: bool = False, showall: bool = False) -> None:
185
202
  handle: Union[TextIOWrapper, TextIO]
186
203
  if outfile:
187
204
  handle = open(outfile, "w")
@@ -189,44 +206,30 @@ class Prodigy:
189
206
  handle = sys.stdout
190
207
 
191
208
  if quiet:
192
- handle.write("{0}\t{1:8.3f}\n".format(self.structure.id, self.ba_val))
209
+ handle.write("{0}\t{1:8.3f}\n".format(self.name, self.ba_val))
193
210
  else:
194
- handle.write(
195
- "[+] No. of intermolecular contacts: {0}\n".format(len(self.ic_network))
196
- )
197
- handle.write(
198
- "[+] No. of charged-charged contacts: {0}\n".format(self.bins["CC"])
199
- )
200
- handle.write(
201
- "[+] No. of charged-polar contacts: {0}\n".format(self.bins["CP"])
202
- )
203
- handle.write(
204
- "[+] No. of charged-apolar contacts: {0}\n".format(self.bins["AC"])
205
- )
206
- handle.write(
207
- "[+] No. of polar-polar contacts: {0}\n".format(self.bins["PP"])
208
- )
209
- handle.write(
210
- "[+] No. of apolar-polar contacts: {0}\n".format(self.bins["AP"])
211
- )
212
- handle.write(
213
- "[+] No. of apolar-apolar contacts: {0}\n".format(self.bins["AA"])
214
- )
215
-
216
- handle.write(
217
- "[+] Percentage of apolar NIS residues: {0:3.2f}\n".format(self.nis_a)
218
- )
219
- handle.write(
220
- "[+] Percentage of charged NIS residues: {0:3.2f}\n".format(self.nis_c)
221
- )
222
- handle.write(
223
- "[++] Predicted binding "
224
- "affinity (kcal.mol-1): {0:8.1f}\n".format(self.ba_val)
225
- )
226
- handle.write(
227
- "[++] Predicted dissociation constant (M) at {:.1f}˚C:"
228
- " {:8.1e}\n".format(self.temp, self.kd_val)
229
- )
211
+ # Collect output lines in order
212
+ lines = []
213
+ lines.append(f"[+] No. of intermolecular contacts: {len(self.ic_network)}\n")
214
+ lines.append(f"[+] No. of Charged-Charged contacts: {self.bins['CC']}\n")
215
+ lines.append(f"[+] No. of Charged-Polar contacts: {self.bins['CP']}\n")
216
+ lines.append(f"[+] No. of Charged-Apolar contacts: {self.bins['AC']}\n")
217
+ lines.append(f"[+] No. of Polar-Polar contacts: {self.bins['PP']}\n")
218
+ lines.append(f"[+] No. of Apolar-Polar contacts: {self.bins['AP']}\n")
219
+ lines.append(f"[+] No. of Apolar-Apolar contacts: {self.bins['AA']}\n")
220
+
221
+ if showall:
222
+ lines.append(f"[+] No. of hydrophiLic-hydrophiLic contacts: {self.bins['LL']}\n")
223
+ lines.append(f"[+] No. of hydrophoBic-hydrophiLic contacts: {self.bins['BL']}\n")
224
+ lines.append(f"[+] No. of hydrophoBic-hydrophoBic contacts: {self.bins['BB']}\n")
225
+ lines.append(f"[+] Percentage of Polar NIS residues: {self.nis_p:3.2f}\n")
226
+
227
+ lines.append(f"[+] Percentage of Apolar NIS residues: {self.nis_a:3.2f}\n")
228
+ lines.append(f"[+] Percentage of Charged NIS residues: {self.nis_c:3.2f}\n")
229
+ lines.append(f"[++] predicted binding affinity (kcal.mol-1): {self.ba_val:8.1f}\n")
230
+ lines.append(f"[++] predicted dissociation constant (M) at {self.temp:.1f}˚C: {self.kd_val:8.1e}\n")
231
+
232
+ handle.writelines(lines)
230
233
 
231
234
  if handle is not sys.stdout:
232
235
  handle.close()
@@ -39,27 +39,38 @@ def test_validate_structure_pdb(input_structure_pdb):
39
39
  assert isinstance(structure, Structure)
40
40
 
41
41
  result = validate_structure(structure)
42
- assert result == structure
42
+ assert result == structure.child_list
43
43
 
44
44
 
45
- def test_validate_stucture_cif(input_structure_cif):
45
+ def test_validate_structure_cif(input_structure_cif):
46
46
 
47
47
  parser = MMCIFParser()
48
48
  structure = parser.get_structure("test_structure", input_structure_cif)
49
49
  assert isinstance(structure, Structure)
50
50
 
51
51
  result = validate_structure(structure)
52
- assert result == structure
52
+ assert result == structure.child_list
53
+
54
+
55
+ def test_validate_structure_forcefield_resnames(input_structure_pdb):
56
+
57
+ structure = PDBParser().get_structure("test_structure", input_structure_pdb)
58
+ his = next(r for r in structure.get_residues() if r.resname == "HIS")
59
+ his.resname = "HSD"
60
+
61
+ validate_structure(structure)
62
+ assert his.resname == "HIS"
53
63
 
54
64
 
55
65
  def test_parse_structure_pdb(input_structure_pdb):
56
66
 
57
67
  parser = PDBParser()
58
68
  structure = parser.get_structure(input_structure_pdb.stem, input_structure_pdb)
69
+ assert isinstance(structure, Structure)
59
70
 
60
71
  result, num_chains, num_res = parse_structure(input_structure_pdb)
61
72
 
62
- assert result == structure
73
+ assert result == structure.child_list
63
74
  assert num_chains == 2
64
75
  assert num_res == 116
65
76
 
@@ -68,9 +79,10 @@ def test_parse_structure_cif(input_structure_cif):
68
79
 
69
80
  parser = MMCIFParser()
70
81
  structure = parser.get_structure(input_structure_cif.stem, input_structure_cif)
82
+ assert isinstance(structure, Structure)
71
83
 
72
84
  result, num_chains, num_res = parse_structure(input_structure_cif)
73
85
 
74
- assert result == structure
86
+ assert result == structure.child_list
75
87
  assert num_chains == 2
76
88
  assert num_res == 116
@@ -6,6 +6,7 @@ from os.path import basename, splitext
6
6
  from pathlib import Path
7
7
 
8
8
  import pytest
9
+ from Bio.PDB.Model import Model
9
10
  from Bio.PDB.PDBParser import PDBParser
10
11
  from Bio.PDB.Residue import Residue
11
12
  from Bio.PDB.Structure import Structure
@@ -22,10 +23,12 @@ from . import TEST_DATA
22
23
 
23
24
 
24
25
  @pytest.fixture
25
- def input_pdb_structure():
26
+ def input_model():
26
27
  input_f = Path(TEST_DATA, "2oob.pdb")
27
28
  parser = PDBParser()
28
- return parser.get_structure(input_f.stem, input_f)
29
+ structure = parser.get_structure(input_f.stem, input_f)
30
+ assert isinstance(structure, Structure)
31
+ return structure.child_list[0]
29
32
 
30
33
 
31
34
  @pytest.fixture
@@ -39,13 +42,13 @@ def expected_dataset_json():
39
42
 
40
43
 
41
44
  @pytest.fixture
42
- def prodigy_class(input_pdb_structure):
43
- yield Prodigy(struct_obj=input_pdb_structure)
45
+ def prodigy_class(input_model):
46
+ yield Prodigy(input_model)
44
47
 
45
48
 
46
- def test_calculate_ic(input_pdb_structure):
49
+ def test_calculate_ic(input_model):
47
50
 
48
- result = calculate_ic(struct=input_pdb_structure, d_cutoff=5.5)
51
+ result = calculate_ic(model=input_model, d_cutoff=5.5)
49
52
 
50
53
  assert len(result) == 78
51
54
 
@@ -55,11 +58,9 @@ def test_calculate_ic(input_pdb_structure):
55
58
  assert first_hit[1].get_resname() == "LYS"
56
59
 
57
60
 
58
- def test_calculate_ic_with_selection(input_pdb_structure):
61
+ def test_calculate_ic_with_selection(input_model):
59
62
 
60
- result = calculate_ic(
61
- struct=input_pdb_structure, d_cutoff=5.5, selection={"A": 0, "B": 1}
62
- )
63
+ result = calculate_ic(model=input_model, d_cutoff=5.5, selection={"A": 0, "B": 1})
63
64
 
64
65
  assert len(result) == 78
65
66
 
@@ -69,10 +70,10 @@ def test_calculate_ic_with_selection(input_pdb_structure):
69
70
  assert first_hit[1].get_resname() == "LYS"
70
71
 
71
72
 
72
- def test_analyse_contacts(input_pdb_structure):
73
+ def test_analyse_contacts(input_model):
73
74
 
74
- res_a = input_pdb_structure[0]["A"][(" ", 931, " ")]
75
- res_b = input_pdb_structure[0]["B"][(" ", 6, " ")]
75
+ res_a = input_model["A"][(" ", 931, " ")]
76
+ res_b = input_model["B"][(" ", 6, " ")]
76
77
  contact = (res_a, res_b)
77
78
 
78
79
  test_input = [contact]
@@ -86,8 +87,10 @@ def test_analyse_contacts(input_pdb_structure):
86
87
  "AP": 0.0,
87
88
  "CP": 1.0,
88
89
  "AC": 0.0,
90
+ "LL": 1.0,
91
+ "BL": 0.0,
92
+ "BB": 0.0
89
93
  }
90
-
91
94
  assert result == expected_output
92
95
 
93
96
 
@@ -118,7 +121,8 @@ def test_prodigy_as_dict(prodigy_class):
118
121
  result = prodigy_class.as_dict()
119
122
 
120
123
  assert isinstance(result, dict)
121
- assert len(result) == 14
124
+ # 14 'original' + 3 hydro + 1 %NIS
125
+ assert len(result) == 18
122
126
 
123
127
 
124
128
  def test_prodigy_print_prediction(prodigy_class):
@@ -143,10 +147,10 @@ def test_prodigy_print_prediction_quiet(prodigy_class):
143
147
  Path(outfile.name).unlink()
144
148
 
145
149
 
146
- def test_prodigy_print_contacts(input_pdb_structure, prodigy_class):
150
+ def test_prodigy_print_contacts(input_model, prodigy_class):
147
151
 
148
- res_a = input_pdb_structure[0]["A"][(" ", 931, " ")]
149
- res_b = input_pdb_structure[0]["B"][(" ", 6, " ")]
152
+ res_a = input_model["A"][(" ", 931, " ")]
153
+ res_b = input_model["B"][(" ", 6, " ")]
150
154
  prodigy_class.ic_network = [(res_a, res_b)]
151
155
 
152
156
  outfile = tempfile.NamedTemporaryFile(delete=False)
@@ -158,9 +162,9 @@ def test_prodigy_print_contacts(input_pdb_structure, prodigy_class):
158
162
  Path(outfile.name).unlink()
159
163
 
160
164
 
161
- def test_print_pymol_script(input_pdb_structure, prodigy_class):
162
- res_a = input_pdb_structure[0]["A"][(" ", 931, " ")]
163
- res_b = input_pdb_structure[0]["B"][(" ", 6, " ")]
165
+ def test_print_pymol_script(input_model, prodigy_class):
166
+ res_a = input_model["A"][(" ", 931, " ")]
167
+ res_b = input_model["B"][(" ", 6, " ")]
164
168
  prodigy_class.ic_network = [(res_a, res_b)]
165
169
 
166
170
  outfile = tempfile.NamedTemporaryFile(delete=False)
@@ -205,26 +209,31 @@ def test_dataset_prediction(compressed_dataset_f, expected_dataset_json):
205
209
  parsed_structure = parser.get_structure(s_name, handle)
206
210
  assert isinstance(parsed_structure, Structure)
207
211
 
208
- s = validate_structure(parsed_structure, selection=["A", "B"])
212
+ models = validate_structure(parsed_structure, selection=["A", "B"])
209
213
 
210
214
  # Test for structure object
211
- assert isinstance(s, Structure)
215
+ # Check if it's a list and all elements are Model objects
216
+ assert isinstance(models, list) and all(
217
+ isinstance(item, Model) for item in models
218
+ )
219
+ # assert isinstance(s, list[Model])
212
220
 
213
221
  # run prediction and retrieve result dict
214
- prod = Prodigy(s, selection=["A", "B"])
215
- prod.predict()
216
- results = prod.as_dict()
217
-
218
- # check for equality of prdicted interface residues
219
- for k in keys_equal:
220
- observed_value = results[k]
221
- expected_value = expected_data[s_name][k]
222
- assert observed_value == pytest.approx(expected_value)
223
-
224
- # check that NIS and binding afinity values are within 2% of
225
- # expected values and add diffs for summary
226
- for k in diffs.keys():
227
- delta = abs(results[k] / expected_data[s_name][k] - 1)
228
- # assume a difference of less then 2%
229
- assert delta == pytest.approx(0, abs=0.02)
230
- diffs[k].append(delta)
222
+ for m in models:
223
+ prod = Prodigy(m, selection=["A", "B"])
224
+ prod.predict()
225
+ results = prod.as_dict()
226
+
227
+ # check for equality of prdicted interface residues
228
+ for k in keys_equal:
229
+ observed_value = results[k]
230
+ expected_value = expected_data[s_name][k]
231
+ assert observed_value == pytest.approx(expected_value)
232
+
233
+ # check that NIS and binding afinity values are within 2% of
234
+ # expected values and add diffs for summary
235
+ for k in diffs.keys():
236
+ delta = abs(results[k] / expected_data[s_name][k] - 1)
237
+ # assume a difference of less then 2%
238
+ assert delta == pytest.approx(0, abs=0.02)
239
+ diffs[k].append(delta)
@@ -1,166 +0,0 @@
1
- """
2
- Functions to read PDB/mmCIF files
3
- """
4
-
5
- import logging
6
- import sys
7
- import warnings
8
- from pathlib import Path
9
- from typing import Optional, Union
10
-
11
- from Bio.PDB.Chain import Chain
12
- from Bio.PDB.MMCIFParser import MMCIFParser
13
- from Bio.PDB.PDBExceptions import PDBConstructionWarning
14
- from Bio.PDB.PDBParser import PDBParser
15
- from Bio.PDB.Polypeptide import PPBuilder, is_aa
16
- from Bio.PDB.Structure import Structure
17
-
18
- warnings.filterwarnings("ignore", category=PDBConstructionWarning)
19
- log = logging.getLogger("Prodigy")
20
-
21
-
22
- def get_parser(input_f: Path) -> Union[PDBParser, MMCIFParser]:
23
- if input_f.suffix == ".cif":
24
- return MMCIFParser()
25
- else:
26
- return PDBParser()
27
-
28
-
29
- def validate_structure(
30
- s: Structure, selection: Optional[list[str]] = None, clean: bool = True
31
- ) -> Structure:
32
-
33
- # setup logging
34
- logger = logging.getLogger("Prodigy")
35
-
36
- # Keep first model only
37
- if len(s) > 1:
38
- logger.warning(
39
- (
40
- "[!] Structure contains more than one model."
41
- " Only the first one will be kept"
42
- )
43
- )
44
- model_one = s[0].id
45
- for m in s.child_list[:]:
46
- if m.id != model_one:
47
- s.detach_child(m.id)
48
-
49
- # process selected chains
50
- chains: list[Chain] = list(s.get_chains())
51
- chain_ids = set([c.id for c in chains])
52
-
53
- if selection:
54
- sel_chains = []
55
- # Match selected chain with structure
56
- for sel in selection:
57
- for c_str in sel.split(","):
58
- sel_chains.append(c_str)
59
- if c_str not in chain_ids:
60
- raise ValueError(
61
- f"Selected chain not present in provided structure: {c_str}"
62
- )
63
-
64
- # Remove unselected chains
65
- def _ignore_helper(x) -> bool:
66
- return x.id not in sel_chains
67
-
68
- for c in chains:
69
- if _ignore_helper(c):
70
- if c.parent is not None:
71
- c.parent.detach_child(c.id)
72
-
73
- # Double occupancy check
74
- for atom in list(s.get_atoms()):
75
- if atom.is_disordered():
76
- residue = atom.parent
77
- sel_at = atom.selected_child
78
- sel_at.altloc = " "
79
- sel_at.disordered_flag = 0
80
- residue.detach_child(atom.id)
81
- residue.add(sel_at)
82
-
83
- # Insertion code check
84
- for c in chains:
85
- for residue in c.get_residues():
86
- if residue.get_id()[2] != " ":
87
- c.detach_child(residue.id)
88
-
89
- if clean:
90
- # Remove HETATMs and solvent
91
- res_list = list(s.get_residues())
92
-
93
- def _ignore(r):
94
- return r.id[0][0] == "W" or r.id[0][0] == "H"
95
-
96
- for res in res_list:
97
- if _ignore(res):
98
- chain = res.parent
99
- chain.detach_child(res.id)
100
- elif not is_aa(res, standard=True):
101
- raise ValueError(
102
- "Unsupported non-standard amino acid found: {0}".format(res.resname)
103
- )
104
-
105
- # Remove Hydrogens
106
- atom_list = list(s.get_atoms())
107
-
108
- def _ignore(x):
109
- return x.element == "H"
110
-
111
- for atom in atom_list:
112
- if _ignore(atom):
113
- residue = atom.parent
114
- residue.detach_child(atom.name)
115
-
116
- # Detect gaps and compare with no. of chains
117
- pep_builder = PPBuilder()
118
- peptides = pep_builder.build_peptides(s)
119
- n_peptides = len(peptides)
120
-
121
- if n_peptides != len(chain_ids):
122
- message = "[!] Structure contains gaps:\n"
123
- for i_pp, pp in enumerate(peptides):
124
- message += (
125
- "\t{1.parent.id} {1.resname}{1.id[1]} < Fragment {0} > "
126
- "{2.parent.id} {2.resname}{2.id[1]}\n".format(i_pp, pp[0], pp[-1])
127
- )
128
- logger.warning(message)
129
- # raise Exception(message)
130
-
131
- return s
132
-
133
-
134
- def parse_structure(path: str) -> tuple[Structure, int, int]:
135
- """Return a validated `Structure`, number of chains and number of residues"""
136
-
137
- extension = Path(path).suffix
138
- supported_extensions = [".pdb", ".cif", ".ent"]
139
- if extension not in supported_extensions:
140
- log.error(
141
- f"[!] Structure format '{extension}' is "
142
- "not supported. Use '.pdb' or '.cif'."
143
- )
144
- sys.exit(1)
145
-
146
- parser = get_parser(Path(path))
147
- structure_name = Path(path).stem
148
- structure_path = Path(path)
149
- try:
150
- original_structure = parser.get_structure(structure_name, structure_path)
151
- except Exception as e:
152
- log.exception(e)
153
- sys.exit(1)
154
-
155
- assert isinstance(original_structure, Structure)
156
-
157
- structure = validate_structure(original_structure)
158
-
159
- # Get number of chains
160
- number_of_chains = len(set([c.id for c in structure.get_chains()]))
161
-
162
- # Get number of residues
163
- number_of_residues = len(list(structure.get_residues()))
164
-
165
- # structure, n_chains, n_res = parse_structure(path=str(struct_path))
166
- return (structure, number_of_chains, number_of_residues)
File without changes
File without changes
File without changes
File without changes
File without changes