Coverage for biobb_amber / leap / leap_solvate.py: 69%
164 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 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 # Set default forcefields
130 amber_home_path = os.getenv("AMBERHOME")
131 protein_ff14SB_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.protein.ff14SB')
132 dna_bsc1_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.DNA.bsc1')
133 gaff_path = os.path.join(amber_home_path, 'dat', 'leap', 'cmd', 'leaprc.gaff')
135 # Properties specific for BB
136 self.properties = properties
137 self.forcefield = _from_string_to_list(
138 properties.get("forcefield", [protein_ff14SB_path, dna_bsc1_path, gaff_path])
139 )
140 # Find the paths of the leaprc files if only the force field names are provided
141 self.forcefield = self.find_leaprc_paths(self.forcefield)
142 self.water_type = properties.get("water_type", "TIP3PBOX")
143 self.box_type = properties.get("box_type", "truncated_octahedron")
144 self.ions_type = properties.get("ions_type", "ionsjc_tip3p")
145 self.neutralise = properties.get("neutralise", False)
146 self.iso = properties.get("iso", False)
147 self.positive_ions_number = properties.get("positive_ions_number", 0)
148 self.positive_ions_type = properties.get("positive_ions_type", "Na+")
149 self.negative_ions_number = properties.get("negative_ions_number", 0)
150 self.negative_ions_type = properties.get("negative_ions_type", "Cl-")
151 self.distance_to_molecule = properties.get("distance_to_molecule", 8.0)
152 self.closeness = properties.get("closeness", 1.0)
153 self.binary_path = properties.get("binary_path", "tleap")
155 # Check the properties
156 self.check_properties(properties)
157 self.check_arguments()
159 def find_leaprc_paths(self, forcefields: List[str]) -> List[str]:
160 """
161 Find the leaprc paths for the force fields provided.
163 For each item in the forcefields list, the function checks if the str is a path to an existing file.
164 If not, it tries to find the file in the $AMBERHOME/dat/leap/cmd/ directory or the $AMBERHOME/dat/leap/cmd/oldff/
165 directory with and without the leaprc prefix.
167 Args:
168 forcefields (List[str]): List of force fields to find the leaprc files for.
170 Returns:
171 List[str]: List of leaprc file paths.
172 """
174 leaprc_paths = []
176 for forcefield in forcefields:
178 num_paths = len(leaprc_paths)
180 # Check if the forcefield is a path to an existing file
181 if os.path.exists(forcefield):
182 leaprc_paths.append(forcefield)
183 continue
185 # Check if the forcefield is in the leaprc directory
186 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"leaprc.{forcefield}")
187 if os.path.exists(leaprc_path):
188 leaprc_paths.append(leaprc_path)
189 continue
191 # Check if the forcefield is in the oldff directory
192 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"leaprc.{forcefield}")
193 if os.path.exists(leaprc_path):
194 leaprc_paths.append(leaprc_path)
195 continue
197 # Check if the forcefield is in the leaprc directory without the leaprc prefix
198 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', f"{forcefield}")
199 if os.path.exists(leaprc_path):
200 leaprc_paths.append(leaprc_path)
201 continue
203 # Check if the forcefield is in the oldff directory without the leaprc prefix
204 leaprc_path = os.path.join(os.environ.get('AMBERHOME', ''), 'dat', 'leap', 'cmd', 'oldff', f"{forcefield}")
205 if os.path.exists(leaprc_path):
206 leaprc_paths.append(leaprc_path)
207 continue
209 new_num_paths = len(leaprc_paths)
211 if new_num_paths == num_paths:
212 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.")
214 return leaprc_paths
216 # def check_data_params(self, out_log, err_log):
217 # """ Checks input/output paths correctness """
219 # # Check input(s)
220 # 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__)
221 # 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__)
222 # 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__)
223 # # 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__)
224 # # 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__)
226 # # Check output(s)
227 # 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__)
228 # 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__)
229 # 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__)
231 @launchlogger
232 def launch(self):
233 """Launches the execution of the LeapSolvate module."""
235 # check input/output paths and parameters
236 # self.check_data_params(self.out_log, self.err_log)
238 # Setup Biobb
239 if self.check_restart():
240 return 0
241 self.stage_files()
243 box_command = "solvateOct"
244 if self.box_type == "cubic":
245 box_command = "solvateBox"
247 # Forcefield
248 # source_ff_command = "source leaprc." + self.forcefield
250 # Water Type
251 # leaprc.water.tip4pew, tip4pd, tip3p, spceb, spce, opc, fb4, fb3
252 # Values: POL3BOX, QSPCFWBOX, SPCBOX, SPCFWBOX, TIP3PBOX, TIP3PFBOX, TIP4PBOX, TIP4PEWBOX, OPCBOX, OPC3BOX, TIP5PBOX.
253 source_wat_command = "source leaprc.water.tip3p"
254 if self.water_type == "TIP4PEWBOX":
255 source_wat_command = "leaprc.water.tip4pew"
256 if self.water_type == "TIP4PBOX":
257 source_wat_command = "leaprc.water.tip4pd"
258 if re.match(r"SPC", self.water_type):
259 source_wat_command = "source leaprc.water.spce"
260 if re.match(r"OPC", self.water_type):
261 source_wat_command = "source leaprc.water.opc"
263 # Counterions
264 ions_command = ""
265 if self.neutralise:
266 ions_command = (
267 ions_command + "addions mol " + self.negative_ions_type + " 0 \n"
268 )
269 ions_command = (
270 ions_command + "addions mol " + self.positive_ions_type + " 0 \n"
271 )
273 if self.negative_ions_number != 0:
274 ions_command = (
275 ions_command + "addions mol " + self.negative_ions_type + " " + str(self.negative_ions_number) + " \n"
276 )
277 if self.positive_ions_number != 0:
278 ions_command = (
279 ions_command + "addions mol " + self.positive_ions_type + " " + str(self.positive_ions_number) + " \n"
280 )
282 # Creating temporary folder & Leap configuration (instructions) file
283 if self.container_path:
284 instructions_file = str(
285 PurePath(self.stage_io_dict["unique_dir"]).joinpath("leap.in")
286 )
287 instructions_file_path = str(
288 PurePath(self.container_volume_path).joinpath("leap.in")
289 )
290 self.tmp_folder = None
291 else:
292 self.tmp_folder = fu.create_unique_dir()
293 instructions_file = str(PurePath(self.tmp_folder).joinpath("leap.in"))
294 fu.log("Creating %s temporary folder" % self.tmp_folder, self.out_log)
295 instructions_file_path = instructions_file
297 ligands_lib_list = []
298 if self.io_dict["in"]["input_lib_path"] is not None:
299 if self.io_dict["in"]["input_lib_path"].endswith(".zip"):
300 ligands_lib_list = fu.unzip_list(
301 self.stage_io_dict["in"]["input_lib_path"],
302 dest_dir=self.tmp_folder,
303 out_log=self.out_log,
304 )
305 else:
306 ligands_lib_list.append(self.stage_io_dict["in"]["input_lib_path"])
308 ligands_frcmod_list = []
309 if self.io_dict["in"]["input_frcmod_path"] is not None:
310 if self.io_dict["in"]["input_frcmod_path"].endswith(".zip"):
311 ligands_frcmod_list = fu.unzip_list(
312 self.stage_io_dict["in"]["input_frcmod_path"],
313 dest_dir=self.tmp_folder,
314 out_log=self.out_log,
315 )
316 else:
317 ligands_frcmod_list.append(
318 self.stage_io_dict["in"]["input_frcmod_path"]
319 )
321 amber_params_list = []
322 if self.io_dict["in"]["input_params_path"] is not None:
323 if self.io_dict["in"]["input_params_path"].endswith(".zip"):
324 amber_params_list = fu.unzip_list(
325 self.stage_io_dict["in"]["input_params_path"],
326 dest_dir=self.tmp_folder,
327 out_log=self.out_log,
328 )
329 else:
330 amber_params_list.append(self.stage_io_dict["in"]["input_params_path"])
332 amber_prep_list = []
333 if self.io_dict["in"]["input_prep_path"] is not None:
334 if self.io_dict["in"]["input_prep_path"].endswith(".zip"):
335 amber_prep_list = fu.unzip_list(
336 self.stage_io_dict["in"]["input_prep_path"],
337 dest_dir=self.tmp_folder,
338 out_log=self.out_log,
339 )
340 else:
341 amber_prep_list.append(self.stage_io_dict["in"]["input_prep_path"])
343 leap_source_list = []
344 if self.io_dict["in"]["input_source_path"] is not None:
345 if self.io_dict["in"]["input_source_path"].endswith(".zip"):
346 leap_source_list = fu.unzip_list(
347 self.stage_io_dict["in"]["input_source_path"],
348 dest_dir=self.tmp_folder,
349 out_log=self.out_log,
350 )
351 else:
352 leap_source_list.append(self.stage_io_dict["in"]["input_source_path"])
354 with open(instructions_file, "w") as leapin:
355 # Forcefields loaded by default:
356 # Protein: ff14SB (PARM99 + frcmod.ff99SB + frcmod.parmbsc0 + OL3 for RNA)
357 # leapin.write("source leaprc.protein.ff14SB \n")
358 # DNA: parmBSC1 (ParmBSC1 (ff99 + bsc0 + bsc1) for DNA. Ivani et al. Nature Methods 13: 55, 2016)
359 # leapin.write("source leaprc.DNA.bsc1 \n")
360 # Ligands: GAFF (General Amber Force field, J. Comput. Chem. 2004 Jul 15;25(9):1157-74)
361 # leapin.write("source leaprc.gaff \n")
363 # Forcefields loaded from input forcefield property
364 for t in self.forcefield:
365 leapin.write("source {}\n".format(t))
367 # Additional Leap commands
368 for leap_commands in leap_source_list:
369 leapin.write("source " + leap_commands + "\n")
371 # Ions Type
372 if self.ions_type != "None":
373 leapin.write("loadamberparams frcmod." + self.ions_type + "\n")
375 # Additional Amber parameters
376 for amber_params in amber_params_list:
377 leapin.write("loadamberparams " + amber_params + "\n")
379 # Additional Amber prep files
380 for amber_prep in amber_prep_list:
381 leapin.write("loadamberprep " + amber_prep + "\n")
383 # Water Model loaded from input water_model property
384 leapin.write(source_wat_command + " \n")
386 # Ligand(s) libraries (if any)
387 for amber_lib in ligands_lib_list:
388 leapin.write("loadOff " + amber_lib + "\n")
389 for amber_frcmod in ligands_frcmod_list:
390 leapin.write("loadamberparams " + amber_frcmod + "\n")
392 # Loading PDB file
393 leapin.write(
394 "mol = loadpdb " + self.stage_io_dict["in"]["input_pdb_path"] + " \n"
395 )
397 # Generating box + adding water molecules
398 leapin.write(
399 box_command + " mol " + self.water_type + " " + str(self.distance_to_molecule)
400 )
401 leapin.write(
402 " iso " + str(self.closeness) + "\n"
403 ) if self.iso else leapin.write(" " + str(self.closeness) + "\n")
405 # Adding counterions
406 leapin.write(ions_command)
408 # Saving output PDB file, coordinates and topology
409 leapin.write(
410 "savepdb mol " + self.stage_io_dict["out"]["output_pdb_path"] + " \n"
411 )
412 leapin.write(
413 "saveAmberParm mol " + self.stage_io_dict["out"]["output_top_path"] + " " + self.stage_io_dict["out"]["output_crd_path"] + "\n"
414 )
415 leapin.write("quit \n")
417 # Command line
418 self.cmd = [self.binary_path, "-f", instructions_file_path]
420 # Run Biobb block
421 self.run_biobb()
423 # Copy files to host
424 self.copy_to_host()
426 # Saving octahedron box with all decimals in PDB file. Needed for the add_ions BB.
428 # Getting octahedron box from generated crd file
429 with open(self.io_dict["out"]["output_crd_path"], "r") as file:
430 for line in file:
431 pass
433 # Adding box as a first line in the generated pdb file with OCTBOX tag
434 octbox = "OCTBOX " + line
435 with open(self.io_dict["out"]["output_pdb_path"], "r+") as f:
436 content = f.read()
437 f.seek(0, 0)
438 f.write(octbox + content)
440 # remove temporary folder(s)
441 self.tmp_files.extend([str(self.tmp_folder), "leap.log"])
442 self.remove_tmp_files()
444 self.check_arguments(output_files_created=True, raise_exception=False)
446 return self.return_code
449def leap_solvate(
450 input_pdb_path: str,
451 output_pdb_path: str,
452 output_top_path: str,
453 output_crd_path: str,
454 input_lib_path: Optional[str] = None,
455 input_frcmod_path: Optional[str] = None,
456 input_params_path: Optional[str] = None,
457 input_prep_path: Optional[str] = None,
458 input_source_path: Optional[str] = None,
459 properties: Optional[dict] = None,
460 **kwargs,
461) -> int:
462 """Create the :class:`LeapSolvate <leap.leap_solvate.LeapSolvate>` class and
463 execute the :meth:`launch() <leap.leap_solvate.LeapSolvate.launch>` method."""
464 return LeapSolvate(**dict(locals())).launch()
467leap_solvate.__doc__ = LeapSolvate.__doc__
468main = LeapSolvate.get_main(leap_solvate, "Generating and solvating a system box for an AMBER MD system. using tLeap program from AmberTools MD package.")
470if __name__ == "__main__":
471 main()