Coverage for biobb_vs/utils/box.py: 96%
52 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 Box class and the command line interface."""
4from pathlib import PurePath
5from typing import Optional
6import numpy as np
7from biobb_common.generic.biobb_object import BiobbObject, launcher
8from biobb_common.tools import file_utils as fu
10from biobb_vs.utils.common import (
11 get_box_coordinates,
12)
15class Box(BiobbObject):
16 """
17 | biobb_vs Box
18 | This class sets the center and the size of a rectangular parallelepiped box around a set of residues or a pocket.
19 | 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.
21 Args:
22 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).
23 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).
24 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
25 * **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.
26 * **box_coordinates** (*bool*) - (False) Add box coordinates as 8 ATOM records.
27 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
28 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
29 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
31 Examples:
32 This is a use example of how to use the building block from Python::
34 from biobb_vs.utils.box import box
35 prop = {
36 'offset': 2,
37 'box_coordinates': True
38 }
39 box(input_pdb_path='/path/to/myPocket.pqr',
40 output_pdb_path='/path/to/newBox.pdb',
41 properties=prop)
43 Info:
44 * wrapped_software:
45 * name: In house
46 * license: Apache-2.0
47 * ontology:
48 * name: EDAM
49 * schema: http://edamontology.org/EDAM.owl
51 """
53 def __init__(
54 self, input_pdb_path: str, output_pdb_path: str, properties: Optional[dict] = None, **kwargs
55 ) -> None:
56 super().__init__(**locals())
58 # Properties specific for BB
59 self.offset = float(self.offset)
60 self.box_coordinates = float(self.box_coordinates)
62 def stage_files(self) -> None:
63 """The block does not use the sandbox: there are no files to stage."""
65 def run(self) -> None:
66 """Execute the :class:`Box <utils.box.Box>` utils.box.Box object."""
68 # check if cavity (pdb) or pocket (pqr)
69 input_type = PurePath(self.io_dict["in"]["input_pdb_path"]).suffix.lstrip(".")
70 if input_type == "pdb":
71 fu.log(
72 "Loading residue PDB selection from %s"
73 % (self.io_dict["in"]["input_pdb_path"]),
74 self.out_log,
75 self.global_log,
76 )
77 else:
78 fu.log(
79 "Loading pocket PQR selection from %s"
80 % (self.io_dict["in"]["input_pdb_path"]),
81 self.out_log,
82 self.global_log,
83 )
85 # get input_pdb_path atoms coordinates
86 selection_atoms_num = 0
87 x_coordslist = []
88 y_coordslist = []
89 z_coordslist = []
90 with open(self.io_dict["in"]["input_pdb_path"]) as infile:
91 for line in infile:
92 if line.startswith("HETATM") or line.startswith("ATOM"):
93 x_coordslist.append(float(line[30:38].strip()))
94 y_coordslist.append(float(line[38:46].strip()))
95 z_coordslist.append(float(line[46:54].strip()))
96 selection_atoms_num = selection_atoms_num + 1
98 # Compute binding site box size
100 # compute box center
101 selection_box_center = [
102 np.average(x_coordslist),
103 np.average(y_coordslist),
104 np.average(z_coordslist),
105 ]
106 fu.log(
107 "Binding site center (Angstroms): %10.3f%10.3f%10.3f"
108 % (
109 selection_box_center[0],
110 selection_box_center[1],
111 selection_box_center[2],
112 ),
113 self.out_log,
114 self.global_log,
115 )
117 # compute box size
118 selection_coords_max = np.amax(
119 [x_coordslist, y_coordslist, z_coordslist], axis=1
120 )
121 selection_box_size = selection_coords_max - selection_box_center
122 if self.offset:
123 fu.log(
124 "Adding %.1f Angstroms offset" % (self.offset),
125 self.out_log,
126 self.global_log,
127 )
128 selection_box_size = [c + self.offset for c in selection_box_size]
130 # SIZE is written as the full edge length, which is what Vina reads from
131 # --size_x/y/z. selection_box_size stays a half-extent because that is
132 # what the corner coordinates and the volume are computed from.
133 selection_box_edge = [2 * side for side in selection_box_size]
134 fu.log(
135 "Binding site box edge lengths (Angstroms): %10.3f%10.3f%10.3f"
136 % (selection_box_edge[0], selection_box_edge[1], selection_box_edge[2]),
137 self.out_log,
138 self.global_log,
139 )
141 # compute volume
142 vol = np.prod(selection_box_size) * 2**3
143 fu.log("Volume (cubic Angstroms): %.0f" % (vol), self.out_log, self.global_log)
145 # add box details as PDB remarks
146 remarks = "REMARK BOX CENTER:%10.3f%10.3f%10.3f" % (
147 selection_box_center[0],
148 selection_box_center[1],
149 selection_box_center[2],
150 )
151 remarks += " SIZE:%10.3f%10.3f%10.3f" % (
152 selection_box_edge[0],
153 selection_box_edge[1],
154 selection_box_edge[2],
155 )
157 selection_box_coords_txt = ""
158 # add (optional) box coordinates as 8 ATOM records
159 if self.box_coordinates:
160 fu.log("Adding box coordinates", self.out_log, self.global_log)
161 selection_box_coords_txt = get_box_coordinates(
162 selection_box_center, selection_box_size
163 )
165 with open(self.io_dict["out"]["output_pdb_path"], "w") as f:
166 f.seek(0, 0)
167 f.write(remarks.rstrip("\r\n") + "\n" + selection_box_coords_txt)
169 fu.log(
170 "Saving output PDB file (with box setting annotations): %s"
171 % (self.io_dict["out"]["output_pdb_path"]),
172 self.out_log,
173 self.global_log,
174 )
177box = launcher(Box)
180if __name__ == "__main__":
181 Box.main()