Coverage for biobb_analysis / gromacs / gmx_energy.py: 93%
54 statements
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-12 10:53 +0000
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-12 10:53 +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.stage_io_dict['unique_dir']).joinpath("instructions.in"))
111 self.instructions_file_path = str(PurePath(self.container_volume_path).joinpath("instructions.in"))
112 else:
113 self.instructions_file = self.create_tmp_file(self.instructions_file)
114 self.instructions_file_path = self.instructions_file
116 for t in self.terms:
117 instructions_list.append(t)
119 # create instructions file
120 with open(self.instructions_file, "w") as mdp:
121 for line in instructions_list:
122 mdp.write(line.strip() + "\n")
124 return self.instructions_file_path
126 @launchlogger
127 def launch(self) -> int:
128 """Execute the :class:`GMXEnergy <gromacs.gmx_energy.GMXEnergy>` object."""
130 # check input/output paths and parameters
131 self.check_data_params(self.out_log, self.err_log)
133 # Setup Biobb
134 if self.check_restart():
135 return 0
136 self.stage_files()
138 # create instructions file
139 self.create_instructions_file()
141 self.cmd = [
142 self.binary_path,
143 "energy",
144 "-f",
145 self.stage_io_dict["in"]["input_energy_path"],
146 "-o",
147 self.stage_io_dict["out"]["output_xvg_path"],
148 "-xvg",
149 self.xvg,
150 "<",
151 self.instructions_file_path,
152 ]
154 # Run Biobb block
155 self.run_biobb()
156 # Copy files to host
157 self.copy_to_host()
158 self.remove_tmp_files()
159 self.check_arguments(output_files_created=True, raise_exception=False)
161 return self.return_code
164def gmx_energy(
165 input_energy_path: str,
166 output_xvg_path: str,
167 properties: Optional[dict] = None,
168 **kwargs,
169) -> int:
170 """Create the :class:`GMXEnergy <gromacs.gmx_energy.GMXEnergy>` class and
171 execute the :meth:`launch() <gromacs.gmx_energy.GMXEnergy.launch>` method."""
172 return GMXEnergy(**dict(locals())).launch()
175gmx_energy.__doc__ = GMXEnergy.__doc__
176main = GMXEnergy.get_main(gmx_energy, "Extracts energy components from a given GROMACS energy file.")
178if __name__ == "__main__":
179 main()