Coverage for biobb_gromacs / gromacs / genrestr.py: 93%
56 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-03-05 08:26 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-03-05 08:26 +0000
1#!/usr/bin/env python3
3"""Module containing the Genrestr class and the command line interface."""
5from pathlib import Path
6from typing import Optional, Union
8from biobb_common.generic.biobb_object import BiobbObject
9from biobb_common.tools import file_utils as fu
10from biobb_common.tools.file_utils import launchlogger
12from biobb_gromacs.gromacs.common import get_gromacs_version
15class Genrestr(BiobbObject):
16 """
17 | biobb_gromacs Genrestr
18 | Wrapper of the `GROMACS genrestr <http://manual.gromacs.org/current/onlinehelp/gmx-genrestr.html>`_ module.
19 | The GROMACS genrestr module, produces an #include file for a topology containing a list of atom numbers and three force constants for the x-, y-, and z-direction based on the contents of the -f file. A single isotropic force constant may be given on the command line instead of three components.
21 Args:
22 input_structure_path (str): Path to the input structure PDB, GRO or TPR format. File type: input. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/data/gromacs/genrestr.gro>`_. Accepted formats: pdb (edam:format_1476), gro (edam:format_2033), tpr (edam:format_2333).
23 output_itp_path (str): Path the output ITP topology file with restrains. File type: output. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/reference/gromacs/ref_genrestr.itp>`_. Accepted formats: itp (edam:format_3883).
24 input_ndx_path (str) (Optional): Path to the input GROMACS index file, NDX format. File type: input. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/data/gromacs/genrestr.ndx>`_. Accepted formats: ndx (edam:format_2033).
25 properties (dict - Python dictionary object containing the tool parameters, not input/output files):
26 * **restrained_group** (*str*) - ("system") Index group that will be restrained.
27 * **force_constants** (*str*) - ("500 500 500") Array of three floats defining the force constants
28 * **gmx_lib** (*str*) - (None) Path set GROMACS GMXLIB environment variable.
29 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
30 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
31 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
32 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
33 * **container_path** (*str*) - (None) Path to the binary executable of your container.
34 * **container_image** (*str*) - ("gromacs/gromacs:latest") Container Image identifier.
35 * **container_volume_path** (*str*) - ("/data") Path to an internal directory in the container.
36 * **container_working_dir** (*str*) - (None) Path to the internal CWD in the container.
37 * **container_user_id** (*str*) - (None) User number id to be mapped inside the container.
38 * **container_shell_path** (*str*) - ("/bin/bash") Path to the binary executable of the container shell.
40 Examples:
41 This is a use example of how to use the building block from Python::
43 from biobb_gromacs.gromacs.genrestr import genrestr
44 prop = { 'restrained_group': 'system',
45 'force_constants': '500 500 500' }
46 genrestr(input_structure_path='/path/to/myStructure.gro',
47 output_itp_path='/path/to/newTopologyAddOn.itp',
48 properties=prop)
50 Info:
51 * wrapped_software:
52 * name: GROMACS Genrestr
53 * version: 2025.2
54 * license: LGPL 2.1
55 * ontology:
56 * name: EDAM
57 * schema: http://edamontology.org/EDAM.owl
58 """
60 def __init__(
61 self,
62 input_structure_path: Union[str, Path],
63 output_itp_path: Union[str, Path],
64 input_ndx_path: Optional[Union[str, Path]] = None,
65 properties: Optional[dict] = None,
66 **kwargs,
67 ) -> None:
68 properties = properties or {}
70 # Call parent class constructor
71 super().__init__(properties)
72 self.locals_var_dict = locals().copy()
74 # Input/Output files
75 self.io_dict = {
76 "in": {
77 "input_structure_path": input_structure_path,
78 "input_ndx_path": input_ndx_path,
79 },
80 "out": {"output_itp_path": output_itp_path},
81 }
83 # Properties specific for BB
84 self.force_constants = str(properties.get("force_constants", "500 500 500"))
85 self.restrained_group = properties.get("restrained_group", "system")
87 # Properties common in all GROMACS BB
88 self.gmx_lib = properties.get("gmx_lib", None)
89 self.binary_path = properties.get("binary_path", "gmx")
90 self.gmx_nobackup = properties.get("gmx_nobackup", True)
91 self.gmx_nocopyright = properties.get("gmx_nocopyright", True)
92 if self.gmx_nobackup:
93 self.binary_path = f"{self.binary_path} -nobackup"
94 if self.gmx_nocopyright:
95 self.binary_path = f"{self.binary_path} -nocopyright"
96 if not self.container_path:
97 self.gmx_version = get_gromacs_version(str(self.binary_path))
99 # Check the properties
100 self.check_properties(properties)
101 self.check_arguments()
103 @launchlogger
104 def launch(self) -> int:
105 """Execute the :class:`Grompp <gromacs.grompp.Grompp>` object."""
107 # Setup Biobb
108 if self.check_restart():
109 return 0
111 self.io_dict["in"]["stdin_file_path"] = fu.create_stdin_file(f"{self.restrained_group}")
112 self.stage_files()
114 self.cmd = [
115 str(self.binary_path),
116 "genrestr",
117 "-f",
118 self.stage_io_dict["in"]["input_structure_path"],
119 "-o",
120 self.stage_io_dict["out"]["output_itp_path"],
121 ]
123 if not isinstance(self.force_constants, str):
124 self.force_constants = " ".join(map(str, self.force_constants))
126 self.cmd.append("-fc")
127 self.cmd.append(self.force_constants)
129 if self.stage_io_dict["in"].get("input_ndx_path"):
130 self.cmd.append("-n")
131 self.cmd.append(self.stage_io_dict["in"]["input_ndx_path"])
133 # Add stdin input file
134 self.cmd.append("<")
135 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"])
137 if self.gmx_lib:
138 self.env_vars_dict["GMXLIB"] = self.gmx_lib
140 # Run Biobb block
141 self.run_biobb()
143 # Copy files to host
144 self.copy_to_host()
146 # Remove temporal files
147 self.tmp_files.append(str(self.io_dict["in"].get("stdin_file_path")))
148 self.remove_tmp_files()
150 self.check_arguments(output_files_created=True, raise_exception=False)
151 return self.return_code
154def genrestr(
155 input_structure_path: Union[str, Path],
156 output_itp_path: Union[str, Path],
157 input_ndx_path: Optional[Union[str, Path]] = None,
158 properties: Optional[dict] = None,
159 **kwargs,
160) -> int:
161 """Create :class:`Genrestr <gromacs.genrestr.Genrestr>` class and
162 execute the :meth:`launch() <gromacs.genrestr.Genrestr.launch>` method."""
163 return Genrestr(**dict(locals())).launch()
166genrestr.__doc__ = Genrestr.__doc__
167main = Genrestr.get_main(genrestr, "Wrapper for the GROMACS genrestr module.")
170if __name__ == "__main__":
171 main()