Coverage for biobb_structure_utils/utils/extract_heteroatoms.py: 75%

68 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2024-06-14 19:03 +0000

1#!/usr/bin/env python3 

2 

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

4import argparse 

5from biobb_common.configuration import settings 

6from biobb_common.generic.biobb_object import BiobbObject 

7from biobb_common.tools import file_utils as fu 

8from biobb_common.tools.file_utils import launchlogger 

9from Bio.PDB.PDBParser import PDBParser 

10from biobb_structure_utils.utils.common import check_input_path, check_format_heteroatoms, check_output_path, create_biopython_residue, create_output_file 

11 

12 

13class ExtractHeteroAtoms(BiobbObject): 

14 """ 

15 | biobb_structure_utils ExtractHeteroAtoms 

16 | Class to extract hetero-atoms from a 3D structure using Biopython. 

17 | Extracts a list of heteroatoms from a 3D structure using Biopython. 

18 

19 Args: 

20 input_structure_path (str): Input structure file path. File type: input. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/data/utils/extract_heteroatom.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476). 

21 output_heteroatom_path (str): Output heteroatom file path. File type: output. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/reference/utils/ref_extract_heteroatom.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476). 

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

23 * **heteroatoms** (*list*) - (None) List of dictionaries with the name | res_id | chain | model of the heteroatoms to be extracted. Format: [{"name": "ZZ7", "res_id": "302", "chain": "B", "model": "1"}]. If empty, all the heteroatoms of the structure will be returned. 

24 * **water** (*bool*) - (False) Add or not waters. 

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_structure_utils.utils.extract_heteroatoms import extract_heteroatoms 

33 prop = { 

34 'heteroatoms': [ 

35 { 

36 'name': 'ZZ7', 

37 'res_id': '302', 

38 'chain': 'B', 

39 'model': '1' 

40 } 

41 ] 

42 } 

43 extract_heteroatoms(input_structure_path='/path/to/myStructure.pdb', 

44 output_heteroatom_path='/path/to/newHeteroatom.pdb', 

45 properties=prop) 

46 

47 Info: 

48 * wrapped_software: 

49 * name: In house using Biopython 

50 * version: >=1.76 

51 * license: other 

52 * ontology: 

53 * name: EDAM 

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

55 

56 """ 

57 

58 def __init__(self, input_structure_path, output_heteroatom_path, properties=None, **kwargs) -> None: 

59 properties = properties or {} 

60 

61 # Call parent class constructor 

62 super().__init__(properties) 

63 self.locals_var_dict = locals().copy() 

64 

65 # Input/Output files 

66 self.io_dict = { 

67 "in": {"input_structure_path": input_structure_path}, 

68 "out": {"output_heteroatom_path": output_heteroatom_path} 

69 } 

70 

71 # Properties specific for BB 

72 self.heteroatoms = properties.get('heteroatoms', []) 

73 self.water = properties.get('water', False) 

74 self.properties = properties 

75 

76 # Check the properties 

77 self.check_properties(properties) 

78 self.check_arguments() 

79 

80 @launchlogger 

81 def launch(self) -> int: 

82 """Execute the :class:`ExtractHeteroAtoms <utils.extract_heteroatoms.ExtractHeteroAtoms>` utils.extract_heteroatoms.ExtractHeteroAtoms object.""" 

83 

84 self.io_dict['in']['input_structure_path'] = check_input_path(self.io_dict['in']['input_structure_path'], 

85 self.out_log, self.__class__.__name__) 

86 self.io_dict['out']['output_heteroatom_path'] = check_output_path(self.io_dict['out']['output_heteroatom_path'], 

87 self.out_log, self.__class__.__name__) 

88 

89 # Setup Biobb 

90 if self.check_restart(): 

91 return 0 

92 self.stage_files() 

93 

94 # Business code 

95 # get list of heteroatoms from properties 

96 list_heteroatoms = check_format_heteroatoms(self.heteroatoms, self.out_log) 

97 

98 # load input into BioPython structure 

99 structure = PDBParser(QUIET=True).get_structure('structure', self.stage_io_dict['in']['input_structure_path']) 

100 

101 new_structure = [] 

102 # get desired heteroatoms 

103 for residue in structure.get_residues(): 

104 r = create_biopython_residue(residue) 

105 if list_heteroatoms: 

106 for het in list_heteroatoms: 

107 match = True 

108 for code in het['code']: 

109 if het[code].strip() != r[code].strip(): 

110 match = False 

111 break 

112 

113 if match: 

114 if not self.water and (r['name'] == 'HOH' or r['name'] == 'SOL' or r['name'] == 'WAT'): 

115 pass 

116 else: 

117 new_structure.append(r) 

118 else: 

119 if not self.water and (r['name'] == 'HOH' or r['name'] == 'SOL' or r['name'] == 'WAT'): 

120 pass 

121 else: 

122 new_structure.append(r) 

123 

124 # if not heteroatoms found in structure, raise exit 

125 if not new_structure: 

126 fu.log(self.__class__.__name__ + ': The heteroatoms given by user were not found in input structure', self.out_log) 

127 raise SystemExit(self.__class__.__name__ + ': The heteroatoms given by user were not found in input structure') 

128 

129 create_output_file(1, self.stage_io_dict['in']['input_structure_path'], new_structure, self.stage_io_dict['out']['output_heteroatom_path'], self.out_log) 

130 

131 self.return_code = 0 

132 

133 # Copy files to host 

134 self.copy_to_host() 

135 

136 # Remove temporal files 

137 self.tmp_files.append(self.stage_io_dict.get("unique_dir")) 

138 self.remove_tmp_files() 

139 

140 self.check_arguments(output_files_created=True, raise_exception=False) 

141 

142 return self.return_code 

143 

144 

145def extract_heteroatoms(input_structure_path: str, output_heteroatom_path: str, properties: dict = None, **kwargs) -> int: 

146 """Execute the :class:`ExtractHeteroAtoms <utils.extract_heteroatoms.ExtractHeteroAtoms>` class and 

147 execute the :meth:`launch() <utils.extract_heteroatoms.ExtractHeteroAtoms.launch>` method.""" 

148 

149 return ExtractHeteroAtoms(input_structure_path=input_structure_path, 

150 output_heteroatom_path=output_heteroatom_path, 

151 properties=properties, **kwargs).launch() 

152 

153 

154def main(): 

155 """Command line execution of this building block. Please check the command line documentation.""" 

156 parser = argparse.ArgumentParser(description="Extract a list of heteroatoms from a 3D structure.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

157 parser.add_argument('-c', '--config', required=False, help="This file can be a YAML file, JSON file or JSON string") 

158 

159 # Specific args of each building block 

160 required_args = parser.add_argument_group('required arguments') 

161 required_args.add_argument('-i', '--input_structure_path', required=True, help="Input structure file path. Accepted formats: pdb.") 

162 required_args.add_argument('-o', '--output_heteroatom_path', required=True, help="Output heteroatom file path. Accepted formats: pdb.") 

163 

164 args = parser.parse_args() 

165 config = args.config if args.config else None 

166 properties = settings.ConfReader(config=config).get_prop_dic() 

167 

168 # Specific call of each building block 

169 extract_heteroatoms(input_structure_path=args.input_structure_path, 

170 output_heteroatom_path=args.output_heteroatom_path, 

171 properties=properties) 

172 

173 

174if __name__ == '__main__': 

175 main()