Coverage for biobb_gromacs/gromacs/genrestr.py: 79%
68 statements
« prev ^ index » next coverage.py v7.10.4, created at 2025-10-21 09:54 +0000
« prev ^ index » next coverage.py v7.10.4, created at 2025-10-21 09:54 +0000
1#!/usr/bin/env python3
3"""Module containing the Genrestr class and the command line interface."""
5import argparse
6from pathlib import Path
7from typing import Optional, Union
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_gromacs.gromacs.common import get_gromacs_version
17class Genrestr(BiobbObject):
18 """
19 | biobb_gromacs Genrestr
20 | Wrapper of the `GROMACS genrestr <http://manual.gromacs.org/current/onlinehelp/gmx-genrestr.html>`_ module.
21 | 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.
23 Args:
24 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).
25 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).
26 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).
27 properties (dict - Python dictionary object containing the tool parameters, not input/output files):
28 * **restrained_group** (*str*) - ("system") Index group that will be restrained.
29 * **force_constants** (*str*) - ("500 500 500") Array of three floats defining the force constants
30 * **gmx_lib** (*str*) - (None) Path set GROMACS GMXLIB environment variable.
31 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
32 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
33 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
34 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
35 * **container_path** (*str*) - (None) Path to the binary executable of your container.
36 * **container_image** (*str*) - ("gromacs/gromacs:latest") Container Image identifier.
37 * **container_volume_path** (*str*) - ("/data") Path to an internal directory in the container.
38 * **container_working_dir** (*str*) - (None) Path to the internal CWD in the container.
39 * **container_user_id** (*str*) - (None) User number id to be mapped inside the container.
40 * **container_shell_path** (*str*) - ("/bin/bash") Path to the binary executable of the container shell.
42 Examples:
43 This is a use example of how to use the building block from Python::
45 from biobb_gromacs.gromacs.genrestr import genrestr
46 prop = { 'restrained_group': 'system',
47 'force_constants': '500 500 500' }
48 genrestr(input_structure_path='/path/to/myStructure.gro',
49 output_itp_path='/path/to/newTopologyAddOn.itp',
50 properties=prop)
52 Info:
53 * wrapped_software:
54 * name: GROMACS Genrestr
55 * version: 2025.2
56 * license: LGPL 2.1
57 * ontology:
58 * name: EDAM
59 * schema: http://edamontology.org/EDAM.owl
60 """
62 def __init__(
63 self,
64 input_structure_path: Union[str, Path],
65 output_itp_path: Union[str, Path],
66 input_ndx_path: Optional[Union[str, Path]] = None,
67 properties: Optional[dict] = None,
68 **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": {
79 "input_structure_path": input_structure_path,
80 "input_ndx_path": input_ndx_path,
81 },
82 "out": {"output_itp_path": output_itp_path},
83 }
85 # Properties specific for BB
86 self.force_constants = str(properties.get("force_constants", "500 500 500"))
87 self.restrained_group = properties.get("restrained_group", "system")
89 # Properties common in all GROMACS BB
90 self.gmx_lib = properties.get("gmx_lib", None)
91 self.binary_path = properties.get("binary_path", "gmx")
92 self.gmx_nobackup = properties.get("gmx_nobackup", True)
93 self.gmx_nocopyright = properties.get("gmx_nocopyright", True)
94 if self.gmx_nobackup:
95 self.binary_path = f"{self.binary_path} -nobackup"
96 if self.gmx_nocopyright:
97 self.binary_path = f"{self.binary_path} -nocopyright"
98 if not self.container_path:
99 self.gmx_version = get_gromacs_version(str(self.binary_path))
101 # Check the properties
102 self.check_properties(properties)
103 self.check_arguments()
105 @launchlogger
106 def launch(self) -> int:
107 """Execute the :class:`Grompp <gromacs.grompp.Grompp>` object."""
109 # Setup Biobb
110 if self.check_restart():
111 return 0
113 self.io_dict["in"]["stdin_file_path"] = fu.create_stdin_file(f"{self.restrained_group}")
114 self.stage_files()
116 self.cmd = [
117 str(self.binary_path),
118 "genrestr",
119 "-f",
120 self.stage_io_dict["in"]["input_structure_path"],
121 "-o",
122 self.stage_io_dict["out"]["output_itp_path"],
123 ]
125 if not isinstance(self.force_constants, str):
126 self.force_constants = " ".join(map(str, self.force_constants))
128 self.cmd.append("-fc")
129 self.cmd.append(self.force_constants)
131 if self.stage_io_dict["in"].get("input_ndx_path"):
132 self.cmd.append("-n")
133 self.cmd.append(self.stage_io_dict["in"]["input_ndx_path"])
135 # Add stdin input file
136 self.cmd.append("<")
137 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"])
139 if self.gmx_lib:
140 self.env_vars_dict["GMXLIB"] = self.gmx_lib
142 # Run Biobb block
143 self.run_biobb()
145 # Copy files to host
146 self.copy_to_host()
148 # Remove temporal files
149 self.tmp_files.extend(
150 [
151 str(self.io_dict["in"].get("stdin_file_path")),
152 ]
153 )
154 self.remove_tmp_files()
156 self.check_arguments(output_files_created=True, raise_exception=False)
157 return self.return_code
160def genrestr(
161 input_structure_path: Union[str, Path],
162 output_itp_path: Union[str, Path],
163 input_ndx_path: Optional[Union[str, Path]] = None,
164 properties: Optional[dict] = None,
165 **kwargs,
166) -> int:
167 """Create :class:`Genrestr <gromacs.genrestr.Genrestr>` class and
168 execute the :meth:`launch() <gromacs.genrestr.Genrestr.launch>` method."""
170 return Genrestr(
171 input_structure_path=input_structure_path,
172 output_itp_path=output_itp_path,
173 input_ndx_path=input_ndx_path,
174 properties=properties,
175 **kwargs,
176 ).launch()
179genrestr.__doc__ = Genrestr.__doc__
182def main():
183 """Command line execution of this building block. Please check the command line documentation."""
184 parser = argparse.ArgumentParser(
185 description="Wrapper for the GROMACS genion module.",
186 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999),
187 )
188 parser.add_argument(
189 "-c",
190 "--config",
191 required=False,
192 help="This file can be a YAML file, JSON file or JSON string",
193 )
195 # Specific args of each building block
196 required_args = parser.add_argument_group("required arguments")
197 required_args.add_argument("--input_structure_path", required=True)
198 required_args.add_argument("--output_itp_path", required=True)
199 parser.add_argument("--input_ndx_path", required=False)
201 args = parser.parse_args()
202 config = args.config if args.config else None
203 properties = settings.ConfReader(config=config).get_prop_dic()
205 # Specific call of each building block
206 genrestr(
207 input_structure_path=args.input_structure_path,
208 input_ndx_path=args.input_ndx_path,
209 output_itp_path=args.output_itp_path,
210 properties=properties,
211 )
214if __name__ == "__main__":
215 main()