Coverage for biobb_amber/leap/leap_solvate.py: 70%
148 statements
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-07 08:11 +0000
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-07 08:11 +0000
1#!/usr/bin/env python3
3"""Module containing the LeapSolvate class and the command line interface."""
4import argparse
5import re
6from pathlib import PurePath
7from biobb_common.generic.biobb_object import BiobbObject
8from biobb_common.configuration import settings
9from biobb_common.tools import file_utils as fu
10from biobb_common.tools.file_utils import launchlogger
11from biobb_amber.leap.common import check_input_path, check_output_path
14class LeapSolvate(BiobbObject):
15 """
16 | biobb_amber LeapSolvate
17 | Wrapper of the `AmberTools (AMBER MD Package) leap tool <https://ambermd.org/AmberTools.php>`_ module.
18 | Creates and solvates a system box for an AMBER MD system using tLeap tool from the AmberTools MD package.
20 Args:
21 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).
22 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).
23 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).
24 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).
25 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).
26 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).
27 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).
28 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).
29 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
30 * **forcefield** (*list*) - (["protein.ff14SB","DNA.bsc1","gaff"]) Forcefield to be used for the structure generation. Values: protein.ff14SB, protein.ff19SB, DNA.bsc1, DNA.OL15, RNA.OL3, gaff.
31 * **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.
32 * **box_type** (*str*) - ("truncated_octahedron") Type for the MD system box. Values: cubic, truncated_octahedron.
33 * **ions_type** (*str*) - ("ionsjc_tip3p") Ions type. Values: ionsjc_tip3p, ionsjc_spce, ionsff99_tip3p, ions_charmm22, ionsjc_tip4pew, None.
34 * **neutralise** (*bool*) - ("False") Energetically neutralise the system adding the necessary counterions.
35 * **iso** (*bool*) - ("False") Make the box isometric.
36 * **positive_ions_number** (*int*) - (0) Number of additional positive ions to include in the system box.
37 * **negative_ions_number** (*int*) - (0) Number of additional negative ions to include in the system box.
38 * **positive_ions_type** (*str*) - ("Na+") Type of additional positive ions to include in the system box. Values: Na+,K+.
39 * **negative_ions_type** (*str*) - ("Cl-") Type of additional negative ions to include in the system box. Values: Cl-.
40 * **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.
41 * **closeness** (*float*) - ("1.0") How close, in Å, solvent ATOMs may come to solute ATOMs.
42 * **binary_path** (*str*) - ("tleap") Path to the tleap executable binary.
43 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
44 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
45 * **container_path** (*str*) - (None) Container path definition.
46 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition.
47 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
48 * **container_working_dir** (*str*) - (None) Container working directory definition.
49 * **container_user_id** (*str*) - (None) Container user_id definition.
50 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
52 Examples:
53 This is a use example of how to use the building block from Python::
54 from biobb_amber.leap.leap_solvate import leap_solvate
55 prop = {
56 'forcefield': ['protein.ff14SB'],
57 'water_type': 'TIP3PBOX',
58 'box_type': 'truncated_octahedron',
59 'neutralise' : True
60 }
61 leap_solvate(input_pdb_path='/path/to/structure.pdb',
62 output_pdb_path='/path/to/newStructure.pdb',
63 output_top_path='/path/to/newTopology.top',
64 output_crd_path='/path/to/newCoordinates.crd',
65 properties=prop)
67 Info:
68 * wrapped_software:
69 * name: AmberTools tLeap
70 * version: >20.9
71 * license: LGPL 2.1
72 * ontology:
73 * name: EDAM
74 * schema: http://edamontology.org/EDAM.owl
76 """
78 def __init__(self, input_pdb_path: str, output_pdb_path: str,
79 output_top_path: str, output_crd_path: str,
80 input_lib_path: str = None, input_frcmod_path: str = None,
81 input_params_path: str = None, input_source_path: str = None,
82 properties: dict = None, **kwargs):
84 properties = properties or {}
86 # Call parent class constructor
87 super().__init__(properties)
88 self.locals_var_dict = locals().copy()
90 # Input/Output files
91 self.io_dict = {
92 'in': {'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_source_path': input_source_path},
97 'out': {'output_pdb_path': output_pdb_path,
98 'output_top_path': output_top_path,
99 'output_crd_path': output_crd_path}
100 }
102 # # Ligand Parameter lists
103 # self.ligands_lib_list = []
104 # if input_lib_path:
105 # self.ligands_lib_list.append(input_lib_path)
106 #
107 # self.ligands_frcmod_list = []
108 # if input_frcmod_path:
109 # self.ligands_frcmod_list.append(input_frcmod_path)
111 # Properties specific for BB
112 self.properties = properties
113 self.forcefield = properties.get('forcefield', ["protein.ff14SB", "DNA.bsc1", "gaff"])
114 self.water_type = properties.get('water_type', "TIP3PBOX")
115 self.box_type = properties.get('box_type', "truncated_octahedron")
116 self.ions_type = properties.get('ions_type', "ionsjc_tip3p")
117 self.neutralise = properties.get('neutralise', False)
118 self.iso = properties.get('iso', False)
119 self.positive_ions_number = properties.get('positive_ions_number', 0)
120 self.positive_ions_type = properties.get('positive_ions_type', "Na+")
121 self.negative_ions_number = properties.get('negative_ions_number', 0)
122 self.negative_ions_type = properties.get('negative_ions_type', "Cl-")
123 self.distance_to_molecule = properties.get('distance_to_molecule', 8.0)
124 self.closeness = properties.get('closeness', 1.0)
125 self.binary_path = properties.get('binary_path', 'tleap')
127 # Check the properties
128 self.check_properties(properties)
129 self.check_arguments()
131 def check_data_params(self, out_log, err_log):
132 """ Checks input/output paths correctness """
134 # Check input(s)
135 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__)
136 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__)
137 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__)
138 # 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__)
139 # 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__)
141 # Check output(s)
142 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__)
143 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__)
144 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__)
146 @launchlogger
147 def launch(self):
148 """Launches the execution of the LeapSolvate module."""
150 # check input/output paths and parameters
151 self.check_data_params(self.out_log, self.err_log)
153 # Setup Biobb
154 if self.check_restart():
155 return 0
156 self.stage_files()
158 box_command = "solvateOct"
159 if self.box_type == "cubic":
160 box_command = "solvateBox"
162 # Forcefield
163 # source_ff_command = "source leaprc." + self.forcefield
165 # Water Type
166 # leaprc.water.tip4pew, tip4pd, tip3p, spceb, spce, opc, fb4, fb3
167 # Values: POL3BOX, QSPCFWBOX, SPCBOX, SPCFWBOX, TIP3PBOX, TIP3PFBOX, TIP4PBOX, TIP4PEWBOX, OPCBOX, OPC3BOX, TIP5PBOX.
168 source_wat_command = "source leaprc.water.tip3p"
169 if self.water_type == "TIP4PEWBOX":
170 source_wat_command = "leaprc.water.tip4pew"
171 if self.water_type == "TIP4PBOX":
172 source_wat_command = "leaprc.water.tip4pd"
173 if re.match(r"SPC", self.water_type):
174 source_wat_command = "source leaprc.water.spce"
175 if re.match(r"OPC", self.water_type):
176 source_wat_command = "source leaprc.water.opc"
178 # Counterions
179 ions_command = ""
180 if self.neutralise:
181 ions_command = ions_command + "addions mol " + self.negative_ions_type + " 0 \n"
182 ions_command = ions_command + "addions mol " + self.positive_ions_type + " 0 \n"
184 if self.negative_ions_number != 0:
185 ions_command = ions_command + "addions mol " + self.negative_ions_type + " " + str(self.negative_ions_number) + " \n"
186 if self.positive_ions_number != 0:
187 ions_command = ions_command + "addions mol " + self.positive_ions_type + " " + str(self.positive_ions_number) + " \n"
189 # Creating temporary folder & Leap configuration (instructions) file
190 if self.container_path:
191 instructions_file = str(PurePath(self.stage_io_dict['unique_dir']).joinpath("leap.in"))
192 instructions_file_path = str(PurePath(self.container_volume_path).joinpath("leap.in"))
193 self.tmp_folder = None
194 else:
195 self.tmp_folder = fu.create_unique_dir()
196 instructions_file = str(PurePath(self.tmp_folder).joinpath("leap.in"))
197 fu.log('Creating %s temporary folder' % self.tmp_folder, self.out_log)
198 instructions_file_path = instructions_file
200 ligands_lib_list = []
201 if self.io_dict['in']['input_lib_path'] is not None:
202 if self.io_dict['in']['input_lib_path'].endswith('.zip'):
203 ligands_lib_list = fu.unzip_list(self.stage_io_dict['in']['input_lib_path'], dest_dir=self.tmp_folder, out_log=self.out_log)
204 else:
205 ligands_lib_list.append(self.stage_io_dict['in']['input_lib_path'])
207 ligands_frcmod_list = []
208 if self.io_dict['in']['input_frcmod_path'] is not None:
209 if self.io_dict['in']['input_frcmod_path'].endswith('.zip'):
210 ligands_frcmod_list = fu.unzip_list(self.stage_io_dict['in']['input_frcmod_path'], dest_dir=self.tmp_folder, out_log=self.out_log)
211 else:
212 ligands_frcmod_list.append(self.stage_io_dict['in']['input_frcmod_path'])
214 amber_params_list = []
215 if self.io_dict['in']['input_params_path'] is not None:
216 if self.io_dict['in']['input_params_path'].endswith('.zip'):
217 amber_params_list = fu.unzip_list(self.stage_io_dict['in']['input_params_path'], dest_dir=self.tmp_folder, out_log=self.out_log)
218 else:
219 amber_params_list.append(self.stage_io_dict['in']['input_params_path'])
221 leap_source_list = []
222 if self.io_dict['in']['input_source_path'] is not None:
223 if self.io_dict['in']['input_source_path'].endswith('.zip'):
224 leap_source_list = fu.unzip_list(self.stage_io_dict['in']['input_source_path'], dest_dir=self.tmp_folder, out_log=self.out_log)
225 else:
226 leap_source_list.append(self.stage_io_dict['in']['input_source_path'])
228 with open(instructions_file, 'w') as leapin:
229 # Forcefields loaded by default:
230 # Protein: ff14SB (PARM99 + frcmod.ff99SB + frcmod.parmbsc0 + OL3 for RNA)
231 # leapin.write("source leaprc.protein.ff14SB \n")
232 # DNA: parmBSC1 (ParmBSC1 (ff99 + bsc0 + bsc1) for DNA. Ivani et al. Nature Methods 13: 55, 2016)
233 # leapin.write("source leaprc.DNA.bsc1 \n")
234 # Ligands: GAFF (General Amber Force field, J. Comput. Chem. 2004 Jul 15;25(9):1157-74)
235 # leapin.write("source leaprc.gaff \n")
237 # Forcefields loaded from input forcefield property
238 for t in self.forcefield:
239 leapin.write("source leaprc.{}\n".format(t))
241 # Additional Leap commands
242 for leap_commands in leap_source_list:
243 leapin.write("source " + leap_commands + "\n")
245 # Ions Type
246 if self.ions_type != "None":
247 leapin.write("loadamberparams frcmod." + self.ions_type + "\n")
249 # Additional Amber parameters
250 for amber_params in amber_params_list:
251 leapin.write("loadamberparams " + amber_params + "\n")
253 # Water Model loaded from input water_model property
254 leapin.write(source_wat_command + " \n")
256 # Ligand(s) libraries (if any)
257 for amber_lib in ligands_lib_list:
258 leapin.write("loadOff " + amber_lib + "\n")
259 for amber_frcmod in ligands_frcmod_list:
260 leapin.write("loadamberparams " + amber_frcmod + "\n")
262 # Loading PDB file
263 leapin.write("mol = loadpdb " + self.stage_io_dict['in']['input_pdb_path'] + " \n")
265 # Generating box + adding water molecules
266 leapin.write(box_command + " mol " + self.water_type + " " + str(self.distance_to_molecule))
267 leapin.write(" iso " + str(self.closeness) + "\n") if self.iso else leapin.write(" " + str(self.closeness) + "\n")
269 # Adding counterions
270 leapin.write(ions_command)
272 # Saving output PDB file, coordinates and topology
273 leapin.write("savepdb mol " + self.stage_io_dict['out']['output_pdb_path'] + " \n")
274 leapin.write("saveAmberParm mol " + self.stage_io_dict['out']['output_top_path'] + " " + self.stage_io_dict['out']['output_crd_path'] + "\n")
275 leapin.write("quit \n")
277 # Command line
278 self.cmd = [self.binary_path,
279 '-f', instructions_file_path
280 ]
282 # Run Biobb block
283 self.run_biobb()
285 # Copy files to host
286 self.copy_to_host()
288 # Saving octahedron box with all decimals in PDB file. Needed for the add_ions BB.
290 # Getting octahedron box from generated crd file
291 with open(self.io_dict['out']['output_crd_path'], "r") as file:
292 for line in file:
293 pass
295 # Adding box as a first line in the generated pdb file with OCTBOX tag
296 octbox = "OCTBOX " + line
297 with open(self.io_dict['out']['output_pdb_path'], 'r+') as f:
298 content = f.read()
299 f.seek(0, 0)
300 f.write(octbox + content)
302 # remove temporary folder(s)
303 self.tmp_files.extend([
304 self.stage_io_dict.get("unique_dir"),
305 self.tmp_folder,
306 "leap.log"
307 ])
308 self.remove_tmp_files()
310 self.check_arguments(output_files_created=True, raise_exception=False)
312 return self.return_code
315def leap_solvate(input_pdb_path: str, output_pdb_path: str,
316 output_top_path: str, output_crd_path: str,
317 input_lib_path: str = None, input_frcmod_path: str = None,
318 input_params_path: str = None, input_source_path: str = None,
319 properties: dict = None, **kwargs) -> int:
320 """Create :class:`LeapSolvate <leap.leap_solvate.LeapSolvate>`leap.leap_solvate.LeapSolvate class and
321 execute :meth:`launch() <leap.leap_solvate.LeapSolvate.launch>` method"""
323 return LeapSolvate(input_pdb_path=input_pdb_path,
324 input_lib_path=input_lib_path,
325 input_frcmod_path=input_frcmod_path,
326 input_params_path=input_params_path,
327 input_source_path=input_source_path,
328 output_pdb_path=output_pdb_path,
329 output_top_path=output_top_path,
330 output_crd_path=output_crd_path,
331 properties=properties).launch()
334def main():
335 parser = argparse.ArgumentParser(description='Generating and solvating a system box for an AMBER MD system. using tLeap program from AmberTools MD package.', formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
336 parser.add_argument('--config', required=False, help='Configuration file')
338 # Specific args
339 required_args = parser.add_argument_group('required arguments')
340 required_args.add_argument('--input_pdb_path', required=True, help='Input 3D structure PDB file. Accepted formats: pdb.')
341 required_args.add_argument('--input_lib_path', required=False, help='Input ligand library parameters file. Accepted formats: lib, zip.')
342 required_args.add_argument('--input_frcmod_path', required=False, help='Input ligand frcmod parameters file. Accepted formats: frcmod, zip.')
343 required_args.add_argument('--input_params_path', required=False, help='Additional leap parameter files to load with loadAmberParams Leap command. Accepted formats: leapin, in, txt, zip.')
344 required_args.add_argument('--input_source_path', required=False, help='Additional leap command files to load with source Leap command. Accepted formats: leapin, in, txt, zip.')
345 required_args.add_argument('--output_pdb_path', required=True, help='Output 3D structure PDB file matching the topology file. Accepted formats: pdb.')
346 required_args.add_argument('--output_top_path', required=True, help='Output topology file (AMBER ParmTop). Accepted formats: top.')
347 required_args.add_argument('--output_crd_path', required=True, help='Output coordinates file (AMBER crd). Accepted formats: crd.')
349 args = parser.parse_args()
350 config = args.config if args.config else None
351 properties = settings.ConfReader(config=config).get_prop_dic()
353 # Specific call
354 leap_solvate(input_pdb_path=args.input_pdb_path,
355 input_lib_path=args.input_lib_path,
356 input_frcmod_path=args.input_frcmod_path,
357 input_params_path=args.input_params_path,
358 input_source_path=args.input_source_path,
359 output_pdb_path=args.output_pdb_path,
360 output_top_path=args.output_top_path,
361 output_crd_path=args.output_crd_path,
362 properties=properties)
365if __name__ == '__main__':
366 main()