Coverage for biobb_amber/leap/leap_gen_top.py: 57%

137 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-01-28 08:28 +0000

1#!/usr/bin/env python3 

2 

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

4 

5import os 

6import argparse 

7from pathlib import PurePath 

8from typing import List, Optional 

9 

10from biobb_common.configuration import settings 

11from biobb_common.generic.biobb_object import BiobbObject 

12from biobb_common.tools import file_utils as fu 

13from biobb_common.tools.file_utils import launchlogger 

14 

15from biobb_amber.leap.common import _from_string_to_list 

16 

17 

18class LeapGenTop(BiobbObject): 

19 """ 

20 | biobb_amber.leap.leap_gen_top LeapGenTop 

21 | Wrapper of the `AmberTools (AMBER MD Package) leap tool <https://ambermd.org/AmberTools.php>`_ module. 

22 | Generates a MD topology from a molecule structure using tLeap tool from the AmberTools MD package. 

23 

24 Args: 

25 input_pdb_path (str): Input 3D structure PDB file. File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/leap/structure.leapin.pdb>`_. Accepted formats: pdb (edam:format_1476). 

26 input_lib_path (str) (Optional): Input ligand library parameters file. File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/leap/ligand.lib>`_. Accepted formats: lib (edam:format_3889), zip (edam:format_3987). 

27 input_frcmod_path (str) (Optional): Input ligand frcmod parameters file. File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/leap/ligand.frcmod>`_. Accepted formats: frcmod (edam:format_3888), zip (edam:format_3987). 

28 input_params_path (str) (Optional): Additional leap parameter files to load with loadAmberParams Leap command. File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/leap/frcmod.ionsdang_spce.txt>`_. Accepted formats: in (edam:format_2330), leapin (edam:format_2330), txt (edam:format_2330), zip (edam:format_3987). 

29 input_prep_path (str) (Optional): Additional leap parameter files to load with loadAmberPrep Leap command. File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/leap/heme_all.in>`_. Accepted formats: in (edam:format_2330), leapin (edam:format_2330), txt (edam:format_2330), zip (edam:format_3987). 

30 input_source_path (str) (Optional): Additional leap command files to load with source Leap command. File type: input. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/data/leap/leaprc.water.spce.txt>`_. Accepted formats: in (edam:format_2330), leapin (edam:format_2330), txt (edam:format_2330), zip (edam:format_3987). 

31 output_pdb_path (str): Output 3D structure PDB file matching the topology file. File type: output. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/reference/leap/structure.leap.pdb>`_. Accepted formats: pdb (edam:format_1476). 

32 output_top_path (str): Output topology file (AMBER ParmTop). File type: output. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/reference/leap/structure.leap.top>`_. Accepted formats: top (edam:format_3881), parmtop (edam:format_3881), prmtop (edam:format_3881). 

33 output_crd_path (str): Output coordinates file (AMBER crd). File type: output. `Sample file <https://github.com/bioexcel/biobb_amber/raw/master/biobb_amber/test/reference/leap/structure.leap.crd>`_. Accepted formats: crd (edam:format_3878), mdcrd (edam:format_3878), inpcrd (edam:format_3878). 

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

35 * **forcefield** (*list*) - (["protein.ff14SB","DNA.bsc1","gaff"]) Forcefields to be used for the structure generation. Each item should be either a path to a leaprc file or a string with the leaprc file name if the force field is included with Amber (e.g. "/path/to/leaprc.protein.ff14SB" or "protein.ff14SB"). Default values: ["protein.ff14SB","DNA.bsc1","gaff"]. 

36 * **binary_path** (*str*) - ("tleap") Path to the tleap executable binary. 

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

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

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

40 * **container_path** (*str*) - (None) Container path definition. 

41 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition. 

42 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition. 

43 * **container_working_dir** (*str*) - (None) Container working directory definition. 

44 * **container_user_id** (*str*) - (None) Container user_id definition. 

45 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container. 

46 

47 Examples: 

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

49 

50 from biobb_amber.leap.leap_gen_top import leap_gen_top 

51 prop = { 

52 'forcefield': ['protein.ff14SB'] 

53 } 

54 leap_gen_top(input_pdb_path='/path/to/structure.pdb', 

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

56 output_top_path='/path/to/newTopology.top', 

57 output_crd_path='/path/to/newCoordinates.crd', 

58 properties=prop) 

59 

60 Info: 

61 * wrapped_software: 

62 * name: AmberTools tLeap 

63 * version: >20.9 

64 * license: LGPL 2.1 

65 * ontology: 

66 * name: EDAM 

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

68 

69 """ 

70 

71 def __init__( 

72 self, 

73 input_pdb_path: str, 

74 output_pdb_path: str, 

75 output_top_path: str, 

76 output_crd_path: str, 

77 input_lib_path: Optional[str] = None, 

78 input_frcmod_path: Optional[str] = None, 

79 input_params_path: Optional[str] = None, 

80 input_prep_path: Optional[str] = None, 

81 input_source_path: Optional[str] = None, 

82 properties: Optional[dict] = None, 

83 **kwargs, 

84 ): 

85 properties = properties or {} 

86 

87 # Call parent class constructor 

88 super().__init__(properties) 

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

90 

91 # Input/Output files 

92 self.io_dict = { 

93 "in": { 

94 "input_pdb_path": input_pdb_path, 

95 "input_lib_path": input_lib_path, 

96 "input_frcmod_path": input_frcmod_path, 

97 "input_params_path": input_params_path, 

98 "input_prep_path": input_prep_path, 

99 "input_source_path": input_source_path, 

100 }, 

101 "out": { 

102 "output_pdb_path": output_pdb_path, 

103 "output_top_path": output_top_path, 

104 "output_crd_path": output_crd_path, 

105 }, 

106 } 

107 

108 # # Ligand Parameter lists 

109 # self.ligands_lib_list = [] 

110 # if input_lib_path: 

111 # self.ligands_lib_list.append(input_lib_path) 

112 # 

113 # self.ligands_frcmod_list = [] 

114 # if input_frcmod_path: 

115 # self.ligands_frcmod_list.append(input_frcmod_path) 

116 

117 # Set default forcefields 

118 amber_home_path = os.getenv("AMBERHOME") 

119 protein_ff14SB_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.protein.ff14SB') 

120 dna_bsc1_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.DNA.bsc1') 

121 gaff_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.gaff') 

122 

123 # Properties specific for BB 

124 self.properties = properties 

125 self.forcefield = _from_string_to_list( 

126 properties.get("forcefield", [protein_ff14SB_path, dna_bsc1_path, gaff_path]) 

127 ) 

128 # Find the paths of the leaprc files if only the force field names are provided 

129 self.forcefield = self.find_leaprc_paths(self.forcefield) 

130 

131 self.binary_path = properties.get("binary_path", "tleap") 

132 

133 # Check the properties 

134 self.check_properties(properties) 

135 self.check_arguments() 

136 

137 def find_leaprc_paths(self, forcefields: List[str]) -> List[str]: 

138 """ 

139 Find the leaprc paths for the force fields provided. 

140 

141 For each item in the forcefields list, the function checks if the str is a path to an existing file. 

142 If not, it tries to find the file in the $AMBERHOME/dat/leap/cmd/ directory or the $AMBERHOME/dat/leap/cmd/oldff/ 

143 directory with and without the leaprc prefix. 

144 

145 Args: 

146 forcefields (List[str]): List of force fields to find the leaprc files for. 

147 

148 Returns: 

149 List[str]: List of leaprc file paths. 

150 """ 

151 

152 leaprc_paths = [] 

153 

154 for forcefield in forcefields: 

155 

156 num_paths = len(leaprc_paths) 

157 

158 # Check if the forcefield is a path to an existing file 

159 if os.path.exists(forcefield): 

160 leaprc_paths.append(forcefield) 

161 continue 

162 

163 # Check if the forcefield is in the leaprc directory 

164 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"leaprc.{forcefield}") 

165 if os.path.exists(leaprc_path): 

166 leaprc_paths.append(leaprc_path) 

167 continue 

168 

169 # Check if the forcefield is in the oldff directory 

170 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"leaprc.{forcefield}") 

171 if os.path.exists(leaprc_path): 

172 leaprc_paths.append(leaprc_path) 

173 continue 

174 

175 # Check if the forcefield is in the leaprc directory without the leaprc prefix 

176 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"{forcefield}") 

177 if os.path.exists(leaprc_path): 

178 leaprc_paths.append(leaprc_path) 

179 continue 

180 

181 # Check if the forcefield is in the oldff directory without the leaprc prefix 

182 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"{forcefield}") 

183 if os.path.exists(leaprc_path): 

184 leaprc_paths.append(leaprc_path) 

185 continue 

186 

187 new_num_paths = len(leaprc_paths) 

188 

189 if new_num_paths == num_paths: 

190 raise ValueError(f"Force field {forcefield} not found. Check the $AMBERHOME/dat/leap/cmd/ directory for available force fields or provide the path to an existing leaprc file.") 

191 

192 return leaprc_paths 

193 

194 # def check_data_params(self, out_log, err_log): 

195 # """ Checks input/output paths correctness """ 

196 

197 # # Check input(s) 

198 # self.io_dict["in"]["input_pdb_path"] = check_input_path(self.io_dict["in"]["input_pdb_path"], "input_pdb_path", False, out_log, self.__class__.__name__) 

199 # self.io_dict["in"]["input_lib_path"] = check_input_path(self.io_dict["in"]["input_lib_path"], "input_lib_path", True, out_log, self.__class__.__name__) 

200 # self.io_dict["in"]["input_frcmod_path"] = check_input_path(self.io_dict["in"]["input_frcmod_path"], "input_frcmod_path", True, out_log, self.__class__.__name__) 

201 # # self.io_dict["in"]["input_params_path"] = check_input_path(self.io_dict["in"]["input_params_path"], "input_params_path", True, out_log, self.__class__.__name__) 

202 # # self.io_dict["in"]["input_prep_path"] = check_input_path(self.io_dict["in"]["input_params_path"], "input_params_path", True, out_log, self.__class__.__name__) 

203 # # self.io_dict["in"]["input_source_path"] = check_input_path(self.io_dict["in"]["input_source_path"], "input_source_path", True, out_log, self.__class__.__name__) 

204 

205 # # Check output(s) 

206 # self.io_dict["out"]["output_pdb_path"] = check_output_path(self.io_dict["out"]["output_pdb_path"], "output_pdb_path", False, out_log, self.__class__.__name__) 

207 # self.io_dict["out"]["output_top_path"] = check_output_path(self.io_dict["out"]["output_top_path"], "output_top_path", False, out_log, self.__class__.__name__) 

208 # self.io_dict["out"]["output_crd_path"] = check_output_path(self.io_dict["out"]["output_crd_path"], "output_crd_path", False, out_log, self.__class__.__name__) 

209 

210 @launchlogger 

211 def launch(self): 

212 """Launches the execution of the LeapGenTop module.""" 

213 

214 # check input/output paths and parameters 

215 # self.check_data_params(self.out_log, self.err_log) 

216 

217 # Setup Biobb 

218 if self.check_restart(): 

219 return 0 

220 self.stage_files() 

221 

222 # Creating temporary folder & Leap configuration (instructions) file 

223 if self.container_path: 

224 instructions_file = str( 

225 PurePath(self.stage_io_dict["unique_dir"]).joinpath("leap.in") 

226 ) 

227 instructions_file_path = str( 

228 PurePath(self.container_volume_path).joinpath("leap.in") 

229 ) 

230 self.tmp_folder = None 

231 else: 

232 self.tmp_folder = fu.create_unique_dir() 

233 instructions_file = str(PurePath(self.tmp_folder).joinpath("leap.in")) 

234 fu.log("Creating %s temporary folder" % self.tmp_folder, self.out_log) 

235 instructions_file_path = instructions_file 

236 

237 ligands_lib_list = [] 

238 if self.io_dict["in"]["input_lib_path"] is not None: 

239 if self.io_dict["in"]["input_lib_path"].endswith(".zip"): 

240 ligands_lib_list = fu.unzip_list( 

241 self.stage_io_dict["in"]["input_lib_path"], 

242 dest_dir=self.tmp_folder, 

243 out_log=self.out_log, 

244 ) 

245 else: 

246 ligands_lib_list.append(self.stage_io_dict["in"]["input_lib_path"]) 

247 

248 ligands_frcmod_list = [] 

249 if self.io_dict["in"]["input_frcmod_path"] is not None: 

250 if self.io_dict["in"]["input_frcmod_path"].endswith(".zip"): 

251 ligands_frcmod_list = fu.unzip_list( 

252 self.stage_io_dict["in"]["input_frcmod_path"], 

253 dest_dir=self.tmp_folder, 

254 out_log=self.out_log, 

255 ) 

256 else: 

257 ligands_frcmod_list.append( 

258 self.stage_io_dict["in"]["input_frcmod_path"] 

259 ) 

260 

261 amber_params_list = [] 

262 if self.io_dict["in"]["input_params_path"] is not None: 

263 if self.io_dict["in"]["input_params_path"].endswith(".zip"): 

264 amber_params_list = fu.unzip_list( 

265 self.stage_io_dict["in"]["input_params_path"], 

266 dest_dir=self.tmp_folder, 

267 out_log=self.out_log, 

268 ) 

269 else: 

270 amber_params_list.append(self.stage_io_dict["in"]["input_params_path"]) 

271 

272 amber_prep_list = [] 

273 if self.io_dict["in"]["input_prep_path"] is not None: 

274 if self.io_dict["in"]["input_prep_path"].endswith(".zip"): 

275 amber_prep_list = fu.unzip_list( 

276 self.stage_io_dict["in"]["input_prep_path"], 

277 dest_dir=self.tmp_folder, 

278 out_log=self.out_log, 

279 ) 

280 else: 

281 amber_prep_list.append(self.stage_io_dict["in"]["input_prep_path"]) 

282 

283 leap_source_list = [] 

284 if self.io_dict["in"]["input_source_path"] is not None: 

285 if self.io_dict["in"]["input_source_path"].endswith(".zip"): 

286 leap_source_list = fu.unzip_list( 

287 self.stage_io_dict["in"]["input_source_path"], 

288 dest_dir=self.tmp_folder, 

289 out_log=self.out_log, 

290 ) 

291 else: 

292 leap_source_list.append(self.stage_io_dict["in"]["input_source_path"]) 

293 

294 with open(instructions_file, "w") as leapin: 

295 # Forcefields loaded by default: 

296 # Protein: ff14SB (PARM99 + frcmod.ff99SB + frcmod.parmbsc0 + OL3 for RNA) 

297 # leapin.write("source leaprc.protein.ff14SB \n") 

298 # DNA: parmBSC1 (ParmBSC1 (ff99 + bsc0 + bsc1) for DNA. Ivani et al. Nature Methods 13: 55, 2016) 

299 # leapin.write("source leaprc.DNA.bsc1 \n") 

300 # Ligands: GAFF (General Amber Force field, J. Comput. Chem. 2004 Jul 15;25(9):1157-74) 

301 # leapin.write("source leaprc.gaff \n") 

302 

303 # Forcefields loaded from input forcefield property 

304 for t in self.forcefield: 

305 leapin.write("source {}\n".format(t)) 

306 

307 # Additional Leap commands 

308 for leap_commands in leap_source_list: 

309 leapin.write("source " + leap_commands + "\n") 

310 

311 # Additional Amber parameters 

312 for amber_params in amber_params_list: 

313 leapin.write("loadamberparams " + amber_params + "\n") 

314 

315 # Additional Amber prep files 

316 for amber_prep in amber_prep_list: 

317 leapin.write("loadamberprep " + amber_prep + "\n") 

318 

319 # Ions libraries 

320 leapin.write("loadOff atomic_ions.lib \n") 

321 

322 # Ligand(s) libraries (if any) 

323 for amber_lib in ligands_lib_list: 

324 leapin.write("loadOff " + amber_lib + "\n") 

325 for amber_frcmod in ligands_frcmod_list: 

326 leapin.write("loadamberparams " + amber_frcmod + "\n") 

327 

328 # Loading PDB file 

329 leapin.write( 

330 "mol = loadpdb " + self.stage_io_dict["in"]["input_pdb_path"] + " \n" 

331 ) 

332 

333 # Saving output PDB file, coordinates and topology 

334 leapin.write( 

335 "savepdb mol " + self.stage_io_dict["out"]["output_pdb_path"] + " \n" 

336 ) 

337 leapin.write( 

338 "saveAmberParm mol " + self.stage_io_dict["out"]["output_top_path"] + " " + self.stage_io_dict["out"]["output_crd_path"] + "\n" 

339 ) 

340 leapin.write("quit \n") 

341 

342 # Command line 

343 self.cmd = [self.binary_path, "-f", instructions_file_path] 

344 

345 # Run Biobb block 

346 self.run_biobb() 

347 

348 # Copy files to host 

349 self.copy_to_host() 

350 

351 # remove temporary folder(s) 

352 self.tmp_files.extend([ 

353 # self.stage_io_dict.get("unique_dir", ""), 

354 str(self.tmp_folder), "leap.log" 

355 ]) 

356 self.remove_tmp_files() 

357 

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

359 

360 return self.return_code 

361 

362 

363def leap_gen_top( 

364 input_pdb_path: str, 

365 output_pdb_path: str, 

366 output_top_path: str, 

367 output_crd_path: str, 

368 input_lib_path: Optional[str] = None, 

369 input_frcmod_path: Optional[str] = None, 

370 input_params_path: Optional[str] = None, 

371 input_prep_path: Optional[str] = None, 

372 input_source_path: Optional[str] = None, 

373 properties: Optional[dict] = None, 

374 **kwargs, 

375) -> int: 

376 """Create :class:`LeapGenTop <leap.leap_gen_top.LeapGenTop>`leap.leap_gen_top.LeapGenTop class and 

377 execute :meth:`launch() <leap.leap_gen_top.LeapGenTop.launch>` method""" 

378 

379 return LeapGenTop( 

380 input_pdb_path=input_pdb_path, 

381 input_lib_path=input_lib_path, 

382 input_frcmod_path=input_frcmod_path, 

383 input_params_path=input_params_path, 

384 input_prep_path=input_prep_path, 

385 input_source_path=input_source_path, 

386 output_pdb_path=output_pdb_path, 

387 output_top_path=output_top_path, 

388 output_crd_path=output_crd_path, 

389 properties=properties, 

390 ).launch() 

391 

392 leap_gen_top.__doc__ = LeapGenTop.__doc__ 

393 

394 

395def main(): 

396 parser = argparse.ArgumentParser( 

397 description="Generating a MD topology from a molecule structure using tLeap program from AmberTools MD package.", 

398 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999), 

399 ) 

400 parser.add_argument("--config", required=False, help="Configuration file") 

401 

402 # Specific args 

403 required_args = parser.add_argument_group("required arguments") 

404 required_args.add_argument( 

405 "--input_pdb_path", 

406 required=True, 

407 help="Input 3D structure PDB file. Accepted formats: pdb.", 

408 ) 

409 required_args.add_argument( 

410 "--input_lib_path", 

411 required=False, 

412 help="Input ligand library parameters file. Accepted formats: lib, zip.", 

413 ) 

414 required_args.add_argument( 

415 "--input_frcmod_path", 

416 required=False, 

417 help="Input ligand frcmod parameters file. Accepted formats: frcmod, zip.", 

418 ) 

419 required_args.add_argument( 

420 "--input_params_path", 

421 required=False, 

422 help="Additional leap parameter files to load with loadAmberParams Leap command. Accepted formats: leapin, in, txt, zip.", 

423 ) 

424 required_args.add_argument( 

425 "--input_prep_path", 

426 required=False, 

427 help="Additional leap parameter files to load with loadAmberPrep Leap command. Accepted formats: leapin, in, txt, zip.", 

428 ) 

429 required_args.add_argument( 

430 "--input_source_path", 

431 required=False, 

432 help="Additional leap command files to load with source Leap command. Accepted formats: leapin, in, txt, zip.", 

433 ) 

434 required_args.add_argument( 

435 "--output_pdb_path", 

436 required=True, 

437 help="Output 3D structure PDB file matching the topology file. Accepted formats: pdb.", 

438 ) 

439 required_args.add_argument( 

440 "--output_top_path", 

441 required=True, 

442 help="Output topology file (AMBER ParmTop). Accepted formats: top.", 

443 ) 

444 required_args.add_argument( 

445 "--output_crd_path", 

446 required=True, 

447 help="Output coordinates file (AMBER crd). Accepted formats: crd.", 

448 ) 

449 

450 args = parser.parse_args() 

451 config = args.config if args.config else None 

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

453 

454 # Specific call 

455 leap_gen_top( 

456 input_pdb_path=args.input_pdb_path, 

457 input_lib_path=args.input_lib_path, 

458 input_frcmod_path=args.input_frcmod_path, 

459 input_params_path=args.input_params_path, 

460 input_prep_path=args.input_prep_path, 

461 input_source_path=args.input_source_path, 

462 output_pdb_path=args.output_pdb_path, 

463 output_top_path=args.output_top_path, 

464 output_crd_path=args.output_crd_path, 

465 properties=properties, 

466 ) 

467 

468 

469if __name__ == "__main__": 

470 main()