Coverage for biobb_structure_utils / utils / renumber_structure.py: 97%

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

4import json 

5from pathlib import Path 

6from typing import Optional 

7from biobb_common.generic.biobb_object import BiobbObject 

8from biobb_common.tools import file_utils as fu 

9from biobb_common.tools.file_utils import launchlogger 

10 

11from biobb_structure_utils.gro_lib.gro import Gro 

12from biobb_structure_utils.utils.common import PDB_SERIAL_RECORDS 

13 

14 

15class RenumberStructure(BiobbObject): 

16 """ 

17 | biobb_structure_utils RenumberStructure 

18 | Class to renumber atomic indexes from a 3D structure. 

19 | Renumber atomic indexes from a 3D structure. 

20 

21 Args: 

22 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/cl3.noH.pdb>`_. Accepted formats: pdb (edam:format_1476), gro (edam:format_2033). 

23 output_structure_path (str): Output structure file path. File type: output. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/reference/utils/renum_cl3_noH.pdb>`_. Accepted formats: pdb (edam:format_1476), gro (edam:format_2033). 

24 output_mapping_json_path (str): Output mapping json file path. File type: output. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/reference/utils/cl3_output_mapping_json_path.json>`_. Accepted formats: json (edam:format_3464). 

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

26 * **renumber_residues** (*bool*) - (True) Residue code of the ligand to be removed. 

27 * **renumber_residues_per_chain** (*bool*) - (True) Restart residue enumeration every time a new chain is detected. 

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

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

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

31 

32 Examples: 

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

34 

35 from biobb_structure_utils.utils.renumber_structure import renumber_structure 

36 prop = { 

37 'renumber_residues': True, 

38 'renumber_residues_per_chain': True 

39 } 

40 renumber_structure(input_structure_path='/path/to/myInputStr.pdb', 

41 output_structure_path='/path/to/newStructure.pdb', 

42 output_mapping_json_path='/path/to/newMapping.json', 

43 properties=prop) 

44 

45 Info: 

46 * wrapped_software: 

47 * name: In house 

48 * license: Apache-2.0 

49 * ontology: 

50 * name: EDAM 

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

52 

53 """ 

54 

55 def __init__( 

56 self, 

57 input_structure_path, 

58 output_structure_path, 

59 output_mapping_json_path, 

60 properties=None, 

61 **kwargs, 

62 ) -> None: 

63 properties = properties or {} 

64 

65 # Call parent class constructor 

66 super().__init__(properties) 

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

68 

69 # Input/Output files 

70 self.io_dict = { 

71 "in": {"input_structure_path": input_structure_path}, 

72 "out": { 

73 "output_structure_path": output_structure_path, 

74 "output_mapping_json_path": output_mapping_json_path, 

75 }, 

76 } 

77 

78 # Properties specific for BB 

79 self.renumber_residues = properties.get("renumber_residues", True) 

80 self.renumber_residues_per_chain = properties.get( 

81 "renumber_residues_per_chain", True 

82 ) 

83 

84 # Common in all BB 

85 self.can_write_console_log = properties.get("can_write_console_log", True) 

86 self.global_log = properties.get("global_log", None) 

87 self.prefix = properties.get("prefix", None) 

88 self.step = properties.get("step", None) 

89 self.path = properties.get("path", "") 

90 self.remove_tmp = properties.get("remove_tmp", True) 

91 self.restart = properties.get("restart", False) 

92 

93 # Check the properties 

94 self.check_properties(properties) 

95 self.check_arguments() 

96 

97 @launchlogger 

98 def launch(self) -> int: 

99 """Execute the :class:`RenumberStructure <utils.renumber_structure.RenumberStructure>` utils.renumber_structure.RenumberStructure object.""" 

100 

101 # Setup Biobb 

102 if self.check_restart(): 

103 return 0 

104 self.stage_files() 

105 

106 # Business code 

107 extension = Path( 

108 self.stage_io_dict["in"]["input_structure_path"] 

109 ).suffix.lower() 

110 if extension.lower() == ".gro": 

111 fu.log("GRO format detected, reenumerating atoms", self.out_log) 

112 gro_st = Gro() 

113 gro_st.read_gro_file(self.stage_io_dict["in"]["input_structure_path"]) 

114 residue_mapping, atom_mapping = gro_st.renumber_atoms( 

115 renumber_residues=self.renumber_residues, 

116 renumber_residues_per_chain=self.renumber_residues_per_chain, 

117 ) 

118 gro_st.write_gro_file(self.stage_io_dict["out"]["output_structure_path"]) 

119 

120 else: 

121 fu.log("PDB format detected, reenumerating atoms", self.out_log) 

122 atom_mapping = {} 

123 atom_count = 0 

124 residue_mapping = {} 

125 residue_count = 0 

126 with open( 

127 self.stage_io_dict["in"]["input_structure_path"], "r" 

128 ) as input_pdb, open( 

129 self.stage_io_dict["out"]["output_structure_path"], "w" 

130 ) as output_pdb: 

131 for line in input_pdb: 

132 record = line[:6].upper().strip() 

133 if ( 

134 len(line) > 10 and record in PDB_SERIAL_RECORDS 

135 ): # Avoid MODEL, ENDMDL records and empty lines 

136 # Renumbering atoms 

137 pdb_atom_number = line[6:11].strip() 

138 if not atom_mapping.get( 

139 pdb_atom_number 

140 ): # ANISOU records should have the same numeration as ATOM records 

141 atom_count += 1 

142 atom_mapping[pdb_atom_number] = str(atom_count) 

143 line = line[:6] + "{: >5d}".format(atom_count) + line[11:] 

144 # Renumbering residues 

145 if self.renumber_residues: 

146 chain = line[21] 

147 pdb_residue_number = line[22:26].strip() 

148 if not residue_mapping.get(chain): 

149 residue_mapping[chain] = {} 

150 if self.renumber_residues_per_chain: 

151 residue_count = 0 

152 if not residue_mapping[chain].get(pdb_residue_number): 

153 residue_count += 1 

154 residue_mapping[chain][pdb_residue_number] = str( 

155 residue_count 

156 ) 

157 line = ( 

158 line[:22] + "{: >4d}".format(residue_count) + line[26:] 

159 ) 

160 output_pdb.write(line) 

161 

162 with open( 

163 self.stage_io_dict["out"]["output_mapping_json_path"], "w" 

164 ) as output_json: 

165 output_json.write( 

166 json.dumps({"residues": residue_mapping, "atoms": atom_mapping}) 

167 ) 

168 

169 self.return_code = 0 

170 ########## 

171 

172 # Copy files to host 

173 self.copy_to_host() 

174 

175 # Remove temporal files 

176 self.remove_tmp_files() 

177 

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

179 

180 return self.return_code 

181 

182 

183def renumber_structure( 

184 input_structure_path: str, 

185 output_structure_path: str, 

186 output_mapping_json_path: str, 

187 properties: Optional[dict] = None, 

188 **kwargs, 

189) -> int: 

190 """Create the :class:`RenumberStructure <utils.renumber_structure.RenumberStructure>` class and 

191 execute the :meth:`launch() <utils.renumber_structure.RenumberStructure.launch>` method.""" 

192 return RenumberStructure(**dict(locals())).launch() 

193 

194 

195renumber_structure.__doc__ = RenumberStructure.__doc__ 

196main = RenumberStructure.get_main(renumber_structure, "Renumber atoms and residues from a 3D structure.") 

197 

198if __name__ == "__main__": 

199 main()