Coverage for biobb_vs/utils/box_residues.py: 93%
69 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 15:52 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 15:52 +0000
1#!/usr/bin/env python3
3"""Module containing the BoxResidues class and the command line interface."""
4import warnings
5from pathlib import PurePath
6from typing import Optional
7import numpy as np
8from Bio import BiopythonDeprecationWarning
9from biobb_common.generic.biobb_object import BiobbObject, launcher
10from biobb_common.tools import file_utils as fu
12from biobb_vs.utils.common import (
13 get_box_coordinates,
14)
16with warnings.catch_warnings():
17 warnings.simplefilter("ignore", BiopythonDeprecationWarning)
18 # try:
19 # import Bio.SubsMat.MatrixInfo
20 # except ImportError:
21 import Bio.Align.substitution_matrices
22 import Bio.pairwise2
23 import Bio.PDB
26class BoxResidues(BiobbObject):
27 """
28 | biobb_vs BoxResidues
29 | This class sets the center and the size of a rectangular parallelepiped box around a set of residues.
30 | Sets the center and the size of a rectangular parallelepiped box around a selection of residues found in a given PDB. The residue identifiers that compose the selection (i.e. binding site) are provided by a property list.
32 Args:
33 input_pdb_path (str): PDB protein structure for which the box will be build. Its size and center will be set around the 'resid_list' property once mapped against this PDB. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/utils/input_box_residues.pdb>`_. Accepted formats: pdb (edam:format_1476), pqr (edam:format_1476).
34 output_pdb_path (str): PDB including the annotation of the box center and size as REMARKs. File type: output. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/reference/utils/ref_output_box_residues.pdb>`_. Accepted formats: pdb (edam:format_1476).
35 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
36 * **resid_list** (*list*) - (None) List with all the residue numbers to form a cavity or binding site. Mandatory property.
37 * **offset** (*float*) - (2.0) [0.1~1000|0.1] Extra distance (Angstroms) between the last residue atom and the box boundary. The box is centred on the mean of the selected coordinates, so a set of points that is asymmetric about its centre may extend slightly beyond the box faces. Choose an offset large enough to absorb that asymmetry, yet small enough not to enlarge the box past what the binding site needs, since a larger box spreads the same sampling effort over more space.
38 * **box_coordinates** (*bool*) - (False) Add box coordinates as 8 ATOM records.
39 * **residue_offset** (*int*) - (0) [0~1000|1] Residue id offset.
40 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
41 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
42 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
44 Examples:
45 This is a use example of how to use the building block from Python::
47 from biobb_vs.utils.box_residues import box_residues
48 prop = {
49 'resid_list': [718, 743, 745, 762, 766, 796, 790, 791, 793, 794, 788],
50 'offset': 2,
51 'box_coordinates': True
52 }
53 box_residues(input_pdb_path='/path/to/myStructure.pdb',
54 output_pdb_path='/path/to/newBox.pdb',
55 properties=prop)
57 Info:
58 * wrapped_software:
59 * name: In house using Biopython
60 * version: >=1.76
61 * license: Apache-2.0
62 * ontology:
63 * name: EDAM
64 * schema: http://edamontology.org/EDAM.owl
66 """
68 def __init__(
69 self, input_pdb_path: str, output_pdb_path: str, properties: Optional[dict] = None, **kwargs
70 ) -> None:
71 super().__init__(**locals())
73 # Properties specific for BB
74 self.resid_list = fu.str_to_list(self.resid_list)
75 self.offset = float(self.offset)
76 self.box_coordinates = float(self.box_coordinates)
78 def stage_files(self) -> None:
79 """The block does not use the sandbox: there are no files to stage."""
81 def run(self) -> None:
82 """Execute the :class:`BoxResidues <utils.box_residues.BoxResidues>` utils.box_residues.BoxResidues object."""
84 # Parse structure
85 fu.log(
86 "Loading input PDB structure %s" % (self.io_dict["in"]["input_pdb_path"]),
87 self.out_log,
88 self.global_log,
89 )
90 structure_name = PurePath(self.io_dict["in"]["input_pdb_path"]).name
91 parser = Bio.PDB.PDBParser(QUIET=True)
92 structPDB = parser.get_structure(
93 structure_name, self.io_dict["in"]["input_pdb_path"]
94 )
96 if len(structPDB):
97 structPDB = structPDB[0]
99 # Mapping residue structure into input structure
101 fu.log(
102 "Mapping residue structure into input structure",
103 self.out_log,
104 self.global_log,
105 )
107 # Listing residues to be selected from the residue structure
108 residPDB_res_list = []
109 for residPDB_res in self.resid_list:
110 if self.residue_offset:
111 residPDB_res_list.append((" ", residPDB_res + self.residue_offset, " "))
112 else:
113 residPDB_res_list.append((" ", residPDB_res, " "))
115 selection_res_list = []
116 selection_atoms_num = 0
117 for struct_chain in structPDB:
118 for struct_res in struct_chain:
119 if struct_res.get_id() in residPDB_res_list:
120 selection_res_list.append(struct_res)
121 selection_atoms_num += len(struct_res.get_list())
123 if len(selection_res_list) == 0:
124 fu.log(
125 self.__class__.__name__ + ": Cannot match any of the residues listed in [%s] into %s"
126 % (
127 ", ".join(str(v) for v in self.resid_list),
128 self.io_dict["in"]["input_pdb_path"],
129 ),
130 self.out_log,
131 )
132 raise SystemExit(
133 self.__class__.__name__ + ": Cannot match any of the residues listed in [%s] into %s"
134 % (
135 ", ".join(str(v) for v in self.resid_list),
136 self.io_dict["in"]["input_pdb_path"],
137 )
138 )
139 elif len(selection_res_list) != len(residPDB_res_list):
140 fu.log(
141 "Cannot match all the residues listed in %s into %s. Found %s out of %s"
142 % (
143 ", ".join(str(v) for v in self.resid_list),
144 self.io_dict["in"]["input_pdb_path"],
145 len(selection_res_list),
146 len(residPDB_res_list),
147 ),
148 self.out_log,
149 )
150 else:
151 fu.log(
152 "Selection of residues successfully matched",
153 self.out_log,
154 self.global_log,
155 )
157 # Compute binding site box size
159 # compute box center
160 selection_box_center = (
161 sum(atom.coord for res in selection_res_list for atom in res.get_atoms()) / selection_atoms_num
162 )
163 fu.log(
164 "Binding site center (Angstroms): %10.3f%10.3f%10.3f"
165 % (
166 selection_box_center[0],
167 selection_box_center[1],
168 selection_box_center[2],
169 ),
170 self.out_log,
171 self.global_log,
172 )
174 # compute box size
175 selection_coords_max = np.amax(
176 [atom.coord for res in selection_res_list for atom in res.get_atoms()],
177 axis=0,
178 )
179 selection_box_size = selection_coords_max - selection_box_center
180 if self.offset:
181 selection_box_size = [c + self.offset for c in selection_box_size]
183 # SIZE is written as the full edge length, which is what Vina reads from
184 # --size_x/y/z. selection_box_size stays a half-extent because that is
185 # what the corner coordinates and the volume are computed from.
186 selection_box_edge = [2 * side for side in selection_box_size]
187 fu.log(
188 "Binding site box edge lengths (Angstroms): %10.3f%10.3f%10.3f"
189 % (selection_box_edge[0], selection_box_edge[1], selection_box_edge[2]),
190 self.out_log,
191 self.global_log,
192 )
194 # compute volume
195 vol = np.prod(selection_box_size) * 2**3
196 fu.log("Volume (cubic Angstroms): %.0f" % (vol), self.out_log, self.global_log)
198 # add box details as PDB remarks
199 remarks = "REMARK BOX CENTER:%10.3f%10.3f%10.3f" % (
200 selection_box_center[0],
201 selection_box_center[1],
202 selection_box_center[2],
203 )
204 remarks += " SIZE:%10.3f%10.3f%10.3f" % (
205 selection_box_edge[0],
206 selection_box_edge[1],
207 selection_box_edge[2],
208 )
210 selection_box_coords_txt = ""
211 # add (optional) box coordinates as 8 ATOM records
212 if self.box_coordinates:
213 fu.log("Adding box coordinates", self.out_log, self.global_log)
214 selection_box_coords_txt = get_box_coordinates(
215 selection_box_center, selection_box_size
216 )
218 with open(self.io_dict["out"]["output_pdb_path"], "w") as f:
219 f.seek(0, 0)
220 f.write(remarks.rstrip("\r\n") + "\n" + selection_box_coords_txt)
222 fu.log(
223 "Saving output PDB file (with box setting annotations): %s"
224 % (self.io_dict["out"]["output_pdb_path"]),
225 self.out_log,
226 self.global_log,
227 )
230box_residues = launcher(BoxResidues)
233if __name__ == "__main__":
234 BoxResidues.main()