Coverage for biobb_pmx/pmxbiobb/pmxcreate_top.py: 84%
87 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-23 10:10 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-23 10:10 +0000
1#!/usr/bin/env python3
3"""Module containing the PMX create_top class and the command line interface."""
5import argparse
6import os
7import shutil
8import sys
9from pathlib import Path, PurePath
10from typing import Optional
12from biobb_common.configuration import settings
13from biobb_common.generic.biobb_object import BiobbObject
14from biobb_common.tools import file_utils as fu
15from biobb_common.tools.file_utils import launchlogger
18class Pmxcreate_top(BiobbObject):
19 """
20 | biobb_pmx Pmxcreate_top
21 | Wrapper class for the `PMX create_top <https://github.com/deGrootLab/pmx>`_ module.
22 | Create a complete ligand topology file from two input topology files.
24 Args:
25 input_topology1_path (str): Path to the input topology file 1. File type: input. `Sample file <https://github.com/bioexcel/biobb_pmx/raw/master/biobb_pmx/test/data/pmx/ligand.itp>`_. Accepted formats: itp (edam:format_3883).
26 input_topology2_path (str): Path to the input topology file 2. File type: input. `Sample file <https://github.com/bioexcel/biobb_pmx/raw/master/biobb_pmx/test/data/pmx/ligand.itp>`_. Accepted formats: itp (edam:format_3883).
27 output_topology_path (str): Path to the complete ligand topology file. File type: output. `Sample file <https://github.com/bioexcel/biobb_pmx/raw/master/biobb_pmx/test/data/pmx/ligand_top.zip>`_. Accepted formats: zip (edam:format_3987).
29 properties (dic):
30 * **force_field** (*str*) - ("amber99sb-star-ildn-mut.ff") Force-field to be included in the generated topology.
31 * **water** (*str*) - ("tip3p") Water model to be included in the generated topology.
32 * **system_name** (*str*) - ("Pmx topology") System name to be included in the generated topology.
33 * **mols** (*list*) - ([['Protein',1],['Ligand',1]]) Molecules to be included in the generated topology.
34 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
35 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
36 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
37 * **container_path** (*str*) - (None) Path to the binary executable of your container.
38 * **container_image** (*str*) - (None) Container Image identifier.
39 * **container_volume_path** (*str*) - ("/inout") Path to an internal directory in the container.
40 * **container_working_dir** (*str*) - (None) Path to the internal CWD in the container.
41 * **container_user_id** (*str*) - (None) User number id to be mapped inside the container.
42 * **container_shell_path** (*str*) - ("/bin/bash") Path to the binary executable of the container shell.
44 Examples:
45 This is a use example of how to use the building block from Python::
47 from biobb_pmx.pmxbiobb.pmxcreate_top import pmxcreate_top
48 prop = {
49 'remove_tmp' : True
50 }
51 pmxcreate_top(input_topology1_path='/path/to/myTopology1.itp',
52 input_topology2_path='/path/to/myTopology2.itp',
53 output_topology_path='/path/to/myMergedTopology.zip',
54 properties=prop)
56 Info:
57 * wrapped_software:
58 * name: PMX create_top
59 * version: >=1.0.1
60 * license: GNU
61 * ontology:
62 * name: EDAM
63 * schema: http://edamontology.org/EDAM.owl
65 """
67 def __init__(
68 self,
69 input_topology1_path: str,
70 input_topology2_path: str,
71 output_topology_path: str,
72 properties: Optional[dict] = None,
73 **kwargs,
74 ) -> None:
75 properties = properties or {}
77 # Call parent class constructor
78 super().__init__(properties)
79 self.locals_var_dict = locals().copy()
81 # Input/Output files
82 self.io_dict = {
83 "in": {
84 "input_topology1_path": input_topology1_path,
85 "input_topology2_path": input_topology2_path,
86 },
87 "out": {"output_topology_path": output_topology_path},
88 }
90 # Properties specific for BB
91 self.force_field = properties.get("force_field", "amber99sb-star-ildn-mut.ff")
92 self.water = properties.get("water", "tip3p")
93 self.system_name = properties.get("system_name", "Pmx topology")
94 self.mols = properties.get("mols", [["Protein", 1], ["Ligand", 1]])
96 # Properties common in all PMX BB
97 self.gmx_lib = properties.get("gmx_lib", None)
98 if not self.gmx_lib and os.environ.get("CONDA_PREFIX", ""):
99 python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
100 self.gmx_lib = str(
101 Path(os.environ.get("CONDA_PREFIX", "")).joinpath(
102 f"lib/python{python_version}/site-packages/pmx/data/mutff/"
103 )
104 )
105 if properties.get("container_path"):
106 self.gmx_lib = str(
107 Path("/usr/local/").joinpath(
108 "lib/python3.7/site-packages/pmx/data/mutff/"
109 )
110 )
111 self.binary_path = properties.get("binary_path", "pmx")
113 # Check the properties
114 self.check_properties(properties)
115 self.check_arguments()
117 @launchlogger
118 def launch(self) -> int:
119 """Execute the :class:`Pmxcreate_top <pmx.pmxcreate_top.Pmxcreate_top>` pmx.pmxcreate_top.Pmxcreate_top object."""
120 # os.chdir("/Users/hospital/BioBB/Notebooks_dev/biobb_wf_pmx_tutorial_ligands/biobb_wf_pmx_tutorial/notebooks")
121 # Setup Biobb
122 if self.check_restart():
123 return 0
124 self.stage_files()
126 fu.log("Running create_top from pmx package...\n", self.out_log)
128 # Creating temporary folder
129 self.tmp_folder = fu.create_unique_dir()
130 fu.log("Creating %s temporary folder" % self.tmp_folder, self.out_log)
132 itp = os.path.basename(
133 os.path.normpath(self.stage_io_dict["in"]["input_topology1_path"])
134 )
135 fu.log("Creating %s itp file in temporary folder" % itp, self.out_log)
136 itp_local = str(PurePath(self.tmp_folder).joinpath(itp))
137 shutil.copyfile(self.io_dict["in"]["input_topology1_path"], itp_local)
139 itp2 = os.path.basename(
140 os.path.normpath(self.stage_io_dict["in"]["input_topology2_path"])
141 )
142 fu.log("Creating %s itp file in temporary folder" % itp2, self.out_log)
143 itp2_local = str(PurePath(self.tmp_folder).joinpath(itp2))
144 shutil.copyfile(self.io_dict["in"]["input_topology2_path"], itp2_local)
146 top_local = str(PurePath(self.tmp_folder).joinpath("topology.top"))
148 # _create_top function, taken from the pmx AZ tutorial:
149 # https://github.com/deGrootLab/pmx/blob/develop/tutorials/AZtutorial.py
150 fp = open(top_local, "w")
151 # BioBB signature
152 fp.write("; Topology generated by the BioBB pmxcreate_top building block\n\n")
153 # ff itp
154 fp.write('#include "%s/forcefield.itp"\n\n' % self.force_field)
155 # additional itp
156 # for i in self.itps:
157 # fp.write('#include "%s"\n' % i)
158 fp.write('#include "%s"\n' % itp)
159 fp.write('#include "%s"\n\n' % itp2)
160 # water itp
161 fp.write('#include "%s/%s.itp"\n' % (self.force_field, self.water))
162 # ions
163 fp.write('#include "%s/ions.itp"\n\n' % self.force_field)
164 # system
165 fp.write("[ system ]\n")
166 fp.write("{0}\n\n".format(self.system_name))
167 # molecules
168 fp.write("[ molecules ]\n")
169 for mol in self.mols:
170 fp.write("%s %s\n" % (mol[0], mol[1]))
171 fp.close()
173 # zip topology
174 current_cwd = os.getcwd()
175 top_final = str(
176 PurePath(current_cwd).joinpath(self.io_dict["out"]["output_topology_path"])
177 )
179 os.chdir(self.tmp_folder)
180 fu.log("Compressing topology to: %s" % top_final, self.out_log, self.global_log)
181 fu.zip_top(zip_file=top_final, top_file="topology.top", out_log=self.out_log)
182 os.chdir(current_cwd)
184 fu.log("Exit code 0\n", self.out_log)
186 # Run Biobb block
187 # self.run_biobb()
189 # Copy files to host
190 self.copy_to_host()
192 # self.tmp_files.append(self.stage_io_dict.get("unique_dir", ""))
193 self.tmp_files.extend([self.tmp_folder])
194 self.remove_tmp_files()
196 self.check_arguments(output_files_created=True, raise_exception=False)
197 return self.return_code
200def pmxcreate_top(
201 input_topology1_path: str,
202 input_topology2_path: str,
203 output_topology_path: str,
204 properties: Optional[dict] = None,
205 **kwargs,
206) -> int:
207 """Execute the :class:`Pmxcreate_top <pmx.pmxcreate_top.Pmxcreate_top>` class and
208 execute the :meth:`launch() <pmx.pmxmcreate_top.Pmxmcreate_top.launch> method."""
210 return Pmxcreate_top(
211 input_topology1_path=input_topology1_path,
212 input_topology2_path=input_topology2_path,
213 output_topology_path=output_topology_path,
214 properties=properties,
215 **kwargs,
216 ).launch()
218 pmxcreate_top.__doc__ = Pmxcreate_top.__doc__
221def main():
222 """Command line execution of this building block. Please check the command line documentation."""
223 parser = argparse.ArgumentParser(
224 description="Run PMX create_top module",
225 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999),
226 )
227 parser.add_argument(
228 "-c",
229 "--config",
230 required=False,
231 help="This file can be a YAML file, JSON file or JSON string",
232 )
234 # Specific args of each building block
235 required_args = parser.add_argument_group("required arguments")
236 required_args.add_argument(
237 "--input_topology1_path",
238 required=True,
239 help="Path to the input topology file 1",
240 )
241 required_args.add_argument(
242 "--input_topology2_path",
243 required=True,
244 help="Path to the input topology file 2",
245 )
246 required_args.add_argument(
247 "--output_topology_path",
248 required=True,
249 help="Path to the complete ligand topology file",
250 )
252 args = parser.parse_args()
253 config = args.config if args.config else None
254 properties = settings.ConfReader(config=config).get_prop_dic()
256 # Specific call of each building block
257 pmxcreate_top(
258 input_topology1_path=args.input_topology1_path,
259 input_topology2_path=args.input_topology2_path,
260 output_topology_path=args.output_topology_path,
261 properties=properties,
262 )
265if __name__ == "__main__":
266 main()