Coverage for biobb_analysis/gromacs/gmx_energy.py: 81%
68 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 14:38 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 14:38 +0000
1#!/usr/bin/env python3
3"""Module containing the GMX Energy class and the command line interface."""
5import argparse
6from pathlib import PurePath
7from typing import Optional
9from biobb_common.configuration import settings
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_analysis.gromacs.common import (
15 _from_string_to_list,
16 check_energy_path,
17 check_out_xvg_path,
18 copy_instructions_file_to_container,
19 get_binary_path,
20 get_default_value,
21 get_terms,
22 get_xvg,
23)
26class GMXEnergy(BiobbObject):
27 """
28 | biobb_analysis GMXEnergy
29 | Wrapper of the GROMACS energy module for extracting energy components from a given GROMACS energy file.
30 | `GROMACS energy <http://manual.gromacs.org/current/onlinehelp/gmx-energy.html>`_ extracts energy components from an energy file. The user is prompted to interactively select the desired energy terms.
32 Args:
33 input_energy_path (str): Path to the input EDR file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/gromacs/energy.edr>`_. Accepted formats: edr (edam:format_2330).
34 output_xvg_path (str): Path to the XVG output file. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/gromacs/ref_energy.xvg>`_. Accepted formats: xvg (edam:format_2030).
35 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
36 * **xvg** (*str*) - ("none") XVG plot formatting. Values: xmgrace, xmgr, none.
37 * **terms** (*list*) - (["Potential"]) Energy terms. Values: Angle, Proper-Dih., Improper-Dih., LJ-14, Coulomb-14, LJ-\(SR\), Coulomb-\(SR\), Coul.-recip., Position-Rest., Potential, Kinetic-En., Total-Energy, Temperature, Pressure, Constr.-rmsd, Box-X, Box-Y, Box-Z, Volume, Density, pV, Enthalpy, Vir-XX, Vir-XY, Vir-XZ, Vir-YX, Vir-YY, Vir-YZ, Vir-ZX, Vir-ZY, Vir-ZZ, Pres-XX, Pres-XY, Pres-XZ, Pres-YX, Pres-YY, Pres-YZ, Pres-ZX, Pres-ZY, Pres-ZZ, #Surf*SurfTen, Box-Vel-XX, Box-Vel-YY, Box-Vel-ZZ, Mu-X, Mu-Y, Mu-Z, T-Protein, T-non-Protein, Lamb-Protein, Lamb-non-Protein.
38 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
39 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
40 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
41 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
42 * **container_path** (*str*) - (None) Container path definition.
43 * **container_image** (*str*) - ('gromacs/gromacs:2022.2') Container image definition.
44 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
45 * **container_working_dir** (*str*) - (None) Container working directory definition.
46 * **container_user_id** (*str*) - (None) Container user_id definition.
47 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
49 Examples:
50 This is a use example of how to use the building block from Python::
52 from biobb_analysis.gromacs.gmx_energy import gmx_energy
53 prop = {
54 'xvg': 'xmgr',
55 'terms': ['Potential', 'Pressure']
56 }
57 gmx_energy(input_energy_path='/path/to/myEnergyFile.edr',
58 output_xvg_path='/path/to/newXVG.xvg',
59 properties=prop)
61 Info:
62 * wrapped_software:
63 * name: GROMACS energy
64 * version: >=2019.1
65 * license: LGPL 2.1
66 * ontology:
67 * name: EDAM
68 * schema: http://edamontology.org/EDAM.owl
70 """
72 def __init__(
73 self, input_energy_path, output_xvg_path, properties=None, **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": {"input_energy_path": input_energy_path},
84 "out": {"output_xvg_path": output_xvg_path},
85 }
87 # Properties specific for BB
88 self.xvg = properties.get("xvg", "none")
89 self.terms = _from_string_to_list(properties.get("terms", ["Potential"]))
90 self.instructions_file = get_default_value("instructions_file")
91 self.properties = properties
93 # Properties common in all GROMACS BB
94 self.binary_path = get_binary_path(properties, "binary_path")
96 # Check the properties
97 self.check_properties(properties)
98 self.check_arguments()
100 def check_data_params(self, out_log, err_log):
101 """Checks all the input/output paths and parameters"""
102 self.io_dict["in"]["input_energy_path"] = check_energy_path(
103 self.io_dict["in"]["input_energy_path"], out_log, self.__class__.__name__
104 )
105 self.io_dict["out"]["output_xvg_path"] = check_out_xvg_path(
106 self.io_dict["out"]["output_xvg_path"], out_log, self.__class__.__name__
107 )
108 self.xvg = get_xvg(self.properties, out_log, self.__class__.__name__)
109 self.terms = get_terms(self.properties, out_log, self.__class__.__name__)
111 def create_instructions_file(self):
112 """Creates an input file using the properties file settings"""
113 instructions_list = []
114 # different path if container execution or not
115 if self.container_path:
116 self.instructions_file = str(
117 PurePath(self.container_volume_path).joinpath(self.instructions_file)
118 )
119 else:
120 self.instructions_file = str(
121 PurePath(fu.create_unique_dir()).joinpath(self.instructions_file)
122 )
123 # self.instructions_file = str(PurePath(fu.create_unique_dir()).joinpath(self.instructions_file))
124 fu.create_name(prefix=self.prefix, step=self.step, name=self.instructions_file)
126 for t in self.terms:
127 instructions_list.append(t)
129 # create instructions file
130 with open(self.instructions_file, "w") as mdp:
131 for line in instructions_list:
132 mdp.write(line.strip() + "\n")
134 return self.instructions_file
136 @launchlogger
137 def launch(self) -> int:
138 """Execute the :class:`GMXEnergy <gromacs.gmx_energy.GMXEnergy>` gromacs.gmx_energy.GMXEnergy object."""
140 # check input/output paths and parameters
141 self.check_data_params(self.out_log, self.err_log)
143 # Setup Biobb
144 if self.check_restart():
145 return 0
146 self.stage_files()
148 # create instructions file
149 self.create_instructions_file()
151 # if container execution, copy intructions file to container
152 if self.container_path:
153 copy_instructions_file_to_container(
154 self.instructions_file, self.stage_io_dict.get("unique_dir")
155 )
157 self.cmd = [
158 self.binary_path,
159 "energy",
160 "-f",
161 self.stage_io_dict["in"]["input_energy_path"],
162 "-o",
163 self.stage_io_dict["out"]["output_xvg_path"],
164 "-xvg",
165 self.xvg,
166 "<",
167 self.instructions_file,
168 ]
170 # Run Biobb block
171 self.run_biobb()
173 # Copy files to host
174 self.copy_to_host()
176 self.tmp_files.extend(
177 [
178 self.stage_io_dict.get("unique_dir", ""),
179 str(str(PurePath(self.instructions_file).parent)),
180 ]
181 )
182 self.remove_tmp_files()
184 self.check_arguments(output_files_created=True, raise_exception=False)
186 return self.return_code
189def gmx_energy(
190 input_energy_path: str,
191 output_xvg_path: str,
192 properties: Optional[dict] = None,
193 **kwargs,
194) -> int:
195 """Execute the :class:`GMXEnergy <gromacs.gmx_energy.GMXEnergy>` class and
196 execute the :meth:`launch() <gromacs.gmx_energy.GMXEnergy.launch>` method."""
198 return GMXEnergy(
199 input_energy_path=input_energy_path,
200 output_xvg_path=output_xvg_path,
201 properties=properties,
202 **kwargs,
203 ).launch()
206def main():
207 """Command line execution of this building block. Please check the command line documentation."""
208 parser = argparse.ArgumentParser(
209 description="Extracts energy components from a given GROMACS energy file.",
210 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999),
211 )
212 parser.add_argument("--config", required=False, help="Configuration file")
214 # Specific args of each building block
215 required_args = parser.add_argument_group("required arguments")
216 required_args.add_argument(
217 "--input_energy_path",
218 required=True,
219 help="Path to the input EDR file. Accepted formats: edr.",
220 )
221 required_args.add_argument(
222 "--output_xvg_path",
223 required=True,
224 help="Path to the XVG output file. Accepted formats: xvg.",
225 )
227 args = parser.parse_args()
228 args.config = args.config or "{}"
229 properties = settings.ConfReader(config=args.config).get_prop_dic()
231 # Specific call of each building block
232 gmx_energy(
233 input_energy_path=args.input_energy_path,
234 output_xvg_path=args.output_xvg_path,
235 properties=properties,
236 )
239if __name__ == "__main__":
240 main()