Coverage for biobb_structure_utils / utils / extract_residues.py: 91%

53 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2025-12-22 13:23 +0000

1#!/usr/bin/env python3 

2 

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

4from typing import Optional 

5from Bio.PDB.PDBParser import PDBParser 

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 

9 

10from biobb_structure_utils.utils.common import ( 

11 _from_string_to_list, 

12 check_input_path, 

13 check_output_path, 

14 create_biopython_residue, 

15 create_output_file, 

16 create_residues_list, 

17) 

18 

19 

20class ExtractResidues(BiobbObject): 

21 """ 

22 | biobb_structure_utils ExtractResidues 

23 | Class to extract residues from a 3D structure using Biopython. 

24 | Extracts a list of residues from a 3D structure using Biopython. 

25 

26 Args: 

27 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). 

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

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

30 * **residues** (*list*) - (None) List of comma separated res_id (will extract all residues that match the res_id) or list of dictionaries with the name | res_id | chain | model of the residues to be extracted. Format: [{"name": "HIS", "res_id": "72", "chain": "A", "model": "1"}]. 

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

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

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

34 

35 Examples: 

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

37 

38 from biobb_structure_utils.utils.extract_residues import extract_residues 

39 prop = { 

40 'residues': [ 

41 { 

42 'name': 'HIS', 

43 'res_id': '72', 

44 'chain': 'A', 

45 'model': '1' 

46 } 

47 ] 

48 } 

49 extract_residues(input_structure_path='/path/to/myStructure.pdb', 

50 output_residues_path='/path/to/newResidues.pdb', 

51 properties=prop) 

52 

53 Info: 

54 * wrapped_software: 

55 * name: In house using Biopython 

56 * version: >=1.79 

57 * license: other 

58 * ontology: 

59 * name: EDAM 

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

61 

62 """ 

63 

64 def __init__( 

65 self, input_structure_path, output_residues_path, properties=None, **kwargs 

66 ) -> None: 

67 properties = properties or {} 

68 

69 # Call parent class constructor 

70 super().__init__(properties) 

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

72 

73 # Input/Output files 

74 self.io_dict = { 

75 "in": {"input_structure_path": input_structure_path}, 

76 "out": {"output_residues_path": output_residues_path}, 

77 } 

78 

79 # Properties specific for BB 

80 self.residues = _from_string_to_list(properties.get("residues", [])) 

81 self.properties = properties 

82 

83 # Check the properties 

84 self.check_properties(properties) 

85 self.check_arguments() 

86 

87 @launchlogger 

88 def launch(self) -> int: 

89 """Execute the :class:`ExtractResidues <utils.extract_residues.ExtractResidues>` utils.extract_residues.ExtractResidues object.""" 

90 

91 self.io_dict["in"]["input_structure_path"] = check_input_path( 

92 self.io_dict["in"]["input_structure_path"], 

93 self.out_log, 

94 self.__class__.__name__, 

95 ) 

96 self.io_dict["out"]["output_residues_path"] = check_output_path( 

97 self.io_dict["out"]["output_residues_path"], 

98 self.out_log, 

99 self.__class__.__name__, 

100 ) 

101 

102 # Setup Biobb 

103 if self.check_restart(): 

104 return 0 

105 self.stage_files() 

106 

107 # Business code 

108 # get list of Residues from properties 

109 list_residues = create_residues_list(self.residues, self.out_log) 

110 

111 # load input into BioPython structure 

112 structure = PDBParser(QUIET=True).get_structure( 

113 "structure", self.stage_io_dict["in"]["input_structure_path"] 

114 ) 

115 

116 new_structure = [] 

117 # get desired residues 

118 for residue in structure.get_residues(): 

119 r = create_biopython_residue(residue) 

120 if list_residues: 

121 for res in list_residues: 

122 match = True 

123 for code in res["code"]: 

124 if res[code].strip() != r[code].strip(): 

125 match = False 

126 break 

127 if match: 

128 new_structure.append(r) 

129 else: 

130 new_structure.append(r) 

131 

132 # if not residues found in structure, raise exit 

133 if not new_structure: 

134 fu.log( 

135 self.__class__.__name__ + ": The residues given by user were not found in input structure", 

136 self.out_log, 

137 ) 

138 raise SystemExit( 

139 self.__class__.__name__ + ": The residues given by user were not found in input structure" 

140 ) 

141 

142 create_output_file( 

143 2, 

144 self.stage_io_dict["in"]["input_structure_path"], 

145 new_structure, 

146 self.stage_io_dict["out"]["output_residues_path"], 

147 self.out_log, 

148 ) 

149 

150 self.return_code = 0 

151 

152 # Copy files to host 

153 self.copy_to_host() 

154 

155 # Remove temporal files 

156 self.remove_tmp_files() 

157 

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

159 

160 return self.return_code 

161 

162 

163def extract_residues( 

164 input_structure_path: str, 

165 output_residues_path: str, 

166 properties: Optional[dict] = None, 

167 **kwargs, 

168) -> int: 

169 """Create the :class:`ExtractResidues <utils.extract_residues.ExtractResidues>` class and 

170 execute the :meth:`launch() <utils.extract_residues.ExtractResidues.launch>` method.""" 

171 return ExtractResidues(**dict(locals())).launch() 

172 

173 

174extract_residues.__doc__ = ExtractResidues.__doc__ 

175main = ExtractResidues.get_main(extract_residues, "Extract a list of residues from a 3D structure.") 

176 

177if __name__ == "__main__": 

178 main()