Coverage for biobb_amber / leap / leap_solvate.py: 68%
168 statements
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-12 10:52 +0000
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-12 10:52 +0000
1#!/usr/bin/env python3
3"""Module containing the LeapSolvate class and the command line interface."""
5import os
6import re
7from pathlib import PurePath
8from typing import List, Optional
10from biobb_common.generic.biobb_object import BiobbObject
11from biobb_common.tools import file_utils as fu
12from biobb_common.tools.file_utils import launchlogger
14from biobb_amber.leap.common import _from_string_to_list
17class LeapSolvate(BiobbObject):
18 """
19 | biobb_amber LeapSolvate
20 | Wrapper of the `AmberTools (AMBER MD Package) leap tool <https://ambermd.org/AmberTools.php>`_ module.
21 | Creates and solvates a system box for an AMBER MD system using tLeap tool from the AmberTools MD package.
23 Args:
24 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.leap.pdb>`_. Accepted formats: pdb (edam:format_1476).
25 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).
26 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).
27 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).
28 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).
29 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).
30 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.solv.pdb>`_. Accepted formats: pdb (edam:format_1476).
31 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.solv.top>`_. Accepted formats: top (edam:format_3881), parmtop (edam:format_3881), prmtop (edam:format_3881).
32 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.solv.crd>`_. Accepted formats: crd (edam:format_3878), mdcrd (edam:format_3878), inpcrd (edam:format_3878).
33 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
34 * **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"].
35 * **water_type** (*str*) - ("TIP3PBOX") Water molecule parameters to be used for the topology. Values: POL3BOX, QSPCFWBOX, SPCBOX, SPCFWBOX, TIP3PBOX, TIP3PFBOX, TIP4PBOX, TIP4PEWBOX, OPCBOX, OPC3BOX, TIP5PBOX.
36 * **box_type** (*str*) - ("truncated_octahedron") Type for the MD system box. Values: cubic, truncated_octahedron.
37 * **ions_type** (*str*) - ("ionsjc_tip3p") Ions type. Values: ionsjc_tip3p, ionsjc_spce, ionsff99_tip3p, ions_charmm22, ionsjc_tip4pew, None.
38 * **neutralise** (*bool*) - ("False") Energetically neutralise the system adding the necessary counterions.
39 * **iso** (*bool*) - ("False") Make the box isometric.
40 * **positive_ions_number** (*int*) - (0) Number of additional positive ions to include in the system box.
41 * **negative_ions_number** (*int*) - (0) Number of additional negative ions to include in the system box.
42 * **positive_ions_type** (*str*) - ("Na+") Type of additional positive ions to include in the system box. Values: Na+,K+.
43 * **negative_ions_type** (*str*) - ("Cl-") Type of additional negative ions to include in the system box. Values: Cl-.
44 * **distance_to_molecule** (*float*) - ("8.0") Size for the MD system box -in Angstroms-, defined such as the minimum distance between any atom originally present in solute and the edge of the periodic box is given by this distance parameter.
45 * **closeness** (*float*) - ("1.0") How close, in Å, solvent ATOMs may come to solute ATOMs.
46 * **binary_path** (*str*) - ("tleap") Path to the tleap executable binary.
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 * **container_path** (*str*) - (None) Container path definition.
51 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition.
52 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
53 * **container_working_dir** (*str*) - (None) Container working directory definition.
54 * **container_user_id** (*str*) - (None) Container user_id definition.
55 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
57 Examples:
58 This is a use example of how to use the building block from Python::
59 from biobb_amber.leap.leap_solvate import leap_solvate
60 prop = {
61 'forcefield': ['protein.ff14SB'],
62 'water_type': 'TIP3PBOX',
63 'box_type': 'truncated_octahedron',
64 'neutralise' : True
65 }
66 leap_solvate(input_pdb_path='/path/to/structure.pdb',
67 output_pdb_path='/path/to/newStructure.pdb',
68 output_top_path='/path/to/newTopology.top',
69 output_crd_path='/path/to/newCoordinates.crd',
70 properties=prop)
72 Info:
73 * wrapped_software:
74 * name: AmberTools tLeap
75 * version: >20.9
76 * license: LGPL 2.1
77 * ontology:
78 * name: EDAM
79 * schema: http://edamontology.org/EDAM.owl
81 """
83 def __init__(
84 self,
85 input_pdb_path: str,
86 output_pdb_path: str,
87 output_top_path: str,
88 output_crd_path: str,
89 input_lib_path: Optional[str] = None,
90 input_frcmod_path: Optional[str] = None,
91 input_params_path: Optional[str] = None,
92 input_prep_path: Optional[str] = None,
93 input_source_path: Optional[str] = None,
94 properties: Optional[dict] = None,
95 **kwargs,
96 ):
97 properties = properties or {}
99 # Call parent class constructor
100 super().__init__(properties)
101 self.locals_var_dict = locals().copy()
103 # Input/Output files
104 self.io_dict = {
105 "in": {
106 "input_pdb_path": input_pdb_path,
107 "input_lib_path": input_lib_path,
108 "input_frcmod_path": input_frcmod_path,
109 "input_params_path": input_params_path,
110 "input_prep_path": input_prep_path,
111 "input_source_path": input_source_path,
112 },
113 "out": {
114 "output_pdb_path": output_pdb_path,
115 "output_top_path": output_top_path,
116 "output_crd_path": output_crd_path,
117 },
118 }
120 # # Ligand Parameter lists
121 # self.ligands_lib_list = []
122 # if input_lib_path:
123 # self.ligands_lib_list.append(input_lib_path)
124 #
125 # self.ligands_frcmod_list = []
126 # if input_frcmod_path:
127 # self.ligands_frcmod_list.append(input_frcmod_path)
129 # Properties specific for BB
130 self.properties = properties
132 # Set default forcefields
133 if self.container_path:
134 self.forcefield = _from_string_to_list(
135 properties.get("forcefield", ['leaprc.protein.ff14SB', 'leaprc.DNA.bsc1', 'leaprc.gaff'])
136 )
137 else:
138 amber_home_path = os.getenv("AMBERHOME")
139 protein_ff14SB_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.protein.ff14SB')
140 dna_bsc1_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.DNA.bsc1')
141 gaff_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.gaff')
143 self.forcefield = _from_string_to_list(
144 properties.get("forcefield", [protein_ff14SB_path, dna_bsc1_path, gaff_path])
145 )
147 # Find the paths of the leaprc files if only the force field names are provided
148 self.forcefield = self.find_leaprc_paths(self.forcefield)
150 self.water_type = properties.get("water_type", "TIP3PBOX")
151 self.box_type = properties.get("box_type", "truncated_octahedron")
152 self.ions_type = properties.get("ions_type", "ionsjc_tip3p")
153 self.neutralise = properties.get("neutralise", False)
154 self.iso = properties.get("iso", False)
155 self.positive_ions_number = properties.get("positive_ions_number", 0)
156 self.positive_ions_type = properties.get("positive_ions_type", "Na+")
157 self.negative_ions_number = properties.get("negative_ions_number", 0)
158 self.negative_ions_type = properties.get("negative_ions_type", "Cl-")
159 self.distance_to_molecule = properties.get("distance_to_molecule", 8.0)
160 self.closeness = properties.get("closeness", 1.0)
161 self.binary_path = properties.get("binary_path", "tleap")
163 # Check the properties
164 self.check_properties(properties)
165 self.check_arguments()
167 def find_leaprc_paths(self, forcefields: List[str]) -> List[str]:
168 """
169 Find the leaprc paths for the force fields provided.
171 For each item in the forcefields list, the function checks if the str is a path to an existing file.
172 If not, it tries to find the file in the $AMBERHOME/dat/leap/cmd/ directory or the $AMBERHOME/dat/leap/cmd/oldff/
173 directory with and without the leaprc prefix.
175 Args:
176 forcefields (List[str]): List of force fields to find the leaprc files for.
178 Returns:
179 List[str]: List of leaprc file paths.
180 """
182 leaprc_paths = []
184 for forcefield in forcefields:
186 num_paths = len(leaprc_paths)
188 # Check if the forcefield is a path to an existing file
189 if os.path.exists(forcefield):
190 leaprc_paths.append(forcefield)
191 continue
193 # Check if the forcefield is in the leaprc directory
194 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"leaprc.{forcefield}")
195 if os.path.exists(leaprc_path):
196 leaprc_paths.append(leaprc_path)
197 continue
199 # Check if the forcefield is in the oldff directory
200 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"leaprc.{forcefield}")
201 if os.path.exists(leaprc_path):
202 leaprc_paths.append(leaprc_path)
203 continue
205 # Check if the forcefield is in the leaprc directory without the leaprc prefix
206 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"{forcefield}")
207 if os.path.exists(leaprc_path):
208 leaprc_paths.append(leaprc_path)
209 continue
211 # Check if the forcefield is in the oldff directory without the leaprc prefix
212 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"{forcefield}")
213 if os.path.exists(leaprc_path):
214 leaprc_paths.append(leaprc_path)
215 continue
217 new_num_paths = len(leaprc_paths)
219 if new_num_paths == num_paths:
220 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.")
222 return leaprc_paths
224 # def check_data_params(self, out_log, err_log):
225 # """ Checks input/output paths correctness """
227 # # Check input(s)
228 # 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__)
229 # 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__)
230 # 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__)
231 # # 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__)
232 # # 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__)
234 # # Check output(s)
235 # 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__)
236 # 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__)
237 # 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__)
239 @launchlogger
240 def launch(self):
241 """Launches the execution of the LeapSolvate module."""
243 # check input/output paths and parameters
244 # self.check_data_params(self.out_log, self.err_log)
246 # Setup Biobb
247 if self.check_restart():
248 return 0
249 self.stage_files()
251 box_command = "solvateOct"
252 if self.box_type == "cubic":
253 box_command = "solvateBox"
255 # Forcefield
256 # source_ff_command = "source leaprc." + self.forcefield
258 # Water Type
259 # leaprc.water.tip4pew, tip4pd, tip3p, spceb, spce, opc, fb4, fb3
260 # Values: POL3BOX, QSPCFWBOX, SPCBOX, SPCFWBOX, TIP3PBOX, TIP3PFBOX, TIP4PBOX, TIP4PEWBOX, OPCBOX, OPC3BOX, TIP5PBOX.
261 source_wat_command = "source leaprc.water.tip3p"
262 if self.water_type == "TIP4PEWBOX":
263 source_wat_command = "leaprc.water.tip4pew"
264 if self.water_type == "TIP4PBOX":
265 source_wat_command = "leaprc.water.tip4pd"
266 if re.match(r"SPC", self.water_type):
267 source_wat_command = "source leaprc.water.spce"
268 if re.match(r"OPC", self.water_type):
269 source_wat_command = "source leaprc.water.opc"
271 # Counterions
272 ions_command = ""
273 if self.neutralise:
274 ions_command = (
275 ions_command + "addions mol " + self.negative_ions_type + " 0 \n"
276 )
277 ions_command = (
278 ions_command + "addions mol " + self.positive_ions_type + " 0 \n"
279 )
281 if self.negative_ions_number != 0:
282 ions_command = (
283 ions_command + "addions mol " + self.negative_ions_type + " " + str(self.negative_ions_number) + " \n"
284 )
285 if self.positive_ions_number != 0:
286 ions_command = (
287 ions_command + "addions mol " + self.positive_ions_type + " " + str(self.positive_ions_number) + " \n"
288 )
290 # Creating temporary folder & Leap configuration (instructions) file
291 if self.container_path:
292 instructions_file = str(
293 PurePath(self.stage_io_dict["unique_dir"]).joinpath("leap.in")
294 )
295 instructions_file_path = str(
296 PurePath(self.container_volume_path).joinpath("leap.in")
297 )
298 tmp_folder = None
299 else:
300 tmp_folder = fu.create_unique_dir()
301 instructions_file = str(PurePath(tmp_folder).joinpath("leap.in"))
302 fu.log("Creating %s temporary folder" % tmp_folder, self.out_log)
303 instructions_file_path = instructions_file
305 ligands_lib_list = []
306 if self.io_dict["in"]["input_lib_path"] is not None:
307 if self.io_dict["in"]["input_lib_path"].endswith(".zip"):
308 ligands_lib_list = fu.unzip_list(
309 self.stage_io_dict["in"]["input_lib_path"],
310 dest_dir=tmp_folder,
311 out_log=self.out_log,
312 )
313 else:
314 ligands_lib_list.append(self.stage_io_dict["in"]["input_lib_path"])
316 ligands_frcmod_list = []
317 if self.io_dict["in"]["input_frcmod_path"] is not None:
318 if self.io_dict["in"]["input_frcmod_path"].endswith(".zip"):
319 ligands_frcmod_list = fu.unzip_list(
320 self.stage_io_dict["in"]["input_frcmod_path"],
321 dest_dir=tmp_folder,
322 out_log=self.out_log,
323 )
324 else:
325 ligands_frcmod_list.append(
326 self.stage_io_dict["in"]["input_frcmod_path"]
327 )
329 amber_params_list = []
330 if self.io_dict["in"]["input_params_path"] is not None:
331 if self.io_dict["in"]["input_params_path"].endswith(".zip"):
332 amber_params_list = fu.unzip_list(
333 self.stage_io_dict["in"]["input_params_path"],
334 dest_dir=tmp_folder,
335 out_log=self.out_log,
336 )
337 else:
338 amber_params_list.append(self.stage_io_dict["in"]["input_params_path"])
340 amber_prep_list = []
341 if self.io_dict["in"]["input_prep_path"] is not None:
342 if self.io_dict["in"]["input_prep_path"].endswith(".zip"):
343 amber_prep_list = fu.unzip_list(
344 self.stage_io_dict["in"]["input_prep_path"],
345 dest_dir=tmp_folder,
346 out_log=self.out_log,
347 )
348 else:
349 amber_prep_list.append(self.stage_io_dict["in"]["input_prep_path"])
351 leap_source_list = []
352 if self.io_dict["in"]["input_source_path"] is not None:
353 if self.io_dict["in"]["input_source_path"].endswith(".zip"):
354 leap_source_list = fu.unzip_list(
355 self.stage_io_dict["in"]["input_source_path"],
356 dest_dir=tmp_folder,
357 out_log=self.out_log,
358 )
359 else:
360 leap_source_list.append(self.stage_io_dict["in"]["input_source_path"])
362 with open(instructions_file, "w") as leapin:
363 # Forcefields loaded by default:
364 # Protein: ff14SB (PARM99 + frcmod.ff99SB + frcmod.parmbsc0 + OL3 for RNA)
365 # leapin.write("source leaprc.protein.ff14SB \n")
366 # DNA: parmBSC1 (ParmBSC1 (ff99 + bsc0 + bsc1) for DNA. Ivani et al. Nature Methods 13: 55, 2016)
367 # leapin.write("source leaprc.DNA.bsc1 \n")
368 # Ligands: GAFF (General Amber Force field, J. Comput. Chem. 2004 Jul 15;25(9):1157-74)
369 # leapin.write("source leaprc.gaff \n")
371 # Forcefields loaded from input forcefield property
372 for t in self.forcefield:
373 if self.container_path:
374 leapin.write("source leaprc.{}\n".format(t))
375 else:
376 leapin.write("source {}\n".format(t))
378 # Additional Leap commands
379 for leap_commands in leap_source_list:
380 leapin.write("source " + leap_commands + "\n")
382 # Ions Type
383 if self.ions_type != "None":
384 leapin.write("loadamberparams frcmod." + self.ions_type + "\n")
386 # Additional Amber parameters
387 for amber_params in amber_params_list:
388 leapin.write("loadamberparams " + amber_params + "\n")
390 # Additional Amber prep files
391 for amber_prep in amber_prep_list:
392 leapin.write("loadamberprep " + amber_prep + "\n")
394 # Water Model loaded from input water_model property
395 leapin.write(source_wat_command + " \n")
397 # Ligand(s) libraries (if any)
398 for amber_lib in ligands_lib_list:
399 leapin.write("loadOff " + amber_lib + "\n")
400 for amber_frcmod in ligands_frcmod_list:
401 leapin.write("loadamberparams " + amber_frcmod + "\n")
403 # Loading PDB file
404 leapin.write(
405 "mol = loadpdb " + self.stage_io_dict["in"]["input_pdb_path"] + " \n"
406 )
408 # Generating box + adding water molecules
409 leapin.write(
410 box_command + " mol " + self.water_type + " " + str(self.distance_to_molecule)
411 )
412 leapin.write(
413 " iso " + str(self.closeness) + "\n"
414 ) if self.iso else leapin.write(" " + str(self.closeness) + "\n")
416 # Adding counterions
417 leapin.write(ions_command)
419 # Saving output PDB file, coordinates and topology
420 leapin.write(
421 "savepdb mol " + self.stage_io_dict["out"]["output_pdb_path"] + " \n"
422 )
423 leapin.write(
424 "saveAmberParm mol " + self.stage_io_dict["out"]["output_top_path"] + " " + self.stage_io_dict["out"]["output_crd_path"] + "\n"
425 )
426 leapin.write("quit \n")
428 # Command line
429 self.cmd = [self.binary_path, "-f", instructions_file_path]
431 # Run Biobb block
432 self.run_biobb()
434 # Copy files to host
435 self.copy_to_host()
437 # Saving octahedron box with all decimals in PDB file. Needed for the add_ions BB.
439 # Getting octahedron box from generated crd file
440 with open(self.io_dict["out"]["output_crd_path"], "r") as file:
441 for line in file:
442 pass
444 # Adding box as a first line in the generated pdb file with OCTBOX tag
445 octbox = "OCTBOX " + line
446 with open(self.io_dict["out"]["output_pdb_path"], "r+") as f:
447 content = f.read()
448 f.seek(0, 0)
449 f.write(octbox + content)
451 # remove temporary folder(s)
452 self.tmp_files.extend([str(tmp_folder), "leap.log"])
453 self.remove_tmp_files()
455 self.check_arguments(output_files_created=True, raise_exception=False)
457 return self.return_code
460def leap_solvate(
461 input_pdb_path: str,
462 output_pdb_path: str,
463 output_top_path: str,
464 output_crd_path: str,
465 input_lib_path: Optional[str] = None,
466 input_frcmod_path: Optional[str] = None,
467 input_params_path: Optional[str] = None,
468 input_prep_path: Optional[str] = None,
469 input_source_path: Optional[str] = None,
470 properties: Optional[dict] = None,
471 **kwargs,
472) -> int:
473 """Create the :class:`LeapSolvate <leap.leap_solvate.LeapSolvate>` class and
474 execute the :meth:`launch() <leap.leap_solvate.LeapSolvate.launch>` method."""
475 return LeapSolvate(**dict(locals())).launch()
478leap_solvate.__doc__ = LeapSolvate.__doc__
479main = LeapSolvate.get_main(leap_solvate, "Generating and solvating a system box for an AMBER MD system. using tLeap program from AmberTools MD package.")
481if __name__ == "__main__":
482 main()