Coverage for biobb_vs/utils/box.py: 84%
83 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-28 12:00 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-28 12:00 +0000
1#!/usr/bin/env python3
3"""Module containing the Box class and the command line interface."""
5import argparse
6from pathlib import PurePath
7from typing import Optional
9import numpy as np
10from biobb_common.configuration import settings
11from biobb_common.generic.biobb_object import BiobbObject
12from biobb_common.tools import file_utils as fu
13from biobb_common.tools.file_utils import launchlogger
15from biobb_vs.utils.common import (
16 check_input_path,
17 check_output_path,
18 get_box_coordinates,
19)
22class Box(BiobbObject):
23 """
24 | biobb_vs Box
25 | This class sets the center and the size of a rectangular parallelepiped box around a set of residues or a pocket.
26 | Sets the center and the size of a rectangular parallelepiped box around a set of residues from a given PDB or a pocket from a given PQR.
28 Args:
29 input_pdb_path (str): PDB file containing a selection of residue numbers or PQR file containing the pocket. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/utils/input_box.pqr>`_. Accepted formats: pdb (edam:format_1476), pqr (edam:format_1476).
30 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.pdb>`_. Accepted formats: pdb (edam:format_1476).
31 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
32 * **offset** (*float*) - (2.0) [0.1~1000|0.1] Extra distance (Angstroms) between the last residue atom and the box boundary.
33 * **box_coordinates** (*bool*) - (False) Add box coordinates as 8 ATOM records.
34 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
35 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
36 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
38 Examples:
39 This is a use example of how to use the building block from Python::
41 from biobb_vs.utils.box import box
42 prop = {
43 'offset': 2,
44 'box_coordinates': True
45 }
46 box(input_pdb_path='/path/to/myPocket.pqr',
47 output_pdb_path='/path/to/newBox.pdb',
48 properties=prop)
50 Info:
51 * wrapped_software:
52 * name: In house
53 * license: Apache-2.0
54 * ontology:
55 * name: EDAM
56 * schema: http://edamontology.org/EDAM.owl
58 """
60 def __init__(
61 self, input_pdb_path, output_pdb_path, properties=None, **kwargs
62 ) -> None:
63 properties = properties or {}
65 # Call parent class constructor
66 super().__init__(properties)
67 self.locals_var_dict = locals().copy()
69 # Input/Output files
70 self.io_dict = {
71 "in": {"input_pdb_path": input_pdb_path},
72 "out": {"output_pdb_path": output_pdb_path},
73 }
75 # Properties specific for BB
76 self.offset = float(properties.get("offset", 2.0))
77 self.box_coordinates = float(properties.get("box_coordinates", False))
78 self.properties = properties
80 # Check the properties
81 self.check_properties(properties)
82 self.check_arguments()
84 def check_data_params(self, out_log, err_log):
85 """Checks all the input/output paths and parameters"""
86 self.io_dict["in"]["input_pdb_path"] = check_input_path(
87 self.io_dict["in"]["input_pdb_path"],
88 "input_pdb_path",
89 self.out_log,
90 self.__class__.__name__,
91 )
92 self.io_dict["out"]["output_pdb_path"] = check_output_path(
93 self.io_dict["out"]["output_pdb_path"],
94 "output_pdb_path",
95 False,
96 self.out_log,
97 self.__class__.__name__,
98 )
100 @launchlogger
101 def launch(self) -> int:
102 """Execute the :class:`Box <utils.box.Box>` utils.box.Box object."""
104 # check input/output paths and parameters
105 self.check_data_params(self.out_log, self.err_log)
107 # Setup Biobb
108 if self.check_restart():
109 return 0
110 self.stage_files()
112 # check if cavity (pdb) or pocket (pqr)
113 input_type = PurePath(self.io_dict["in"]["input_pdb_path"]).suffix.lstrip(".")
114 if input_type == "pdb":
115 fu.log(
116 "Loading residue PDB selection from %s"
117 % (self.io_dict["in"]["input_pdb_path"]),
118 self.out_log,
119 self.global_log,
120 )
121 else:
122 fu.log(
123 "Loading pocket PQR selection from %s"
124 % (self.io_dict["in"]["input_pdb_path"]),
125 self.out_log,
126 self.global_log,
127 )
129 # get input_pdb_path atoms coordinates
130 selection_atoms_num = 0
131 x_coordslist = []
132 y_coordslist = []
133 z_coordslist = []
134 with open(self.io_dict["in"]["input_pdb_path"]) as infile:
135 for line in infile:
136 if line.startswith("HETATM") or line.startswith("ATOM"):
137 x_coordslist.append(float(line[31:38].strip()))
138 y_coordslist.append(float(line[39:46].strip()))
139 z_coordslist.append(float(line[47:54].strip()))
140 selection_atoms_num = selection_atoms_num + 1
142 # Compute binding site box size
144 # compute box center
145 selection_box_center = [
146 np.average(x_coordslist),
147 np.average(y_coordslist),
148 np.average(z_coordslist),
149 ]
150 fu.log(
151 "Binding site center (Angstroms): %10.3f%10.3f%10.3f"
152 % (
153 selection_box_center[0],
154 selection_box_center[1],
155 selection_box_center[2],
156 ),
157 self.out_log,
158 self.global_log,
159 )
161 # compute box size
162 selection_coords_max = np.amax(
163 [x_coordslist, y_coordslist, z_coordslist], axis=1
164 )
165 selection_box_size = selection_coords_max - selection_box_center
166 if self.offset:
167 fu.log(
168 "Adding %.1f Angstroms offset" % (self.offset),
169 self.out_log,
170 self.global_log,
171 )
172 selection_box_size = [c + self.offset for c in selection_box_size]
173 fu.log(
174 "Binding site size (Angstroms): %10.3f%10.3f%10.3f"
175 % (selection_box_size[0], selection_box_size[1], selection_box_size[2]),
176 self.out_log,
177 self.global_log,
178 )
180 # compute volume
181 vol = np.prod(selection_box_size) * 2**3
182 fu.log("Volume (cubic Angstroms): %.0f" % (vol), self.out_log, self.global_log)
184 # add box details as PDB remarks
185 remarks = "REMARK BOX CENTER:%10.3f%10.3f%10.3f" % (
186 selection_box_center[0],
187 selection_box_center[1],
188 selection_box_center[2],
189 )
190 remarks += " SIZE:%10.3f%10.3f%10.3f" % (
191 selection_box_size[0],
192 selection_box_size[1],
193 selection_box_size[2],
194 )
196 selection_box_coords_txt = ""
197 # add (optional) box coordinates as 8 ATOM records
198 if self.box_coordinates:
199 fu.log("Adding box coordinates", self.out_log, self.global_log)
200 selection_box_coords_txt = get_box_coordinates(
201 selection_box_center, selection_box_size
202 )
204 with open(self.io_dict["out"]["output_pdb_path"], "w") as f:
205 f.seek(0, 0)
206 f.write(remarks.rstrip("\r\n") + "\n" + selection_box_coords_txt)
208 fu.log(
209 "Saving output PDB file (with box setting annotations): %s"
210 % (self.io_dict["out"]["output_pdb_path"]),
211 self.out_log,
212 self.global_log,
213 )
215 # Copy files to host
216 self.copy_to_host()
218 # self.tmp_files.extend([self.stage_io_dict.get("unique_dir", "")])
219 self.remove_tmp_files()
221 self.check_arguments(output_files_created=True, raise_exception=False)
223 return 0
226def box(
227 input_pdb_path: str,
228 output_pdb_path: str,
229 properties: Optional[dict] = None,
230 **kwargs,
231) -> int:
232 """Execute the :class:`Box <utils.box.Box>` class and
233 execute the :meth:`launch() <utils.box.Box.launch>` method."""
235 return Box(
236 input_pdb_path=input_pdb_path,
237 output_pdb_path=output_pdb_path,
238 properties=properties,
239 **kwargs,
240 ).launch()
242 box.__doc__ = Box.__doc__
245def main():
246 """Command line execution of this building block. Please check the command line documentation."""
247 parser = argparse.ArgumentParser(
248 description="Sets the center and the size of a rectangular parallelepiped box around a set of residues from a given PDB or a pocket from a given PQR.",
249 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999),
250 )
251 parser.add_argument("--config", required=False, help="Configuration file")
253 # Specific args of each building block
254 required_args = parser.add_argument_group("required arguments")
255 required_args.add_argument(
256 "--input_pdb_path",
257 required=True,
258 help="PDB file containing a selection of residue numbers or PQR file containing the pocket. Accepted formats: pdb, pqr.",
259 )
260 required_args.add_argument(
261 "--output_pdb_path",
262 required=True,
263 help="PDB including the annotation of the box center and size as REMARKs. Accepted formats: pdb.",
264 )
266 args = parser.parse_args()
267 args.config = args.config or "{}"
268 properties = settings.ConfReader(config=args.config).get_prop_dic()
270 # Specific call of each building block
271 box(
272 input_pdb_path=args.input_pdb_path,
273 output_pdb_path=args.output_pdb_path,
274 properties=properties,
275 )
278if __name__ == "__main__":
279 main()