Coverage for biobb_analysis/gromacs/gmx_energy.py: 94%
52 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-08 10:47 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-08 10:47 +0000
1#!/usr/bin/env python3
3"""Module containing the GMX Energy class and the command line interface."""
5from pathlib import PurePath
6from typing import Optional
7from biobb_common.generic.biobb_object import BiobbObject
8from biobb_common.tools.file_utils import launchlogger
10from biobb_analysis.gromacs.common import (
11 _from_string_to_list,
12 check_energy_path,
13 check_out_xvg_path,
14 get_binary_path,
15 get_default_value,
16 get_terms,
17 get_xvg,
18)
21class GMXEnergy(BiobbObject):
22 """
23 | biobb_analysis GMXEnergy
24 | Wrapper of the GROMACS energy module for extracting energy components from a given GROMACS energy file.
25 | `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.
27 Args:
28 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).
29 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).
30 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
31 * **xvg** (*str*) - ("none") XVG plot formatting. Values: xmgrace, xmgr, none.
32 * **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.
33 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
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) Container path definition.
38 * **container_image** (*str*) - ('gromacs/gromacs:2022.2') Container image definition.
39 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
40 * **container_working_dir** (*str*) - (None) Container working directory definition.
41 * **container_user_id** (*str*) - (None) Container user_id definition.
42 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
44 Examples:
45 This is a use example of how to use the building block from Python::
47 from biobb_analysis.gromacs.gmx_energy import gmx_energy
48 prop = {
49 'xvg': 'xmgr',
50 'terms': ['Potential', 'Pressure']
51 }
52 gmx_energy(input_energy_path='/path/to/myEnergyFile.edr',
53 output_xvg_path='/path/to/newXVG.xvg',
54 properties=prop)
56 Info:
57 * wrapped_software:
58 * name: GROMACS energy
59 * version: >=2024.5
60 * license: LGPL 2.1
61 * ontology:
62 * name: EDAM
63 * schema: http://edamontology.org/EDAM.owl
65 """
67 def __init__(
68 self, input_energy_path, output_xvg_path, properties=None, **kwargs
69 ) -> None:
70 properties = properties or {}
72 # Call parent class constructor
73 super().__init__(properties)
74 self.locals_var_dict = locals().copy()
76 # Input/Output files
77 self.io_dict = {
78 "in": {"input_energy_path": input_energy_path},
79 "out": {"output_xvg_path": output_xvg_path},
80 }
82 # Properties specific for BB
83 self.xvg = properties.get("xvg", "none")
84 self.terms = _from_string_to_list(properties.get("terms", ["Potential"]))
85 self.instructions_file = get_default_value("instructions_file")
86 self.properties = properties
88 # Properties common in all GROMACS BB
89 self.binary_path = get_binary_path(properties, "binary_path")
91 # Check the properties
92 self.check_init(properties)
94 def check_data_params(self, out_log, err_log):
95 """Checks all the input/output paths and parameters"""
96 self.io_dict["in"]["input_energy_path"] = check_energy_path(
97 self.io_dict["in"]["input_energy_path"], out_log, self.__class__.__name__
98 )
99 self.io_dict["out"]["output_xvg_path"] = check_out_xvg_path(
100 self.io_dict["out"]["output_xvg_path"], out_log, self.__class__.__name__
101 )
102 self.xvg = get_xvg(self.properties, out_log, self.__class__.__name__)
103 self.terms = get_terms(self.properties, out_log, self.__class__.__name__)
105 def create_instructions_file(self):
106 """Creates an input file using the properties file settings"""
107 instructions_list = []
108 # Different path if container execution or not
109 if self.container_path:
110 self.instructions_file = str(PurePath(self.container_volume_path).joinpath(self.instructions_file))
111 else:
112 self.instructions_file = self.create_tmp_file(self.instructions_file)
114 for t in self.terms:
115 instructions_list.append(t)
117 # create instructions file
118 with open(self.instructions_file, "w") as mdp:
119 for line in instructions_list:
120 mdp.write(line.strip() + "\n")
122 return self.instructions_file
124 @launchlogger
125 def launch(self) -> int:
126 """Execute the :class:`GMXEnergy <gromacs.gmx_energy.GMXEnergy>` object."""
128 # check input/output paths and parameters
129 self.check_data_params(self.out_log, self.err_log)
131 # Setup Biobb
132 if self.check_restart():
133 return 0
134 self.stage_files()
136 # create instructions file
137 self.create_instructions_file()
139 self.cmd = [
140 self.binary_path,
141 "energy",
142 "-f",
143 self.stage_io_dict["in"]["input_energy_path"],
144 "-o",
145 self.stage_io_dict["out"]["output_xvg_path"],
146 "-xvg",
147 self.xvg,
148 "<",
149 self.instructions_file,
150 ]
152 # Run Biobb block
153 self.run_biobb()
154 # Copy files to host
155 self.copy_to_host()
156 self.remove_tmp_files()
157 self.check_arguments(output_files_created=True, raise_exception=False)
159 return self.return_code
162def gmx_energy(
163 input_energy_path: str,
164 output_xvg_path: str,
165 properties: Optional[dict] = None,
166 **kwargs,
167) -> int:
168 """Execute the :class:`GMXEnergy <gromacs.gmx_energy.GMXEnergy>` class and
169 execute the :meth:`launch() <gromacs.gmx_energy.GMXEnergy.launch>` method."""
170 return GMXEnergy(**dict(locals())).launch()
173gmx_energy.__doc__ = GMXEnergy.__doc__
174main = GMXEnergy.get_main(gmx_energy, "Extracts energy components from a given GROMACS energy file.")
176if __name__ == "__main__":
177 main()