Coverage for biobb_gromacs/gromacs/convert_tpr.py: 80%

69 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-07-27 16:28 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the Convert_tpr class and the command line interface.""" 

4from pathlib import Path, PurePath 

5from typing import Optional 

6from biobb_common.generic.biobb_object import BiobbObject 

7from biobb_common.tools import file_utils as fu 

8from biobb_common.tools.file_utils import launchlogger 

9from biobb_gromacs.gromacs.common import get_gromacs_version 

10 

11 

12class ConvertTpr(BiobbObject): 

13 """ 

14 | biobb_gromacs ConvertTpr 

15 | Wrapper of the `GROMACS convert-tpr <https://manual.gromacs.org/current/onlinehelp/gmx-convert-tpr.html>`_ module. 

16 | The GROMACS convert-tpr module can edit run input files (.tpr): modify the run length (extend/until/nsteps) or trim the tpr file to a subset of atoms defined in an index file (input_ndx_path). Note that GROMACS does not allow both operations in a single call, so when an index file is provided the extend/until/nsteps properties are ignored. 

17 

18 Args: 

19 input_tpr_path (str): Path to the input portable binary run file TPR. File type: input. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/reference/gromacs/ref_grompp.tpr>`_. Accepted formats: tpr (edam:format_2333). 

20 output_tpr_path (str): Path to the output portable binary run file TPR. File type: output. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/reference/gromacs/ref_grompp.tpr>`_. Accepted formats: tpr (edam:format_2333). 

21 input_ndx_path (str) (Optional): Path to the input index NDX file, used to trim the tpr file to a subset of atoms. File type: input. Accepted formats: ndx (edam:format_2033). 

22 properties (dict - Python dictionary object containing the tool parameters, not input/output files): 

23 * **extend** (*int*) - (0) Extend the runtime by this amount (ps). 

24 * **until** (*int*) - (0) Extend the runtime until this ending time (ps). 

25 * **nsteps** (*int*) - (0) Change the number of steps remaining to be made. 

26 * **output_group** (*str*) - ("System") Index group to write to the output tpr file when trimming to a subset of atoms. Only used when input_ndx_path is provided. 

27 * **gmx_lib** (*str*) - (None) Path set GROMACS GMXLIB environment variable. 

28 * **binary_path** (*str*) - ("gmx") Path to the GROMACS executable binary. 

29 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files. 

30 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist. 

31 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

32 * **container_path** (*str*) - (None) Path to the binary executable of your container. 

33 * **container_image** (*str*) - ("gromacs/gromacs:latest") Container Image identifier. 

34 * **container_volume_path** (*str*) - ("/data") Path to an internal directory in the container. 

35 * **container_working_dir** (*str*) - (None) Path to the internal CWD in the container. 

36 * **container_user_id** (*str*) - (None) User number id to be mapped inside the container. 

37 * **container_shell_path** (*str*) - ("/bin/bash") Path to the binary executable of the container shell. 

38 

39 Examples: 

40 This is a use example of how to use the building block from Python:: 

41 

42 from biobb_gromacs.gromacs.convert_tpr import convert_tpr 

43 

44 prop = { 'extend': 100000} 

45 convert_tpr(input_tpr_path='/path/to/myStructure.tpr', 

46 output_tpr_path='/path/to/newCompiledBin.tpr', 

47 properties=prop) 

48 

49 # Trim the tpr file to a subset of atoms defined in an index file 

50 prop = { 'output_group': 'Protein'} 

51 convert_tpr(input_tpr_path='/path/to/myStructure.tpr', 

52 output_tpr_path='/path/to/trimmedBin.tpr', 

53 input_ndx_path='/path/to/myIndex.ndx', 

54 properties=prop) 

55 

56 Info: 

57 * wrapped_software: 

58 * name: GROMACS Convert-tpr 

59 * version: 2025.2 

60 * license: LGPL 2.1 

61 * ontology: 

62 * name: EDAM 

63 * schema: http://edamontology.org/EDAM.owl 

64 """ 

65 

66 def __init__(self, input_tpr_path: str, output_tpr_path: str, 

67 input_ndx_path: Optional[str] = None, 

68 properties: Optional[dict] = None, **kwargs) -> None: 

69 properties = properties or {} 

70 

71 # Call parent class constructor 

72 super().__init__(properties) 

73 self.locals_var_dict = locals().copy() 

74 

75 # Input/Output files 

76 self.io_dict = { 

77 "in": {"input_tpr_path": input_tpr_path, "input_ndx_path": input_ndx_path}, 

78 "out": {"output_tpr_path": output_tpr_path} 

79 } 

80 

81 # Properties specific for BB 

82 self.extend = properties.get('extend') 

83 self.until = properties.get('until') 

84 self.nsteps = properties.get('nsteps') 

85 self.output_group = properties.get('output_group', 'System') 

86 

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 += ' -nobackup' 

94 if self.gmx_nocopyright: 

95 self.binary_path += ' -nocopyright' 

96 if not self.container_path: 

97 self.gmx_version = get_gromacs_version(self.binary_path) 

98 

99 # Check the properties 

100 self.check_properties(properties) 

101 self.check_arguments() 

102 

103 @launchlogger 

104 def launch(self) -> int: 

105 """Execute the :class:`ConvertTpr <gromacs.convert_tpr.ConvertTpr>` object.""" 

106 

107 # Setup Biobb 

108 if self.check_restart(): 

109 return 0 

110 

111 # When trimming to a subset (an index file is provided), GROMACS 

112 # convert-tpr prompts for the output group; answer it via stdin. 

113 if self.io_dict["in"].get("input_ndx_path"): 

114 self.io_dict["in"]["stdin_file_path"] = fu.create_stdin_file(f"{self.output_group}") 

115 

116 self.stage_files() 

117 

118 if self.container_path: 

119 working_dir = self.container_volume_path if self.container_volume_path else "/data" 

120 else: 

121 working_dir = self.stage_io_dict.get('unique_dir', '') 

122 

123 self.cmd = ["cd", working_dir, ";", self.binary_path, 'convert-tpr', 

124 '-s', PurePath(self.stage_io_dict["in"]["input_tpr_path"]).name, 

125 '-o', PurePath(self.stage_io_dict["out"]["output_tpr_path"]).name 

126 ] 

127 

128 trimming = bool(self.stage_io_dict["in"].get("input_ndx_path")) and \ 

129 Path(self.stage_io_dict["in"].get("input_ndx_path")).exists() 

130 

131 if trimming: 

132 # Trim the tpr to the selected index group. GROMACS does not allow 

133 # combining index-group extraction with runtime modification 

134 # (-extend/-until/-nsteps) in a single convert-tpr call. 

135 self.cmd.append('-n') 

136 self.cmd.append(PurePath(self.stage_io_dict["in"].get("input_ndx_path")).name) 

137 if self.extend or self.until or self.nsteps: 

138 fu.log("Warning: extend, until and nsteps are ignored when trimming the tpr " 

139 "file to an index group; GROMACS convert-tpr cannot do both in a single call.", 

140 self.out_log, self.global_log) 

141 else: 

142 if self.extend: 

143 self.cmd.extend(['-extend', str(self.extend)]) 

144 if self.until: 

145 self.cmd.extend(['-until', str(self.until)]) 

146 if self.nsteps: 

147 self.cmd.extend(['-nsteps', str(self.nsteps)]) 

148 

149 # Add stdin input file to answer the output group prompt when trimming 

150 if self.io_dict["in"].get("stdin_file_path"): 

151 self.cmd.append('<') 

152 self.cmd.append(PurePath(self.stage_io_dict["in"]["stdin_file_path"]).name) 

153 

154 if self.gmx_lib: 

155 self.env_vars_dict['GMXLIB'] = self.gmx_lib 

156 

157 # Run Biobb block 

158 self.run_biobb() 

159 

160 # Copy files to host 

161 self.copy_to_host() 

162 

163 if self.io_dict["in"].get("stdin_file_path"): 

164 self.tmp_files.append(str(self.io_dict["in"].get("stdin_file_path"))) 

165 self.remove_tmp_files() 

166 

167 self.check_arguments(output_files_created=True, raise_exception=False) 

168 return self.return_code 

169 

170 

171def convert_tpr(input_tpr_path: str, output_tpr_path: str, input_ndx_path: Optional[str] = None, 

172 properties: Optional[dict] = None, **kwargs) -> int: 

173 """Create :class:`ConvertTpr <gromacs.convert_tpr.ConvertTpr>` class and 

174 execute the :meth:`launch() <gromacs.convert_tpr.ConvertTpr.launch>` method.""" 

175 return ConvertTpr(**dict(locals())).launch() 

176 

177 

178convert_tpr.__doc__ = ConvertTpr.__doc__ 

179main = ConvertTpr.get_main( 

180 convert_tpr, "Wrapper of the GROMACS convert-tpr module.") 

181 

182 

183if __name__ == '__main__': 

184 main()