Coverage for biobb_vs/utils/bindingsite.py: 88%

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

4import re 

5import warnings 

6from pathlib import PurePath 

7from typing import Optional 

8from Bio import BiopythonDeprecationWarning 

9from biobb_common.generic.biobb_object import BiobbObject, launcher 

10from biobb_common.tools import file_utils as fu 

11 

12from biobb_vs.utils.common import ( 

13 align_sequences, 

14 calculate_alignment_identity, 

15 get_ligand_residues, 

16 get_pdb_sequence, 

17 get_residue_by_id, 

18) 

19 

20with warnings.catch_warnings(): 

21 warnings.simplefilter("ignore", BiopythonDeprecationWarning) 

22 # try: 

23 # import Bio.SubsMat.MatrixInfo 

24 # except ImportError: 

25 import Bio.Align.substitution_matrices 

26 import Bio.pairwise2 

27 import Bio.PDB 

28 

29 

30class BindingSite(BiobbObject): 

31 """ 

32 | biobb_vs BindingSite 

33 | This class finds the binding site of the input_pdb. 

34 | Finds the binding site of the input_pdb_path file based on the ligands' location of similar structures (members of the sequence identity cluster) 

35 

36 Args: 

37 input_pdb_path (str): Path to the PDB structure where the binding site is to be found. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/utils/bindingsite.pdb>`_. Accepted formats: pdb (edam:format_1476), pqr (edam:format_1476). 

38 input_clusters_zip (str): Path to the ZIP file with all the PDB members of the identity cluster. File type: input. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/data/utils/bindingsite.zip>`_. Accepted formats: zip (edam:format_3987). 

39 output_pdb_path (str): Path to the PDB containig the residues belonging to the binding site. File type: output. `Sample file <https://github.com/bioexcel/biobb_vs/raw/master/biobb_vs/test/reference/utils/ref_output_bindingsite.pdb>`_. Accepted formats: pdb (edam:format_1476). 

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

41 * **ligand** (*str*) - (None) Ligand to be found in the protein structure. If no ligand provided, the largest one will be selected, if more than one. 

42 * **radius** (*float*) - (5.0) [0.1~1000|0.1] Cut-off distance (Ångstroms) around ligand atoms to consider a protein atom as a binding site atom. 

43 * **max_num_ligands** (*int*) - (15) [0~1000|1] Total number of superimposed ligands to be extracted from the identity cluster. For populated clusters, the restriction avoids to superimpose redundant structures. If 0, all ligands extracted will be considered. 

44 * **matrix_name** (*str*) - ("BLOSUM62") Substitution matrices for use in alignments. Values: BENNER22, BENNER6, BENNER74, BLASTN, BLASTP, BLOSUM45, BLOSUM50, BLOSUM62, BLOSUM80, BLOSUM90, DAYHOFF, FENG, GENETIC, GONNET1992, HOXD70, JOHNSON, JONES, LEVIN, MCLACHLAN, MDM78, MEGABLAST, NUC.4.4, PAM250, PAM30, PAM70, RAO, RISLER, SCHNEIDER, STR, TRANS. 

45 * **gap_open** (*float*) - (-10.0) [-1000~1000|0.1] Gap open penalty. 

46 * **gap_extend** (*float*) - (-0.5) [-1000~1000|0.1] Gap extend penalty. 

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 

51 Examples: 

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

53 

54 from biobb_vs.utils.bindingsite import bindingsite 

55 prop = { 

56 'ligand': 'PGA', 

57 'matrix_name': 'BLOSUM62', 

58 'gap_open': -10.0, 

59 'gap_extend': -0.5, 

60 'max_num_ligands': 15, 

61 'radius': 5 

62 } 

63 bindingsite(input_pdb_path='/path/to/myStructure.pdb', 

64 input_clusters_zip='/path/to/myCluster.zip', 

65 output_pdb_path='/path/to/newStructure.pdb', 

66 properties=prop) 

67 

68 Info: 

69 * wrapped_software: 

70 * name: In house using Biopython 

71 * version: >=1.76 

72 * license: Apache-2.0 

73 * ontology: 

74 * name: EDAM 

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

76 

77 """ 

78 

79 def __init__( 

80 self, 

81 input_pdb_path: str, 

82 input_clusters_zip: str, 

83 output_pdb_path: str, 

84 properties: Optional[dict] = None, 

85 **kwargs, 

86 ) -> None: 

87 super().__init__(**locals()) 

88 

89 # Properties specific for BB 

90 self.radius = float(self.radius) 

91 

92 def stage_files(self) -> None: 

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

94 

95 def run(self) -> None: 

96 """Execute the :class:`BindingSite <utils.bindingsite.BindingSite>` utils.bindingsite.BindingSite object.""" 

97 

98 # Parse structure 

99 fu.log( 

100 "Loading input PDB structure %s" % (self.io_dict["in"]["input_pdb_path"]), 

101 self.out_log, 

102 self.global_log, 

103 ) 

104 structure_name = PurePath(self.io_dict["in"]["input_pdb_path"]).name 

105 parser = Bio.PDB.PDBParser(QUIET=True) 

106 structPDB = parser.get_structure( 

107 structure_name, self.io_dict["in"]["input_pdb_path"] 

108 ) 

109 

110 if len(structPDB): 

111 structPDB = structPDB[0] 

112 

113 # Use only one chain 

114 n_chains = structPDB.get_list() 

115 if len(n_chains) != 1: 

116 fu.log( 

117 "More than one chain found in the input PDB structure. Using only the first chain to find the binding site", 

118 self.out_log, 

119 self.global_log, 

120 ) 

121 # keep only the first chain in case there is more than one chain 

122 for chain in n_chains[1:]: 

123 structPDB.detach_child(chain.id) 

124 

125 # Get AA sequence 

126 structPDB_seq = get_pdb_sequence(structPDB) 

127 if len(structPDB_seq) == 0: 

128 fu.log( 

129 self.__class__.__name__ + ": Cannot extract AA sequence from the input PDB structure %s. Wrong format?" 

130 % self.io_dict["in"]["input_pdb_path"], 

131 self.out_log, 

132 ) 

133 raise SystemExit( 

134 self.__class__.__name__ + ": Cannot extract AA sequence from the input PDB structure %s. Wrong format?" 

135 % self.io_dict["in"]["input_pdb_path"] 

136 ) 

137 else: 

138 fu.log( 

139 "Found %s residues in %s" 

140 % (len(structPDB_seq), self.io_dict["in"]["input_pdb_path"]), 

141 self.out_log, 

142 ) 

143 

144 # create temporary folder for decompressing the input_clusters_zip file 

145 unique_dir = PurePath(self.create_tmp_dir(log=True)) 

146 

147 # decompress the input_clusters_zip file 

148 cluster_list = fu.unzip_list( 

149 zip_file=self.io_dict["in"]["input_clusters_zip"], 

150 dest_dir=str(unique_dir), 

151 out_log=self.out_log, 

152 ) 

153 

154 clusterPDB_ligands_aligned = [] 

155 clusterPDB_ligands_num = 0 

156 

157 fu.log("Iterating on all clusters:", self.out_log) 

158 

159 for idx, cluster_path in enumerate(cluster_list): 

160 cluster_name = PurePath(cluster_path).stem 

161 fu.log(" ", self.out_log) 

162 fu.log( 

163 "------------ Iteration #%s --------------" % (idx + 1), self.out_log 

164 ) 

165 fu.log("Cluster member: %s" % cluster_name, self.out_log) 

166 

167 # Load and Parse PDB 

168 clusterPDB = {} 

169 clusterPDB = parser.get_structure(cluster_name, cluster_path)[0] 

170 

171 # Use only the first chain 

172 clusterPDB = next(clusterPDB.get_chains()) # type: ignore 

173 

174 # Looking for ligands 

175 clusterPDB_ligands = get_ligand_residues(clusterPDB) 

176 if (len(clusterPDB_ligands)) == 0: 

177 fu.log( 

178 "No ligands found that could guide the binding site search. Ignoring this member: %s" 

179 % cluster_name, 

180 self.out_log, 

181 ) 

182 continue 

183 

184 # Selecting the largest ligand, if more than one 

185 lig_atoms_num = 0 

186 clusterPDB_ligand = {} 

187 if self.ligand: 

188 if self.ligand in [x.get_resname() for x in clusterPDB_ligands]: 

189 for lig in clusterPDB_ligands: 

190 if lig.get_resname() == self.ligand: 

191 clusterPDB_ligand = lig 

192 lig_atoms_num = len(lig.get_list()) 

193 fu.log( 

194 "Ligand found: %s (%s atoms)" 

195 % (lig.get_resname(), lig_atoms_num), 

196 self.out_log, 

197 ) 

198 else: 

199 fu.log( 

200 "Ligand %s not found in %s cluster member, skipping this cluster" 

201 % (self.ligand, cluster_name), 

202 self.out_log, 

203 ) 

204 continue 

205 else: 

206 if len(clusterPDB_ligands) > 1: 

207 for lig_res in clusterPDB_ligands: 

208 lig_res_atoms_num = len(lig_res.get_list()) 

209 fu.log( 

210 "Ligand found: %s (%s atoms)" 

211 % (lig_res.get_resname(), lig_res_atoms_num), 

212 self.out_log, 

213 ) 

214 if lig_res_atoms_num > lig_atoms_num: 

215 clusterPDB_ligand = lig_res 

216 lig_atoms_num = lig_res_atoms_num 

217 else: 

218 clusterPDB_ligand = clusterPDB_ligands[0] 

219 lig_atoms_num = len(clusterPDB_ligands[0].get_list()) 

220 

221 fu.log( 

222 "Member accepted. Valid ligand found: %s (%s atoms)" 

223 % (clusterPDB_ligand.get_resname(), lig_atoms_num), # type: ignore 

224 self.out_log, 

225 ) 

226 

227 # Mapping residues by sequence alignment to match structPDB-clusterPDB paired residues 

228 

229 # Get AA sequence 

230 clusterPDB_seq = get_pdb_sequence(clusterPDB) 

231 

232 # Pairwise align 

233 aln, residue_map = align_sequences( 

234 structPDB_seq, 

235 clusterPDB_seq, 

236 self.matrix_name, 

237 self.gap_open, 

238 self.gap_extend, 

239 ) 

240 fu.log( 

241 "Matching residues to input PDB structure. Alignment is:\n%s" 

242 % (aln[1]), 

243 self.out_log, 

244 ) 

245 

246 # Calculate (gapless) sequence identity 

247 seq_identity, gap_seq_identity = calculate_alignment_identity( 

248 aln[0], aln[1] 

249 ) 

250 fu.log("Sequence identity (%%): %s" % (seq_identity), self.out_log) 

251 fu.log("Gap less identity (%%): %s" % (gap_seq_identity), self.out_log) 

252 

253 # Selecting aligned CA atoms from first model, first chain 

254 

255 struct_atoms = [] 

256 cluster_atoms = [] 

257 

258 for struct_res in residue_map: 

259 # look both up before adding either, so that the two lists stay paired 

260 try: 

261 cluster_atom = clusterPDB[residue_map[struct_res]]["CA"] 

262 struct_atom = get_residue_by_id(structPDB, struct_res)["CA"] 

263 except KeyError: 

264 fu.log( 

265 "Cannot find CA atom for residue %s (input PDB %s)" 

266 % ( 

267 get_residue_by_id(structPDB, struct_res).get_resname(), 

268 struct_res, 

269 ), 

270 self.out_log, 

271 ) 

272 else: 

273 cluster_atoms.append(cluster_atom) 

274 struct_atoms.append(struct_atom) 

275 

276 if len(cluster_atoms) == 0: 

277 fu.log( 

278 self.__class__.__name__ + ": Cannot find CA atoms (1st model, 1st chain) in cluster member %s when aligning against %s. Ignoring this member." 

279 % (cluster_name, structure_name), 

280 self.out_log, 

281 ) 

282 continue 

283 else: 

284 fu.log( 

285 "Superimposing %s aligned protein residues" % (len(cluster_atoms)), 

286 self.out_log, 

287 ) 

288 

289 # Align against input structure 

290 

291 si = Bio.PDB.Superimposer() 

292 si.set_atoms(struct_atoms, cluster_atoms) 

293 si.apply(clusterPDB.get_atoms()) # type: ignore 

294 fu.log("RMSD: %s" % (si.rms), self.out_log) 

295 

296 # Save transformed structure (and ligand) 

297 clusterPDB_ligand_aligned = clusterPDB[clusterPDB_ligand.get_id()] # type: ignore 

298 fu.log("Saving transformed ligand coordinates", self.out_log) 

299 

300 clusterPDB_ligands_aligned.append(clusterPDB_ligand_aligned) 

301 

302 # Stop after n accepted cluster members 

303 

304 clusterPDB_ligands_num += 1 

305 

306 if self.max_num_ligands and clusterPDB_ligands_num >= self.max_num_ligands: 

307 break 

308 

309 if clusterPDB_ligands_num == 0: 

310 msg = (self.__class__.__name__ + ": No cluster member in %s gave a ligand to superimpose: cannot define the binding site." 

311 % self.io_dict["in"]["input_clusters_zip"]) 

312 fu.log(msg, self.out_log) 

313 raise SystemExit(msg) 

314 

315 fu.log(" ", self.out_log) 

316 fu.log("----------------------------------------", self.out_log) 

317 fu.log( 

318 "All transformed ligand coordinates saved, getting binding site residues", 

319 self.out_log, 

320 ) 

321 

322 # Select binding site atoms as those around cluster superimposed ligands 

323 

324 fu.log( 

325 "Defining binding site residues as those %sÅ around the %s cluster superimposed ligands" 

326 % (self.radius, clusterPDB_ligands_num), 

327 self.out_log, 

328 ) 

329 

330 # select Atoms from aligned ligands 

331 clusterPDB_ligands_aligned2 = [res for res in clusterPDB_ligands_aligned] 

332 clusterPDB_ligands_aligned_atoms = Bio.PDB.Selection.unfold_entities( 

333 clusterPDB_ligands_aligned2, "A" 

334 ) 

335 

336 # select Atoms from input PDB structure 

337 structPDB_atoms = [atom for atom in structPDB.get_atoms()] 

338 

339 # compute neighbors for aligned ligands in the input PDB structure 

340 structPDB_bs_residues_raw = {} 

341 structPDB_neighbors = Bio.PDB.NeighborSearch(structPDB_atoms) 

342 for ligand_atom in clusterPDB_ligands_aligned_atoms: 

343 # look for PDB atoms 5A around each ligand atom 

344 k_l = structPDB_neighbors.search(ligand_atom.coord, self.radius, "R") 

345 for k in k_l: 

346 structPDB_bs_residues_raw[k.get_id()] = k.get_full_id() 

347 

348 # Save binding site to PDB 

349 

350 io = Bio.PDB.PDBIO() 

351 fu.log( 

352 "Writing binding site residues into %s" 

353 % (self.io_dict["out"]["output_pdb_path"]), 

354 self.out_log, 

355 ) 

356 

357 # unselect input PDB atoms not in binding site 

358 structPDB_bs_atoms = 0 

359 p = re.compile("H_|W_|W") 

360 residue_ids_to_remove = [] 

361 for res in structPDB.get_residues(): 

362 if res.id not in structPDB_bs_residues_raw.keys(): 

363 # add residue to residue_ids_to_remove list 

364 residue_ids_to_remove.append(res.id) 

365 elif p.match(res.resname): 

366 # add residue to residue_ids_to_remove list 

367 residue_ids_to_remove.append(res.id) 

368 else: 

369 # this residue will be preserved 

370 structPDB_bs_atoms += len(res.get_list()) 

371 

372 # unselect input PDB atoms not in binding site 

373 for chain in structPDB: 

374 for idr in residue_ids_to_remove: 

375 chain.detach_child(idr) 

376 

377 # write PDB file 

378 io.set_structure(structPDB) 

379 io.save(self.io_dict["out"]["output_pdb_path"]) 

380 

381 

382bindingsite = launcher(BindingSite) 

383 

384 

385if __name__ == "__main__": 

386 BindingSite.main()