Coverage for biobb_gromacs/gromacs/make_ndx.py: 76%
63 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-25 09:23 +0000
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-25 09:23 +0000
1#!/usr/bin/env python3
3"""Module containing the MakeNdx class and the command line interface."""
4import argparse
5from typing import Optional
6from pathlib import Path
7from biobb_common.generic.biobb_object import BiobbObject
8from biobb_common.configuration import settings
9from biobb_common.tools import file_utils as fu
10from biobb_common.tools.file_utils import launchlogger
11from biobb_gromacs.gromacs.common import get_gromacs_version
14class MakeNdx(BiobbObject):
15 """
16 | biobb_gromacs MakeNdx
17 | Wrapper of the `GROMACS make_ndx <http://manual.gromacs.org/current/onlinehelp/gmx-make_ndx.html>`_ module.
18 | The GROMACS make_ndx module, generates an index file using the atoms of the selection.
20 Args:
21 input_structure_path (str): Path to the input GRO/PDB/TPR file. File type: input. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/data/gromacs/make_ndx.tpr>`_. Accepted formats: gro (edam:format_2033), pdb (edam:format_1476), tpr (edam:format_2333).
22 output_ndx_path (str): Path to the output index NDX file. File type: output. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/reference/gromacs/ref_make_ndx.ndx>`_. Accepted formats: ndx (edam:format_2033).
23 input_ndx_path (str) (Optional): Path to the input index NDX file. File type: input. Accepted formats: ndx (edam:format_2033).
24 properties (dict - Python dictionary object containing the tool parameters, not input/output files):
25 * **selection** (*str*) - ("a CA C N O") Heavy atoms. Atom selection string.
26 * **gmx_lib** (*str*) - (None) Path set GROMACS GMXLIB environment variable.
27 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary.
28 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
29 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
30 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
31 * **container_path** (*str*) - (None) Path to the binary executable of your container.
32 * **container_image** (*str*) - ("gromacs/gromacs:latest") Container Image identifier.
33 * **container_volume_path** (*str*) - ("/data") Path to an internal directory in the container.
34 * **container_working_dir** (*str*) - (None) Path to the internal CWD in the container.
35 * **container_user_id** (*str*) - (None) User number id to be mapped inside the container.
36 * **container_shell_path** (*str*) - ("/bin/bash") Path to the binary executable of the container shell.
38 Examples:
39 This is a use example of how to use the building block from Python::
41 from biobb_gromacs.gromacs.make_ndx import make_ndx
42 prop = { 'selection': 'a CA C N O' }
43 make_ndx(input_structure_path='/path/to/myStructure.gro',
44 output_ndx_path='/path/to/newIndex.ndx',
45 properties=prop)
47 Info:
48 * wrapped_software:
49 * name: GROMACS MakeNdx
50 * version: 2024.5
51 * license: LGPL 2.1
52 * ontology:
53 * name: EDAM
54 * schema: http://edamontology.org/EDAM.owl
55 """
57 def __init__(self, input_structure_path: str, output_ndx_path: str, input_ndx_path: Optional[str] = None,
58 properties: Optional[dict] = None, **kwargs) -> None:
59 properties = properties or {}
61 # Call parent class constructor
62 super().__init__(properties)
63 self.locals_var_dict = locals().copy()
65 # Input/Output files
66 self.io_dict = {
67 "in": {"input_structure_path": input_structure_path, "input_ndx_path": input_ndx_path},
68 "out": {"output_ndx_path": output_ndx_path}
69 }
71 # Properties specific for BB
72 self.binary_path = properties.get('binary_path', 'gmx')
73 self.selection = properties.get('selection', "a CA C N O")
75 # Properties common in all GROMACS BB
76 self.gmx_lib = properties.get('gmx_lib', None)
77 self.gmx_nobackup = properties.get('gmx_nobackup', True)
78 self.gmx_nocopyright = properties.get('gmx_nocopyright', True)
79 if self.gmx_nobackup:
80 self.binary_path += ' -nobackup'
81 if self.gmx_nocopyright:
82 self.binary_path += ' -nocopyright'
83 if not self.container_path:
84 self.gmx_version = get_gromacs_version(self.binary_path)
86 # Check the properties
87 self.check_properties(properties)
88 self.check_arguments()
90 @launchlogger
91 def launch(self) -> int:
92 """Execute the :class:`MakeNdx <gromacs.make_ndx.MakeNdx>` object."""
94 # Setup Biobb
95 if self.check_restart():
96 return 0
98 self.io_dict['in']['stdin_file_path'] = fu.create_stdin_file(f'{self.selection}\nq\n')
99 self.stage_files()
101 # Create command line
102 self.cmd = [self.binary_path, 'make_ndx',
103 '-f', self.stage_io_dict["in"]["input_structure_path"],
104 '-o', self.stage_io_dict["out"]["output_ndx_path"]]
106 if self.stage_io_dict["in"].get("input_ndx_path")\
107 and Path(self.stage_io_dict["in"].get("input_ndx_path")).exists():
108 self.cmd.append('-n')
109 self.cmd.append(self.stage_io_dict["in"].get("input_ndx_path"))
111 # Add stdin input file
112 self.cmd.append('<')
113 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"])
115 if self.gmx_lib:
116 self.env_vars_dict['GMXLIB'] = self.gmx_lib
118 # create_cmd_line and execute_command
119 self.run_biobb()
121 # Retrieve results
122 self.copy_to_host()
124 # Remove temporal files
125 self.tmp_files.extend([
126 # self.stage_io_dict.get("unique_dir", ""),
127 self.io_dict['in'].get("stdin_file_path", '')
128 ])
129 self.remove_tmp_files()
131 self.check_arguments(output_files_created=True, raise_exception=False)
132 return self.return_code
135def make_ndx(input_structure_path: str, output_ndx_path: str,
136 input_ndx_path: Optional[str] = None, properties: Optional[dict] = None, **kwargs) -> int:
137 """Create :class:`MakeNdx <gromacs.make_ndx.MakeNdx>` class and
138 execute the :meth:`launch() <gromacs.make_ndx.MakeNdx.launch>` method."""
139 return MakeNdx(input_structure_path=input_structure_path,
140 output_ndx_path=output_ndx_path,
141 input_ndx_path=input_ndx_path,
142 properties=properties, **kwargs).launch()
145make_ndx.__doc__ = MakeNdx.__doc__
148def main():
149 """Command line execution of this building block. Please check the command line documentation."""
150 parser = argparse.ArgumentParser(description="Wrapper for the GROMACS make_ndx module.",
151 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
152 parser.add_argument('-c', '--config', required=False, help="This file can be a YAML file, JSON file or JSON string")
154 # Specific args of each building block
155 required_args = parser.add_argument_group('required arguments')
156 required_args.add_argument('--input_structure_path', required=True)
157 required_args.add_argument('--output_ndx_path', required=True)
158 parser.add_argument('--input_ndx_path', required=False)
160 args = parser.parse_args()
161 config = args.config if args.config else None
162 properties = settings.ConfReader(config=config).get_prop_dic()
164 # Specific call of each building block
165 make_ndx(input_structure_path=args.input_structure_path,
166 output_ndx_path=args.output_ndx_path,
167 input_ndx_path=args.input_ndx_path,
168 properties=properties)
171if __name__ == '__main__':
172 main()