Coverage for biobb_amber / leap / leap_gen_top.py: 65%
119 statements
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-15 15:57 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-15 15:57 +0000
1#!/usr/bin/env python3
3"""Module containing the LeapGenTop class and the command line interface."""
5import os
6from pathlib import PurePath
7from typing import List, Optional
9from biobb_common.generic.biobb_object import BiobbObject
10from biobb_common.tools import file_utils as fu
11from biobb_common.tools.file_utils import launchlogger
13from biobb_amber.leap.common import _from_string_to_list
16class LeapGenTop(BiobbObject):
17 """
18 | biobb_amber.leap.leap_gen_top LeapGenTop
19 | Wrapper of the `AmberTools (AMBER MD Package) leap tool <https://ambermd.org/AmberTools.php>`_ module.
20 | Generates a MD topology from a molecule structure using tLeap tool from the AmberTools MD package.
22 Args:
23 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).
24 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).
25 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).
26 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).
27 input_prep_path (str) (Optional): Additional leap parameter files to load with loadAmberPrep Leap command. File type: input. Accepted formats: in (edam:format_2330), leapin (edam:format_2330), txt (edam:format_2330), zip (edam:format_3987).
28 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).
29 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).
30 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).
31 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).
32 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
33 * **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"].
34 * **binary_path** (*str*) - ("tleap") Path to the tleap executable binary.
35 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
36 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
37 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
38 * **container_path** (*str*) - (None) Container path definition.
39 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition.
40 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
41 * **container_working_dir** (*str*) - (None) Container working directory definition.
42 * **container_user_id** (*str*) - (None) Container user_id definition.
43 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
45 Examples:
46 This is a use example of how to use the building block from Python::
48 from biobb_amber.leap.leap_gen_top import leap_gen_top
49 prop = {
50 'forcefield': ['protein.ff14SB']
51 }
52 leap_gen_top(input_pdb_path='/path/to/structure.pdb',
53 output_pdb_path='/path/to/newStructure.pdb',
54 output_top_path='/path/to/newTopology.top',
55 output_crd_path='/path/to/newCoordinates.crd',
56 properties=prop)
58 Info:
59 * wrapped_software:
60 * name: AmberTools tLeap
61 * version: >20.9
62 * license: LGPL 2.1
63 * ontology:
64 * name: EDAM
65 * schema: http://edamontology.org/EDAM.owl
67 """
69 def __init__(
70 self,
71 input_pdb_path: str,
72 output_pdb_path: str,
73 output_top_path: str,
74 output_crd_path: str,
75 input_lib_path: Optional[str] = None,
76 input_frcmod_path: Optional[str] = None,
77 input_params_path: Optional[str] = None,
78 input_prep_path: Optional[str] = None,
79 input_source_path: Optional[str] = None,
80 properties: Optional[dict] = None,
81 **kwargs,
82 ):
83 properties = properties or {}
85 # Call parent class constructor
86 super().__init__(properties)
87 self.locals_var_dict = locals().copy()
89 # Input/Output files
90 self.io_dict = {
91 "in": {
92 "input_pdb_path": input_pdb_path,
93 "input_lib_path": input_lib_path,
94 "input_frcmod_path": input_frcmod_path,
95 "input_params_path": input_params_path,
96 "input_prep_path": input_prep_path,
97 "input_source_path": input_source_path,
98 },
99 "out": {
100 "output_pdb_path": output_pdb_path,
101 "output_top_path": output_top_path,
102 "output_crd_path": output_crd_path,
103 },
104 }
106 # # Ligand Parameter lists
107 # self.ligands_lib_list = []
108 # if input_lib_path:
109 # self.ligands_lib_list.append(input_lib_path)
110 #
111 # self.ligands_frcmod_list = []
112 # if input_frcmod_path:
113 # self.ligands_frcmod_list.append(input_frcmod_path)
115 # Set default forcefields
116 amber_home_path = os.getenv("AMBERHOME")
117 protein_ff14SB_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.protein.ff14SB')
118 dna_bsc1_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.DNA.bsc1')
119 gaff_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.gaff')
121 # Properties specific for BB
122 self.properties = properties
123 self.forcefield = _from_string_to_list(
124 properties.get("forcefield", [protein_ff14SB_path, dna_bsc1_path, gaff_path])
125 )
126 # Find the paths of the leaprc files if only the force field names are provided
127 self.forcefield = self.find_leaprc_paths(self.forcefield)
129 self.binary_path = properties.get("binary_path", "tleap")
131 # Check the properties
132 self.check_properties(properties)
133 self.check_arguments()
135 def find_leaprc_paths(self, forcefields: List[str]) -> List[str]:
136 """
137 Find the leaprc paths for the force fields provided.
139 For each item in the forcefields list, the function checks if the str is a path to an existing file.
140 If not, it tries to find the file in the $AMBERHOME/dat/leap/cmd/ directory or the $AMBERHOME/dat/leap/cmd/oldff/
141 directory with and without the leaprc prefix.
143 Args:
144 forcefields (List[str]): List of force fields to find the leaprc files for.
146 Returns:
147 List[str]: List of leaprc file paths.
148 """
150 leaprc_paths = []
152 for forcefield in forcefields:
154 num_paths = len(leaprc_paths)
156 # Check if the forcefield is a path to an existing file
157 if os.path.exists(forcefield):
158 leaprc_paths.append(forcefield)
159 continue
161 # Check if the forcefield is in the leaprc directory
162 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"leaprc.{forcefield}")
163 if os.path.exists(leaprc_path):
164 leaprc_paths.append(leaprc_path)
165 continue
167 # Check if the forcefield is in the oldff directory
168 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"leaprc.{forcefield}")
169 if os.path.exists(leaprc_path):
170 leaprc_paths.append(leaprc_path)
171 continue
173 # Check if the forcefield is in the leaprc directory without the leaprc prefix
174 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"{forcefield}")
175 if os.path.exists(leaprc_path):
176 leaprc_paths.append(leaprc_path)
177 continue
179 # Check if the forcefield is in the oldff directory without the leaprc prefix
180 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"{forcefield}")
181 if os.path.exists(leaprc_path):
182 leaprc_paths.append(leaprc_path)
183 continue
185 new_num_paths = len(leaprc_paths)
187 if new_num_paths == num_paths:
188 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.")
190 return leaprc_paths
192 # def check_data_params(self, out_log, err_log):
193 # """ Checks input/output paths correctness """
195 # # Check input(s)
196 # 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__)
197 # 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__)
198 # 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__)
199 # # 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__)
200 # # 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__)
201 # # 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__)
203 # # Check output(s)
204 # 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__)
205 # 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__)
206 # 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__)
208 @launchlogger
209 def launch(self):
210 """Launches the execution of the LeapGenTop module."""
212 # check input/output paths and parameters
213 # self.check_data_params(self.out_log, self.err_log)
215 # Setup Biobb
216 if self.check_restart():
217 return 0
218 self.stage_files()
220 # Creating temporary folder & Leap configuration (instructions) file
221 if self.container_path:
222 instructions_file = str(
223 PurePath(self.stage_io_dict["unique_dir"]).joinpath("leap.in")
224 )
225 instructions_file_path = str(
226 PurePath(self.container_volume_path).joinpath("leap.in")
227 )
228 self.tmp_folder = None
229 else:
230 self.tmp_folder = fu.create_unique_dir()
231 instructions_file = str(PurePath(self.tmp_folder).joinpath("leap.in"))
232 fu.log("Creating %s temporary folder" % self.tmp_folder, self.out_log)
233 instructions_file_path = instructions_file
235 ligands_lib_list = []
236 if self.io_dict["in"]["input_lib_path"] is not None:
237 if self.io_dict["in"]["input_lib_path"].endswith(".zip"):
238 ligands_lib_list = fu.unzip_list(
239 self.stage_io_dict["in"]["input_lib_path"],
240 dest_dir=self.tmp_folder,
241 out_log=self.out_log,
242 )
243 else:
244 ligands_lib_list.append(self.stage_io_dict["in"]["input_lib_path"])
246 ligands_frcmod_list = []
247 if self.io_dict["in"]["input_frcmod_path"] is not None:
248 if self.io_dict["in"]["input_frcmod_path"].endswith(".zip"):
249 ligands_frcmod_list = fu.unzip_list(
250 self.stage_io_dict["in"]["input_frcmod_path"],
251 dest_dir=self.tmp_folder,
252 out_log=self.out_log,
253 )
254 else:
255 ligands_frcmod_list.append(
256 self.stage_io_dict["in"]["input_frcmod_path"]
257 )
259 amber_params_list = []
260 if self.io_dict["in"]["input_params_path"] is not None:
261 if self.io_dict["in"]["input_params_path"].endswith(".zip"):
262 amber_params_list = fu.unzip_list(
263 self.stage_io_dict["in"]["input_params_path"],
264 dest_dir=self.tmp_folder,
265 out_log=self.out_log,
266 )
267 else:
268 amber_params_list.append(self.stage_io_dict["in"]["input_params_path"])
270 amber_prep_list = []
271 if self.io_dict["in"]["input_prep_path"] is not None:
272 if self.io_dict["in"]["input_prep_path"].endswith(".zip"):
273 amber_prep_list = fu.unzip_list(
274 self.stage_io_dict["in"]["input_prep_path"],
275 dest_dir=self.tmp_folder,
276 out_log=self.out_log,
277 )
278 else:
279 amber_prep_list.append(self.stage_io_dict["in"]["input_prep_path"])
281 leap_source_list = []
282 if self.io_dict["in"]["input_source_path"] is not None:
283 if self.io_dict["in"]["input_source_path"].endswith(".zip"):
284 leap_source_list = fu.unzip_list(
285 self.stage_io_dict["in"]["input_source_path"],
286 dest_dir=self.tmp_folder,
287 out_log=self.out_log,
288 )
289 else:
290 leap_source_list.append(self.stage_io_dict["in"]["input_source_path"])
292 with open(instructions_file, "w") as leapin:
293 # Forcefields loaded by default:
294 # Protein: ff14SB (PARM99 + frcmod.ff99SB + frcmod.parmbsc0 + OL3 for RNA)
295 # leapin.write("source leaprc.protein.ff14SB \n")
296 # DNA: parmBSC1 (ParmBSC1 (ff99 + bsc0 + bsc1) for DNA. Ivani et al. Nature Methods 13: 55, 2016)
297 # leapin.write("source leaprc.DNA.bsc1 \n")
298 # Ligands: GAFF (General Amber Force field, J. Comput. Chem. 2004 Jul 15;25(9):1157-74)
299 # leapin.write("source leaprc.gaff \n")
301 # Forcefields loaded from input forcefield property
302 for t in self.forcefield:
303 leapin.write("source {}\n".format(t))
305 # Additional Leap commands
306 for leap_commands in leap_source_list:
307 leapin.write("source " + leap_commands + "\n")
309 # Additional Amber parameters
310 for amber_params in amber_params_list:
311 leapin.write("loadamberparams " + amber_params + "\n")
313 # Additional Amber prep files
314 for amber_prep in amber_prep_list:
315 leapin.write("loadamberprep " + amber_prep + "\n")
317 # Ions libraries
318 leapin.write("loadOff atomic_ions.lib \n")
320 # Ligand(s) libraries (if any)
321 for amber_lib in ligands_lib_list:
322 leapin.write("loadOff " + amber_lib + "\n")
323 for amber_frcmod in ligands_frcmod_list:
324 leapin.write("loadamberparams " + amber_frcmod + "\n")
326 # Loading PDB file
327 leapin.write(
328 "mol = loadpdb " + self.stage_io_dict["in"]["input_pdb_path"] + " \n"
329 )
331 # Saving output PDB file, coordinates and topology
332 leapin.write(
333 "savepdb mol " + self.stage_io_dict["out"]["output_pdb_path"] + " \n"
334 )
335 leapin.write(
336 "saveAmberParm mol " + self.stage_io_dict["out"]["output_top_path"] + " " + self.stage_io_dict["out"]["output_crd_path"] + "\n"
337 )
338 leapin.write("quit \n")
340 # Command line
341 self.cmd = [self.binary_path, "-f", instructions_file_path]
343 # Run Biobb block
344 self.run_biobb()
346 # Copy files to host
347 self.copy_to_host()
349 # remove temporary folder(s)
350 self.tmp_files.extend([str(self.tmp_folder), "leap.log"])
351 self.remove_tmp_files()
353 self.check_arguments(output_files_created=True, raise_exception=False)
355 return self.return_code
358def leap_gen_top(
359 input_pdb_path: str,
360 output_pdb_path: str,
361 output_top_path: str,
362 output_crd_path: str,
363 input_lib_path: Optional[str] = None,
364 input_frcmod_path: Optional[str] = None,
365 input_params_path: Optional[str] = None,
366 input_prep_path: Optional[str] = None,
367 input_source_path: Optional[str] = None,
368 properties: Optional[dict] = None,
369 **kwargs,
370) -> int:
371 """Create the :class:`LeapGenTop <leap.leap_gen_top.LeapGenTop>` class and
372 execute the :meth:`launch() <leap.leap_gen_top.LeapGenTop.launch>` method."""
373 return LeapGenTop(**dict(locals())).launch()
376leap_gen_top.__doc__ = LeapGenTop.__doc__
377main = LeapGenTop.get_main(leap_gen_top, "Generating a MD topology from a molecule structure using tLeap program from AmberTools MD package.")
379if __name__ == "__main__":
380 main()