Coverage for biobb_vs/gnina/gnina_select_pose.py: 93%

43 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 GninaSelectPose class and the command line interface.""" 

4from typing import Optional 

5 

6from biobb_common.generic.biobb_object import BiobbObject, launcher 

7from biobb_common.tools import file_utils as fu 

8 

9from biobb_vs.gnina.common import check_gzip_extension, open_sdf, read_sdf_records, to_number 

10 

11 

12class GninaSelectPose(BiobbObject): 

13 """ 

14 | biobb_vs GninaSelectPose 

15 | Selects a single pose in the output of the gnina_run building block. 

16 | Extracts one pose out of the multi record SDF file written by the gnina_run building block, copying the record verbatim. 

17 

18 Args: 

19 input_sdf_path (str): Path to the SDF file with the docked poses written by the gnina_run building block. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/gnina/gnina_poses.sdf>`_. Accepted formats: sdf (edam:format_3814), gz (edam:format_3989). 

20 output_sdf_path (str): Path to the output SDF file with the selected pose. File type: output. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/reference/gnina/ref_output_pose.sdf>`_. Accepted formats: sdf (edam:format_3814), gz (edam:format_3989). 

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

22 * **pose** (*int*) - (1) [1~10000|1] Rank of the pose to extract, counted over the poses left after ligand has been applied and sort_by has been honoured. 

23 * **ligand** (*int*) - (None) [1~1000000|1] Index of the ligand whose poses are considered, following the order of the ligands in the file gnina docked. All poses in the file are considered when unset. 

24 * **sort_by** (*str*) - (None) Score to reorder the poses by before one is picked. The poses are taken in the order gnina wrote them when unset, which is already gnina's own ranking. Note that this reorders only the poses present in the file, so it is not equivalent to the pose_sort_order property of gnina_run, which reorders the whole internal pool before the redundancy filter and the num_modes cutoff discard poses. Values: CNNscore (network pose score, highest first), CNNaffinity (network predicted affinity, highest first), minimizedAffinity (empirical affinity in kcal/mol, lowest first). 

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

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

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

28 

29 Examples: 

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

31 

32 from biobb_vs.gnina.gnina_select_pose import gnina_select_pose 

33 prop = { 

34 'pose': 1, 

35 'sort_by': 'CNNaffinity' 

36 } 

37 gnina_select_pose(input_sdf_path='/path/to/myPoses.sdf', 

38 output_sdf_path='/path/to/myBestPose.sdf', 

39 properties=prop) 

40 

41 Info: 

42 * wrapped_software: 

43 * name: In house 

44 * license: Apache-2.0 

45 * ontology: 

46 * name: EDAM 

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

48 

49 """ 

50 

51 # score to sort by, mapped to whether the highest value is the best one 

52 SORT_ORDERS = { 

53 'CNNscore': True, 

54 'CNNaffinity': True, 

55 'minimizedAffinity': False 

56 } 

57 

58 def __init__(self, input_sdf_path: str, output_sdf_path: str, 

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

60 super().__init__(**locals()) 

61 

62 def prepare(self): 

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

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

65 check_gzip_extension(self.io_dict["in"]["input_sdf_path"], "input_sdf_path", self.out_log, self.__class__.__name__) 

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

67 

68 if self.sort_by is not None and self.sort_by not in self.SORT_ORDERS: 

69 fu.log(self.__class__.__name__ + ': Unknown sort_by %s, use one of %s, exiting' % (self.sort_by, ', '.join(self.SORT_ORDERS)), self.out_log) 

70 raise SystemExit(self.__class__.__name__ + ': Unknown sort_by %s' % self.sort_by) 

71 

72 def select_record(self, records): 

73 """ Narrows the records down to the requested ligand, reorders them and picks one """ 

74 

75 if self.ligand is not None: 

76 records = [record for record in records if record['ligand_index'] == self.ligand] 

77 if not records: 

78 fu.log(self.__class__.__name__ + ': No poses found for ligand %s, exiting' % self.ligand, self.out_log) 

79 raise SystemExit(self.__class__.__name__ + ': No poses found for ligand %s' % self.ligand) 

80 fu.log('%d pose(s) found for ligand %s' % (len(records), self.ligand), self.out_log) 

81 

82 if self.sort_by: 

83 missing = [record for record in records if self.sort_by not in record['data']] 

84 if missing: 

85 fu.log(self.__class__.__name__ + ': %s is missing from some poses, gnina only writes it for certain cnn_scoring values, exiting' % self.sort_by, self.out_log) 

86 raise SystemExit(self.__class__.__name__ + ': %s is missing from some poses' % self.sort_by) 

87 records = sorted(records, 

88 key=lambda record: to_number(record['data'][self.sort_by]), 

89 reverse=self.SORT_ORDERS[self.sort_by]) 

90 fu.log('Poses reordered by %s' % self.sort_by, self.out_log) 

91 

92 if self.pose < 1 or self.pose > len(records): 

93 fu.log(self.__class__.__name__ + ': pose %s is out of range, only %d pose(s) to choose from, exiting' % (self.pose, len(records)), self.out_log) 

94 raise SystemExit(self.__class__.__name__ + ': pose %s is out of range, only %d pose(s) to choose from' % (self.pose, len(records))) 

95 

96 return records[self.pose - 1] 

97 

98 def stage_files(self) -> None: 

99 """The block does not use the sandbox: there are no files to stage.""" 

100 

101 def run(self) -> None: 

102 """Execute the :class:`GninaSelectPose <gnina.gnina_select_pose.GninaSelectPose>` gnina.gnina_select_pose.GninaSelectPose object.""" 

103 

104 records = read_sdf_records(self.io_dict["in"]["input_sdf_path"]) 

105 fu.log('%d pose(s) read from %s' % (len(records), self.io_dict["in"]["input_sdf_path"]), self.out_log) 

106 

107 record = self.select_record(records) 

108 

109 fu.log('Saving pose %s of ligand %s (%s) to %s file' % ( 

110 record['pose'], record['ligand_index'], record['name'], 

111 self.io_dict["out"]["output_sdf_path"]), self.out_log) 

112 

113 # the record is copied as it stands, scores included 

114 with open_sdf(self.io_dict["out"]["output_sdf_path"], 'wt') as output_file: 

115 output_file.write(record['text']) 

116 

117 

118gnina_select_pose = launcher(GninaSelectPose) 

119 

120 

121if __name__ == '__main__': 

122 GninaSelectPose.main()