Coverage for biobb_vs/gnina/gnina_run.py: 25%

60 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-03 15:52 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the GninaRun class and the command line interface.""" 

4from pathlib import PurePath 

5from typing import Optional 

6 

7from biobb_common.generic.biobb_object import BiobbObject, launcher 

8from biobb_common.tools import file_utils as fu 

9 

10from biobb_vs.gnina.common import check_gzip_extension, process_output_gnina 

11 

12 

13class GninaRun(BiobbObject): 

14 """ 

15 | biobb_vs GninaRun 

16 | Wrapper of the gnina software. 

17 | This class performs docking of a ligand to a receptor, optionally rescoring the poses with a convolutional neural network, via the `gnina <https://github.com/gnina/gnina>`_ software. 

18 

19 Args: 

20 input_ligand_path (str): Path to the input ligand. It may hold several ligands and it must hold genuine 3D coordinates, as gnina samples torsions but never bond lengths, bond angles or ring conformations. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/gnina/gnina_ligand.sdf>`_. Accepted formats: sdf (edam:format_3814), mol2 (edam:format_3816), pdb (edam:format_1476), pdbqt (edam:format_1476). 

21 input_receptor_path (str): Path to the input receptor. Every atom of this file is treated as rigid receptor, so any crystal ligand must be removed beforehand. Provide a PDBQT file for full control over protonation, as PDBQT input is passed to gnina unmodified. Charges are not taken into account, just hydrogen donor/acceptor character which depends on the protonation state. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/vina/vina_receptor.pdbqt>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476). 

22 input_box_path (str) (Optional): Path to the PDB file with the box center and size annotated as a REMARK, as written by the box and box_residues building blocks. Mutually exclusive with input_autobox_path. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/vina/vina_box.pdb>`_. Accepted formats: pdb (edam:format_1476). 

23 input_autobox_path (str) (Optional): Path to a reference structure whose bounding coordinates define the docking box, for example a crystal ligand, an fpocket pocket or the whole receptor. It only needs atoms with Cartesian coordinates, it does not need to be a real molecule. Mutually exclusive with input_box_path. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/gnina/gnina_autobox.pdb>`_. Accepted formats: sdf (edam:format_3814), mol2 (edam:format_3816), pdb (edam:format_1476), pdbqt (edam:format_1476), pqr (edam:format_1476). 

24 output_sdf_path (str): Path to the output file with the docked poses and their scores as SD data fields. Use a .sdf.gz extension to obtain gzip compressed output. File type: output. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/reference/gnina/ref_output_gnina.sdf>`_. Accepted formats: sdf (edam:format_3814), gz (edam:format_3989). 

25 output_summary_path (str) (Optional): Path to the JSON summary file, holding one entry per output pose with the ligand it belongs to and every score gnina assigned to it. File type: output. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/reference/gnina/ref_output_summary.json>`_. Accepted formats: json (edam:format_3464). 

26 output_log_path (str) (Optional): Path to the log file written by gnina. File type: output. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/reference/gnina/ref_output_gnina.log>`_. Accepted formats: log (edam:format_2330). 

27 properties (dic - Python dictionary object containing the tool parameters, not input/output files): 

28 * **cpu** (*int*) - (1) [1~1000|1] Number of CPU cores to use. Keep it lower than or equal to exhaustiveness, and always set it explicitly on a shared machine. 

29 * **exhaustiveness** (*int*) - (8) [1~10000|1] Number of independent Monte Carlo search chains. This is the main sampling knob, but it gives diminishing returns past the default for a targeted pocket. 

30 * **num_modes** (*int*) - (9) [1~1000|1] Maximum number of binding modes written out. 

31 * **min_rmsd_filter** (*float*) - (1.0) [0~100|0.1] RMSD in Angstroms below which a pose is dropped as redundant with a better ranked one. 

32 * **num_mc_saved** (*int*) - (None) [1~10000|1] Number of top poses retained in each Monte Carlo chain, gnina defaults to 50 when unset. 

33 * **seed** (*int*) - (None) Explicit random seed. Docking is stochastic, so set it for reproducible runs. 

34 * **scoring** (*str*) - (None) Built-in empirical scoring function, gnina uses its own default when unset. Values: default (the gnina default empirical scoring function), vina (the AutoDock Vina scoring function), vinardo (a reparameterization of the Vina terms that often does better for virtual screening), ad4_scoring (the AutoDock4 scoring function), dkoes_fast (a fast variant of the dkoes scoring function), dkoes_scoring (the dkoes scoring function), dkoes_scoring_old (the legacy dkoes scoring function). 

35 * **cnn_scoring** (*str*) - (None) Where the convolutional neural network is used in the pipeline, gnina defaults to rescore when unset. Values: none (empirical scoring only throughout, by far the fastest), rescore (the network only re-ranks the final pool of poses), refinement (the network also locally minimizes poses after the Monte Carlo search, around ten times slower), metrorescore (network rescoring combined with Metropolis sampling), metrorefine (network refinement combined with Metropolis sampling), all (the network scores the whole search, very slow). 

36 * **cnn** (*str*) - (None) Name of a built-in convolutional neural network model, or a name ending in _ensemble to evaluate every built-in model sharing that prefix. gnina defaults to an ensemble of three models when unset. 

37 * **pose_sort_order** (*str*) - (None) How the internal pose pool is sorted before the redundancy filter and the num_modes cutoff are applied, so it can surface a different set of poses and not merely reorder them. gnina defaults to CNNscore when unset. Values: CNNscore (sort by network pose score, which answers whether a pose is right), CNNaffinity (sort by predicted affinity, which is what ranks compounds in a screen), Energy (sort by empirical energy). 

38 * **autobox_add** (*float*) - (None) [0~100|0.1] Buffer in Angstroms added on every side of the box derived from input_autobox_path, gnina defaults to 4 when unset. A larger box does not slow gnina down, but it does loosen the constraint on sampling. 

39 * **autobox_extend** (*bool*) - (None) Enlarge the box derived from input_autobox_path when needed so the input ligand can rotate freely inside it, gnina enables this when unset. 

40 * **minimize** (*bool*) - (False) Energy minimize the poses given in input_ligand_path instead of searching for new ones. 

41 * **score_only** (*bool*) - (False) Score the poses given in input_ligand_path without searching or minimizing. 

42 * **local_only** (*bool*) - (False) Restrict the search to a local one inside the box. 

43 * **no_gpu** (*bool*) - (False) Disable GPU acceleration even when a GPU is available. 

44 * **device** (*int*) - (None) [0~16|1] Index of the GPU device to use. 

45 * **quiet** (*bool*) - (False) Suppress the gnina output messages. 

46 * **binary_path** (*str*) - ('gnina') Path to the gnina executable in your local computer. gnina is not distributed with this package, install it from its binary release or run it through a container. 

47 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files. 

48 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist. 

49 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

50 * **container_path** (*str*) - (None) Container path definition. 

51 * **container_image** (*str*) - ('gnina/gnina:latest') Container image definition. 

52 * **container_volume_path** (*str*) - ('/data') Container volume path definition. 

53 * **container_user_id** (*str*) - (None) Container user_id definition. 

54 * **container_shell_path** (*str*) - ('/bin/bash -c') Path to default shell inside the container. 

55 

56 Examples: 

57 This is a use example of how to use the building block from Python:: 

58 

59 from biobb_vs.gnina.gnina_run import gnina_run 

60 prop = { 

61 'cnn_scoring': 'rescore', 

62 'scoring': 'vinardo', 

63 'exhaustiveness': 8, 

64 'cpu': 4, 

65 'seed': 42 

66 } 

67 gnina_run(input_ligand_path='/path/to/myLigand.sdf', 

68 input_receptor_path='/path/to/myReceptor.pdbqt', 

69 input_box_path='/path/to/myBox.pdb', 

70 output_sdf_path='/path/to/newPoses.sdf', 

71 output_summary_path='/path/to/newSummary.json', 

72 output_log_path='/path/to/newLog.log', 

73 properties=prop) 

74 

75 Instead of a box file, the docking box may be drawn around a reference structure, 

76 which is gnina's own idiom and needs no box file at all. An fpocket pocket works as 

77 a reference, and so does the receptor itself for whole protein docking:: 

78 

79 gnina_run(input_ligand_path='/path/to/myLigand.sdf', 

80 input_receptor_path='/path/to/myReceptor.pdbqt', 

81 input_autobox_path='/path/to/myPocket.pqr', 

82 output_sdf_path='/path/to/newPoses.sdf', 

83 properties={'autobox_add': 4}) 

84 

85 To reach a GPU from inside a container, ask the container runtime for it through the 

86 container_generic_command property, as in {'container_path': 'docker', 

87 'container_generic_command': 'run --gpus all'} for Docker or 'run --nv' for Singularity. 

88 

89 Info: 

90 * wrapped_software: 

91 * name: gnina 

92 * version: >=1.3 

93 * license: Apache-2.0 and GPL-2.0 

94 * ontology: 

95 * name: EDAM 

96 * schema: http://edamontology.org/EDAM.owl 

97 

98 """ 

99 

100 # gnina flags taking a value, as (flag, property name) pairs 

101 VALUE_FLAGS = ( 

102 ("--cpu", "cpu"), 

103 ("--exhaustiveness", "exhaustiveness"), 

104 ("--num_modes", "num_modes"), 

105 ("--min_rmsd_filter", "min_rmsd_filter"), 

106 ("--num_mc_saved", "num_mc_saved"), 

107 ("--seed", "seed"), 

108 ("--scoring", "scoring"), 

109 ("--cnn_scoring", "cnn_scoring"), 

110 ("--cnn", "cnn"), 

111 ("--pose_sort_order", "pose_sort_order"), 

112 ("--device", "device"), 

113 ) 

114 

115 # gnina flags that are bare switches 

116 SWITCH_FLAGS = ( 

117 ("--minimize", "minimize"), 

118 ("--score_only", "score_only"), 

119 ("--local_only", "local_only"), 

120 ("--no_gpu", "no_gpu"), 

121 ("--quiet", "quiet"), 

122 ) 

123 

124 def __init__(self, input_ligand_path: str, input_receptor_path: str, output_sdf_path: str, 

125 input_box_path: Optional[str] = None, input_autobox_path: Optional[str] = None, 

126 output_summary_path: Optional[str] = None, output_log_path: Optional[str] = None, 

127 properties: Optional[dict] = None, **kwargs) -> None: 

128 super().__init__(**locals()) 

129 

130 def prepare(self): 

131 """ Checks all the input/output paths and parameters """ 

132 # a gzip compressed SDF file must be named .sdf.gz 

133 check_gzip_extension(self.io_dict["out"]["output_sdf_path"], "output_sdf_path", self.out_log, self.__class__.__name__) 

134 

135 # gnina needs a search space, given either as a box file or as a reference structure 

136 if bool(self.io_dict["in"]["input_box_path"]) == bool(self.io_dict["in"]["input_autobox_path"]): 

137 fu.log(self.__class__.__name__ + ': Provide exactly one of input_box_path or input_autobox_path to define the docking box, exiting', self.out_log) 

138 raise SystemExit(self.__class__.__name__ + ': Provide exactly one of input_box_path or input_autobox_path to define the docking box') 

139 

140 if self.io_dict["in"]["input_box_path"]: 

141 # parse it now so an unusable box file is caught before any work is done 

142 self.calculate_box(self.io_dict["in"]["input_box_path"]) 

143 

144 def calculate_box(self, box_file_path): 

145 """ Reads the docking box out of the REMARK line written by the box building blocks 

146 

147 Returns the box center and its edge lengths, as strings. SIZE is the 

148 full edge length of the box, which is what gnina expects in 

149 --size_x/y/z, so it is passed through unchanged. 

150 

151 Does not log, as it is called both to validate the box file up front and 

152 to build the command line. 

153 """ 

154 with open(box_file_path, "r") as box_file: 

155 for line in box_file: 

156 if line.startswith("REMARK BOX CENTER"): 

157 fields = line.split() 

158 center = [float(coord) for coord in fields[3:6]] 

159 size = [float(side) for side in fields[-3:]] 

160 return [str(coord) for coord in center], [str(side) for side in size] 

161 

162 fu.log(self.__class__.__name__ + ': No REMARK BOX CENTER line found in %s, exiting' % box_file_path, self.out_log) 

163 raise SystemExit(self.__class__.__name__ + ': No REMARK BOX CENTER line found in %s' % box_file_path) 

164 

165 def build_cmd(self) -> list: 

166 """ Builds the gnina command line out of the staged files and the properties 

167 

168 Kept apart from :meth:`launch` so the command can be inspected without 

169 running gnina. Must be called after ``stage_files``. 

170 """ 

171 

172 cmd = [self.binary_path, 

173 "--receptor", self.stage_io_dict["in"]["input_receptor_path"], 

174 "--ligand", self.stage_io_dict["in"]["input_ligand_path"], 

175 "--out", self.stage_io_dict["out"]["output_sdf_path"]] 

176 

177 # the box file is read here and never handed to gnina, so it is taken 

178 # from io_dict and not from the staged copy 

179 if self.io_dict["in"].get("input_box_path"): 

180 box_path = self.io_dict["in"]["input_box_path"] 

181 center, size = self.calculate_box(box_path) 

182 fu.log('Docking box center %s and edge lengths %s, read from %s' % ( 

183 ' '.join('%.3f' % float(coord) for coord in center), 

184 ' '.join('%.3f' % float(side) for side in size), 

185 PurePath(box_path).name), self.out_log) 

186 cmd.extend(["--center_x", center[0], "--center_y", center[1], "--center_z", center[2], 

187 "--size_x", size[0], "--size_y", size[1], "--size_z", size[2]]) 

188 else: 

189 # gnina opens the reference structure, so this one must be the staged copy 

190 cmd.extend(["--autobox_ligand", self.stage_io_dict["in"]["input_autobox_path"]]) 

191 if self.autobox_add is not None: 

192 cmd.extend(["--autobox_add", str(self.autobox_add)]) 

193 if self.autobox_extend is not None: 

194 cmd.extend(["--autobox_extend", "1" if self.autobox_extend else "0"]) 

195 

196 # optional outputs are absent from stage_io_dict when they were not requested 

197 if self.stage_io_dict["out"].get("output_log_path"): 

198 cmd.extend(["--log", self.stage_io_dict["out"]["output_log_path"]]) 

199 

200 for flag, prop in self.VALUE_FLAGS: 

201 value = getattr(self, prop) 

202 if value is not None: 

203 cmd.extend([flag, str(value)]) 

204 

205 for flag, prop in self.SWITCH_FLAGS: 

206 if getattr(self, prop): 

207 cmd.append(flag) 

208 

209 return cmd 

210 

211 def run(self) -> None: 

212 """Execute the :class:`GninaRun <gnina.gnina_run.GninaRun>` gnina.gnina_run.GninaRun object.""" 

213 

214 # create cmd 

215 self.cmd = self.build_cmd() 

216 

217 fu.log('Executing gnina', self.out_log, self.global_log) 

218 

219 # Run Biobb block 

220 self.run_biobb() 

221 

222 # Write the output summary from the poses of the output sdf file. 

223 if self.return_code == 0: 

224 if self.io_dict["out"].get("output_summary_path"): 

225 process_output_gnina(self.sandbox_file("output_sdf_path"), 

226 self.sandbox_file("output_summary_path"), 

227 self.out_log, 

228 self.__class__.__name__) 

229 else: 

230 fu.log('gnina ended with return code %s, no summary was generated' % self.return_code, self.out_log, self.global_log) 

231 

232 

233gnina_run = launcher(GninaRun) 

234 

235 

236if __name__ == '__main__': 

237 GninaRun.main()