prodigy-prot 2.3.0__tar.gz → 2.4.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 (37) hide show
  1. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/PKG-INFO +16 -8
  2. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/README.md +15 -7
  3. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/pyproject.toml +1 -1
  4. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/cli.py +75 -14
  5. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/modules/freesasa_tools.py +8 -2
  6. prodigy_prot-2.4.0/src/prodigy_prot/modules/parsers.py +187 -0
  7. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/modules/prodigy.py +12 -9
  8. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/test_parsers.py +7 -5
  9. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/test_prodigy.py +44 -38
  10. prodigy_prot-2.3.0/src/prodigy_prot/modules/parsers.py +0 -166
  11. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/.github/workflows/ci.yml +0 -0
  12. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/.github/workflows/docker-publish.yml +0 -0
  13. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/.github/workflows/publish.yml +0 -0
  14. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/.gitignore +0 -0
  15. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/.howfairis.yml +0 -0
  16. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/CITATION.cff +0 -0
  17. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/CODE_OF_CONDUCT.md +0 -0
  18. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/CONTRIBUTING.md +0 -0
  19. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/DEVELOPMENT.md +0 -0
  20. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/Dockerfile +0 -0
  21. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/LICENSE +0 -0
  22. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/MANIFEST.in +0 -0
  23. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/examples/3BZD.ic_model +0 -0
  24. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/examples/3BZD.pdb +0 -0
  25. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/examples/3bzd.cif +0 -0
  26. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/__init__.py +0 -0
  27. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/data/naccess.config +0 -0
  28. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/modules/__init__.py +0 -0
  29. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/modules/aa_properties.py +0 -0
  30. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/modules/models.py +0 -0
  31. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/src/prodigy_prot/modules/utils.py +0 -0
  32. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/__init__.py +0 -0
  33. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/test_data/2oob.cif +0 -0
  34. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/test_data/2oob.pdb +0 -0
  35. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/test_data/dataset.json +0 -0
  36. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/test_data/dataset.tgz +0 -0
  37. {prodigy_prot-2.3.0 → prodigy_prot-2.4.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: prodigy-prot
3
- Version: 2.3.0
3
+ Version: 2.4.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>
@@ -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,8 @@ 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
+ -np, --number-of-processors NUMBER_OF_PROCESSORS
104
+ Number of processors to use (default: 1)
96
105
 
97
106
  Selection Options:
98
107
 
@@ -110,8 +119,6 @@ Selection Options:
110
119
  --selection A B => Contacts calculated (only) between chains A and B.
111
120
  --selection A,B C => Contacts calculated (only) between chains A and C; and B and C.
112
121
  --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
122
  ```
116
123
 
117
124
  ## Example single structure
@@ -154,10 +161,11 @@ curl -o input/2oob.pdb https://files.rcsb.org/download/2OOB.pdb
154
161
  curl -o input/1ppe.pdb https://files.rcsb.org/download/1PPE.pdb
155
162
  ```
156
163
 
157
- Run `prodigy` with the `quiet` option, so it is easier to parse the output later:
164
+ Run `prodigy` with the `quiet` option, so it is easier to parse the output later
165
+ and run it with 2 processors via the `np` option.
158
166
 
159
167
  ```bash
160
- $ prodigy -q input/
168
+ $ prodigy -q -np 2 input/
161
169
  3bzd -9.373
162
170
  2oob -6.230
163
171
  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,8 @@ 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
+ -np, --number-of-processors NUMBER_OF_PROCESSORS
77
+ Number of processors to use (default: 1)
69
78
 
70
79
  Selection Options:
71
80
 
@@ -83,8 +92,6 @@ Selection Options:
83
92
  --selection A B => Contacts calculated (only) between chains A and B.
84
93
  --selection A,B C => Contacts calculated (only) between chains A and C; and B and C.
85
94
  --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
95
  ```
89
96
 
90
97
  ## Example single structure
@@ -127,10 +134,11 @@ curl -o input/2oob.pdb https://files.rcsb.org/download/2OOB.pdb
127
134
  curl -o input/1ppe.pdb https://files.rcsb.org/download/1PPE.pdb
128
135
  ```
129
136
 
130
- Run `prodigy` with the `quiet` option, so it is easier to parse the output later:
137
+ Run `prodigy` with the `quiet` option, so it is easier to parse the output later
138
+ and run it with 2 processors via the `np` option.
131
139
 
132
140
  ```bash
133
- $ prodigy -q input/
141
+ $ prodigy -q -np 2 input/
134
142
  3bzd -9.373
135
143
  2oob -6.230
136
144
  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.4.0"
5
5
  description = "PROtein binDIng enerGY prediction"
6
6
  authors = [
7
7
  { name = "Anna Vangone" },
@@ -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,14 @@ ap.add_argument(
54
55
  action="store_true",
55
56
  help="Outputs only the predicted affinity value",
56
57
  )
58
+ ap.add_argument(
59
+ "-np",
60
+ "--number-of-processors",
61
+ type=int,
62
+ action="store",
63
+ help="Number of processors to use (default: 1)",
64
+ default=1,
65
+ )
57
66
  _co_help = """
58
67
  By default, all intermolecular contacts are taken into consideration,
59
68
  a molecule being defined as an isolated group of amino acids sharing
@@ -99,28 +108,80 @@ def main():
99
108
  log.error(f"Input path {struct_path} is neither a valid file nor a directory")
100
109
  sys.exit(1)
101
110
 
111
+ # Collect all tasks
112
+ tasks = []
102
113
  for input_f in input_list:
103
- structure, n_chains, n_res = parse_structure(str(input_f))
114
+ models, _, _ = parse_structure(str(input_f))
115
+ struct_path = Path(input_f)
104
116
 
105
- if len(input_list) > 1:
106
- log.info("#" * 42)
117
+ for model in models:
118
+ identifier = f"{struct_path.stem}_model{model.id}"
119
+ tasks.append((model, identifier, args, struct_path))
107
120
 
121
+ # Execute in parallel
122
+ total_tasks = len(tasks)
123
+ if total_tasks == 0:
124
+ log.error("No valid structures found")
125
+ sys.exit(1)
126
+ max_workers = min(args.number_of_processors, total_tasks)
127
+ log.info(f"[+] Executing {total_tasks} task(s) in total")
128
+ if max_workers != args.number_of_processors:
129
+ log.info("[+] Adjusting number of processors based on number of tasks")
108
130
  log.info(
109
- "[+] Parsed structure file {0} ({1} chains, {2} residues)".format(
110
- structure.id, n_chains, n_res
111
- )
131
+ f"[+] Using {max_workers} processor(s) instead of {args.number_of_processors}"
132
+ )
133
+
134
+ # Execute and collect results
135
+ results = []
136
+ with ProcessPoolExecutor(max_workers=max_workers) as executor:
137
+ futures = [executor.submit(process_model, *task) for task in tasks]
138
+ for future in as_completed(futures):
139
+ try:
140
+ result = future.result()
141
+ results.append(result)
142
+ except Exception as e:
143
+ log.error(f"Error processing model: {e}")
144
+
145
+ # Sort by identifier, then model.id
146
+ results.sort(key=lambda x: (x[0], x[1]))
147
+ # Print all outputs sequentially
148
+ for identifier, _, output in results:
149
+ print(output, end="")
150
+
151
+
152
+ def process_model(model: Model, identifier: str, args: argparse.Namespace, struct_path):
153
+ """Process a single model"""
154
+ # Capture stdout
155
+ output_buffer = StringIO()
156
+
157
+ old_stdout = sys.stdout
158
+ sys.stdout = output_buffer
159
+ try:
160
+ if not args.quiet:
161
+ print("#" * 42)
162
+ print(f"[+] Processing structure {identifier}")
163
+ prodigy = Prodigy(
164
+ model=model,
165
+ name=identifier,
166
+ selection=args.selection,
167
+ temp=args.temperature,
112
168
  )
113
- prodigy = Prodigy(structure, args.selection, args.temperature)
114
169
  prodigy.predict(
115
170
  distance_cutoff=args.distance_cutoff, acc_threshold=args.acc_threshold
116
171
  )
117
172
  prodigy.print_prediction(quiet=args.quiet)
173
+ finally:
174
+ sys.stdout = old_stdout
175
+
176
+ if args.contact_list:
177
+ contact_list_f = struct_path.with_suffix(".ic")
178
+ prodigy.print_contacts(outfile=str(contact_list_f))
118
179
 
119
- if args.contact_list:
120
- prodigy.print_contacts(outfile=str(struct_path.with_suffix(".ic")))
180
+ if args.pymol_selection:
181
+ pymol_script_f = struct_path.with_suffix(".pml")
182
+ prodigy.print_pymol_script(outfile=str(pymol_script_f))
121
183
 
122
- if args.pymol_selection:
123
- prodigy.print_pymol_script(outfile=str(struct_path.with_suffix(".pml")))
184
+ return identifier, model.id, output_buffer.getvalue()
124
185
 
125
186
 
126
187
  if __name__ == "__main__":
@@ -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,187 @@
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
+ def validate_structure(
37
+ input_strcture_obj: Structure,
38
+ selection: Optional[list[str]] = None,
39
+ clean: bool = True,
40
+ ) -> list[Model]:
41
+
42
+ result: list[Model] = []
43
+ for model in [m for m in input_strcture_obj.child_list]:
44
+
45
+ # process selected chains
46
+ chains: list[Chain] = list(model.get_chains())
47
+ chain_ids = set([c.id for c in chains])
48
+
49
+ if selection:
50
+ sel_chains = []
51
+ # Match selected chain with structure
52
+ for sel in selection:
53
+ for c_str in sel.split(","):
54
+ sel_chains.append(c_str)
55
+ if c_str not in chain_ids:
56
+ raise ValueError(
57
+ f"Selected chain not present in provided structure: {c_str}"
58
+ )
59
+
60
+ # Remove unselected chains
61
+ def _ignore_helper(x) -> bool:
62
+ return x.id not in sel_chains
63
+
64
+ for c in chains:
65
+ if _ignore_helper(c):
66
+ if c.parent is not None:
67
+ c.parent.detach_child(c.id)
68
+
69
+ # Double occupancy check
70
+ for atom in list(model.get_atoms()):
71
+ if atom.is_disordered():
72
+ atom = typing.cast(DisorderedAtom, atom)
73
+ residue = atom.parent
74
+ assert residue is not None
75
+ sel_at = atom.selected_child
76
+ assert sel_at is not None
77
+ sel_at.altloc = " "
78
+ sel_at.disordered_flag = 0
79
+ residue.detach_child(atom.id)
80
+ residue.add(sel_at)
81
+
82
+ # Insertion code check
83
+ for c in chains:
84
+ for residue in c.get_residues():
85
+ if residue.get_id()[2] != " ":
86
+ c.detach_child(residue.id)
87
+
88
+ if clean:
89
+ # Remove HETATMs and solvent
90
+ res_list = list(model.get_residues())
91
+
92
+ for res in res_list:
93
+ if ignore(res):
94
+ chain = res.parent
95
+ assert chain is not None
96
+ chain.detach_child(res.id)
97
+ elif not is_aa(res, standard=True):
98
+ raise ValueError(
99
+ "Unsupported non-standard amino acid found: {0}".format(
100
+ res.resname
101
+ )
102
+ )
103
+
104
+ # Remove Hydrogens
105
+ atom_list = list(model.get_atoms())
106
+
107
+ def _ignore(x):
108
+ return x.element == "H"
109
+
110
+ for atom in atom_list:
111
+ if _ignore(atom):
112
+ residue = atom.parent
113
+ assert residue is not None
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(model)
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
+ log.warning(message)
129
+
130
+ result.append(model)
131
+
132
+ return result
133
+
134
+
135
+ def parse_structure(path: str) -> tuple[list[Model], int, int]:
136
+ """Return a validated `Structure`, number of chains and number of residues"""
137
+
138
+ extension = Path(path).suffix
139
+ supported_extensions = [".pdb", ".cif", ".ent"]
140
+ if extension not in supported_extensions:
141
+ log.error(
142
+ f"[!] Structure format '{extension}' is "
143
+ "not supported. Use '.pdb' or '.cif'."
144
+ )
145
+ sys.exit(1)
146
+
147
+ parser = get_parser(Path(path))
148
+ structure_name = Path(path).stem
149
+ structure_path = Path(path)
150
+ try:
151
+ original_structure = parser.get_structure(structure_name, structure_path)
152
+ except Exception as e:
153
+ log.exception(e)
154
+ sys.exit(1)
155
+
156
+ assert isinstance(original_structure, Structure)
157
+
158
+ models: list[Model] = validate_structure(original_structure)
159
+
160
+ # Get number of chains
161
+ chain_dict = {}
162
+ res_dict = {}
163
+ for model in models:
164
+ chain_dict.update({c.id: c for c in model.get_chains()})
165
+ res_dict.update({r.id: r for r in model.get_residues()})
166
+
167
+ ## Make sure all models have the same chains
168
+ # Get chain sets for all models
169
+ chain_sets = [set(chain.id for chain in model.get_chains()) for model in models]
170
+
171
+ # Check if all sets are identical
172
+ if not all(chain_set == chain_sets[0] for chain_set in chain_sets):
173
+ raise ValueError(
174
+ "Not all models have the same chains. Found chain sets: "
175
+ + ", ".join(str(s) for s in chain_sets)
176
+ )
177
+
178
+ res_sets = [set(res.id for res in model.get_residues()) for model in models]
179
+
180
+ if not all(res_set == res_sets[0] for res_set in res_sets):
181
+ raise ValueError(
182
+ "Not all models have the same residues. Found residue sets: "
183
+ + ", ".join(str(s) for s in res_sets)
184
+ )
185
+
186
+ # structure, n_chains, n_res = parse_structure(path=str(struct_path))
187
+ return (models, len(chain_sets[0]), len(res_sets[0]))
@@ -2,6 +2,7 @@ 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
7
  from Bio.PDB.Structure import Structure
7
8
 
@@ -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
 
@@ -102,16 +103,18 @@ class Prodigy:
102
103
  # init parameters
103
104
  def __init__(
104
105
  self,
105
- struct_obj: Structure,
106
+ model: Model,
107
+ name: str = "",
106
108
  selection: Optional[list[str]] = None,
107
109
  temp: float = 25.0,
108
110
  ):
109
111
  self.temp = float(temp)
110
112
  if selection is None:
111
- self.selection = [chain.id for chain in struct_obj.get_chains()]
113
+ self.selection = [chain.id for chain in model.get_chains()]
112
114
  else:
113
115
  self.selection = selection
114
- self.structure = struct_obj
116
+ self.model = model
117
+ self.name = name
115
118
  self.ic_network: list = []
116
119
  self.bins: dict[str, float] = {
117
120
  "CC": 0.0,
@@ -147,13 +150,13 @@ class Prodigy:
147
150
 
148
151
  # Contacts
149
152
  self.ic_network = calculate_ic(
150
- self.structure, d_cutoff=distance_cutoff, selection=selection_dict
153
+ self.model, d_cutoff=distance_cutoff, selection=selection_dict
151
154
  )
152
155
 
153
156
  self.bins = analyse_contacts(self.ic_network)
154
157
 
155
158
  # SASA
156
- _, cmplx_sasa = execute_freesasa_api(self.structure)
159
+ _, cmplx_sasa = execute_freesasa_api(self.model)
157
160
  self.nis_a, self.nis_c, _ = analyse_nis(cmplx_sasa, acc_threshold=acc_threshold)
158
161
 
159
162
  # Affinity Calculation
@@ -169,7 +172,7 @@ class Prodigy:
169
172
 
170
173
  def as_dict(self) -> dict:
171
174
  return_dict = {
172
- "structure": self.structure.id,
175
+ "model": self.model.id,
173
176
  "selection": self.selection,
174
177
  "temp": self.temp,
175
178
  "ICs": len(self.ic_network),
@@ -189,7 +192,7 @@ class Prodigy:
189
192
  handle = sys.stdout
190
193
 
191
194
  if quiet:
192
- handle.write("{0}\t{1:8.3f}\n".format(self.structure.id, self.ba_val))
195
+ handle.write("{0}\t{1:8.3f}\n".format(self.name, self.ba_val))
193
196
  else:
194
197
  handle.write(
195
198
  "[+] No. of intermolecular contacts: {0}\n".format(len(self.ic_network))
@@ -39,27 +39,28 @@ 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
53
 
54
54
 
55
55
  def test_parse_structure_pdb(input_structure_pdb):
56
56
 
57
57
  parser = PDBParser()
58
58
  structure = parser.get_structure(input_structure_pdb.stem, input_structure_pdb)
59
+ assert isinstance(structure, Structure)
59
60
 
60
61
  result, num_chains, num_res = parse_structure(input_structure_pdb)
61
62
 
62
- assert result == structure
63
+ assert result == structure.child_list
63
64
  assert num_chains == 2
64
65
  assert num_res == 116
65
66
 
@@ -68,9 +69,10 @@ def test_parse_structure_cif(input_structure_cif):
68
69
 
69
70
  parser = MMCIFParser()
70
71
  structure = parser.get_structure(input_structure_cif.stem, input_structure_cif)
72
+ assert isinstance(structure, Structure)
71
73
 
72
74
  result, num_chains, num_res = parse_structure(input_structure_cif)
73
75
 
74
- assert result == structure
76
+ assert result == structure.child_list
75
77
  assert num_chains == 2
76
78
  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]
@@ -143,10 +144,10 @@ def test_prodigy_print_prediction_quiet(prodigy_class):
143
144
  Path(outfile.name).unlink()
144
145
 
145
146
 
146
- def test_prodigy_print_contacts(input_pdb_structure, prodigy_class):
147
+ def test_prodigy_print_contacts(input_model, prodigy_class):
147
148
 
148
- res_a = input_pdb_structure[0]["A"][(" ", 931, " ")]
149
- res_b = input_pdb_structure[0]["B"][(" ", 6, " ")]
149
+ res_a = input_model["A"][(" ", 931, " ")]
150
+ res_b = input_model["B"][(" ", 6, " ")]
150
151
  prodigy_class.ic_network = [(res_a, res_b)]
151
152
 
152
153
  outfile = tempfile.NamedTemporaryFile(delete=False)
@@ -158,9 +159,9 @@ def test_prodigy_print_contacts(input_pdb_structure, prodigy_class):
158
159
  Path(outfile.name).unlink()
159
160
 
160
161
 
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, " ")]
162
+ def test_print_pymol_script(input_model, prodigy_class):
163
+ res_a = input_model["A"][(" ", 931, " ")]
164
+ res_b = input_model["B"][(" ", 6, " ")]
164
165
  prodigy_class.ic_network = [(res_a, res_b)]
165
166
 
166
167
  outfile = tempfile.NamedTemporaryFile(delete=False)
@@ -205,26 +206,31 @@ def test_dataset_prediction(compressed_dataset_f, expected_dataset_json):
205
206
  parsed_structure = parser.get_structure(s_name, handle)
206
207
  assert isinstance(parsed_structure, Structure)
207
208
 
208
- s = validate_structure(parsed_structure, selection=["A", "B"])
209
+ models = validate_structure(parsed_structure, selection=["A", "B"])
209
210
 
210
211
  # Test for structure object
211
- assert isinstance(s, Structure)
212
+ # Check if it's a list and all elements are Model objects
213
+ assert isinstance(models, list) and all(
214
+ isinstance(item, Model) for item in models
215
+ )
216
+ # assert isinstance(s, list[Model])
212
217
 
213
218
  # 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)
219
+ for m in models:
220
+ prod = Prodigy(m, selection=["A", "B"])
221
+ prod.predict()
222
+ results = prod.as_dict()
223
+
224
+ # check for equality of prdicted interface residues
225
+ for k in keys_equal:
226
+ observed_value = results[k]
227
+ expected_value = expected_data[s_name][k]
228
+ assert observed_value == pytest.approx(expected_value)
229
+
230
+ # check that NIS and binding afinity values are within 2% of
231
+ # expected values and add diffs for summary
232
+ for k in diffs.keys():
233
+ delta = abs(results[k] / expected_data[s_name][k] - 1)
234
+ # assume a difference of less then 2%
235
+ assert delta == pytest.approx(0, abs=0.02)
236
+ 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