Coverage for biobb_analysis/gromacs/gmx_trjconv_trj.py: 72%

78 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-14 14:38 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the GMX TrjConvStr class and the command line interface.""" 

4import argparse 

5from typing import Optional 

6from biobb_common.generic.biobb_object import BiobbObject 

7from biobb_common.configuration import settings 

8from biobb_common.tools.file_utils import launchlogger 

9import biobb_common.tools.file_utils as fu 

10import biobb_analysis.gromacs.common as gro_common 

11 

12 

13class GMXTrjConvTrj(BiobbObject): 

14 """ 

15 | biobb_analysis GMXTrjConvTrj 

16 | Wrapper of the GROMACS trjconv module for converting between GROMACS compatible trajectory file formats and/or extracts a selection of atoms. 

17 | GROMACS trjconv module can convert trajectory files in many ways. See the `GROMACS trjconv <http://manual.gromacs.org/documentation/2018/onlinehelp/gmx-trjconv.html>`_ official documentation for further information. 

18 

19 Args: 

20 input_traj_path (str): Path to the GROMACS trajectory file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/gromacs/trajectory.trr>`_. Accepted formats: xtc (edam:format_3875), trr (edam:format_3910), cpt (edam:format_2333), gro (edam:format_2033), g96 (edam:format_2033), pdb (edam:format_1476), tng (edam:format_3876). 

21 input_top_path (str) (Optional): Path to the GROMACS input topology file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/gromacs/topology.tpr>`_. Accepted formats: tpr (edam:format_2333), gro (edam:format_2033), g96 (edam:format_2033), pdb (edam:format_1476), brk (edam:format_2033), ent (edam:format_1476). 

22 input_index_path (str) (Optional): Path to the GROMACS index file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/gromacs/index.ndx>`_. Accepted formats: ndx (edam:format_2033). 

23 output_traj_path (str): Path to the output file. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/gromacs/ref_trjconv.trj.xtc>`_. Accepted formats: xtc (edam:format_3875), trr (edam:format_3910), cpt (edam:format_2333), gro (edam:format_2033), g96 (edam:format_2033), pdb (edam:format_1476), tng (edam:format_3876). 

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

25 * **selection** (*str*) - ("System") Group where the trjconv will be performed. If **input_index_path** provided, check the file for the accepted values. Values: System (all atoms in the system), Protein (all protein atoms), Protein-H (protein atoms excluding hydrogens), C-alpha (C-alpha atoms), Backbone (protein backbone atoms: N; C-alpha and C), MainChain (protein main chain atoms: N; C-alpha; C and O; including oxygens in C-terminus), MainChain+Cb (protein main chain atoms including C-beta), MainChain+H (protein main chain atoms including backbone amide hydrogens and hydrogens on the N-terminus), SideChain (protein side chain atoms: that is all atoms except N; C-alpha; C; O; backbone amide hydrogens and oxygens in C-terminus and hydrogens on the N-terminus), SideChain-H (protein side chain atoms excluding all hydrogens), Prot-Masses (protein atoms excluding dummy masses), non-Protein (all non-protein atoms), Water (water molecules), SOL (water molecules), non-Water (anything not covered by the Water group), Ion (any name matching an Ion entry in residuetypes.dat), NA (all NA atoms), CL (all CL atoms), Water_and_ions (combination of the Water and Ions groups), DNA (all DNA atoms), RNA (all RNA atoms), Protein_DNA (all Protein-DNA complex atoms), Protein_RNA (all Protein-RNA complex atoms), Protein_DNA_RNA (all Protein-DNA-RNA complex atoms), DNA_RNA (all DNA-RNA complex atoms). 

26 * **start** (*int*) - (0) [0~10000|1] Time of first frame to read from trajectory (default unit ps). 

27 * **end** (*int*) - (0) [0~10000|1] Time of last frame to read from trajectory (default unit ps). 

28 * **dt** (*int*) - (0) [0~10000|1] Only write frame when t MOD dt = first time (ps). 

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) Container path definition. 

34 * **container_image** (*str*) - ('gromacs/gromacs:2022.2') Container image definition. 

35 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition. 

36 * **container_working_dir** (*str*) - (None) Container working directory definition. 

37 * **container_user_id** (*str*) - (None) Container user_id definition. 

38 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container. 

39 

40 Examples: 

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

42 

43 from biobb_analysis.gromacs.gmx_trjconv_trj import gmx_trjconv_trj 

44 prop = { 

45 'selection': 'System', 

46 'start': 0, 

47 'end': 0 

48 } 

49 gmx_trjconv_trj(input_traj_path='/path/to/myStructure.trr', 

50 output_traj_path='/path/to/newTrajectory.xtc', 

51 input_index_path='/path/to/myIndex.ndx', 

52 properties=prop) 

53 

54 Info: 

55 * wrapped_software: 

56 * name: GROMACS trjconv 

57 * version: >=2019.1 

58 * license: LGPL 2.1 

59 * ontology: 

60 * name: EDAM 

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

62 

63 """ 

64 

65 def __init__(self, input_traj_path, 

66 output_traj_path, input_index_path=None, input_top_path=None, properties=None, **kwargs) -> None: 

67 properties = properties or {} 

68 

69 # Call parent class constructor 

70 super().__init__(properties) 

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

72 

73 # Input/Output files 

74 self.io_dict = { 

75 "in": {"input_traj_path": input_traj_path, "input_index_path": input_index_path, "input_top_path": input_top_path}, 

76 "out": {"output_traj_path": output_traj_path} 

77 } 

78 

79 # Properties specific for BB 

80 if not self.io_dict["in"]["input_index_path"] and not self.io_dict["in"]["input_top_path"]: 

81 self.selection = properties.get('selection', "") 

82 else: 

83 self.selection = properties.get('selection', "System") 

84 self.start = properties.get('start', 0) 

85 self.end = properties.get('end', 0) 

86 self.dt = properties.get('dt', 0) 

87 self.properties = properties 

88 

89 # Properties common in all GROMACS BB 

90 self.binary_path = gro_common.get_binary_path(properties, 'binary_path') 

91 

92 # Check the properties 

93 self.check_properties(properties) 

94 self.check_arguments() 

95 

96 def check_data_params(self, out_log, err_log): 

97 """ Checks all the input/output paths and parameters """ 

98 self.io_dict["in"]["input_traj_path"] = gro_common.check_traj_path(self.io_dict["in"]["input_traj_path"], out_log, self.__class__.__name__) 

99 self.io_dict["in"]["input_index_path"] = gro_common.check_index_path(self.io_dict["in"]["input_index_path"], out_log, self.__class__.__name__) 

100 if self.io_dict["in"]["input_top_path"]: 

101 self.io_dict["in"]["input_top_path"] = gro_common.check_input_path(self.io_dict["in"]["input_top_path"], out_log, self.__class__.__name__) 

102 self.io_dict["out"]["output_traj_path"] = gro_common.check_out_traj_path(self.io_dict["out"]["output_traj_path"], out_log, self.__class__.__name__) 

103 '''if not self.io_dict["in"]["input_index_path"]: 

104 self.selection = get_selection(self.properties, out_log, self.__class__.__name__) 

105 else: 

106 self.selection = get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'selection', out_log, self.__class__.__name__)''' 

107 if self.io_dict["in"]["input_top_path"] and not self.io_dict["in"]["input_index_path"]: 

108 self.selection = gro_common.get_selection(self.properties, out_log, self.__class__.__name__) 

109 elif self.io_dict["in"]["input_index_path"]: 

110 self.selection = gro_common.get_selection_index_file(self.properties, self.io_dict["in"]["input_index_path"], 'selection', out_log, self.__class__.__name__) 

111 elif not self.io_dict["in"]["input_top_path"] and not self.io_dict["in"]["input_index_path"]: 

112 self.selection = "" 

113 else: 

114 return True 

115 self.start = gro_common.get_start(self.properties, out_log, self.__class__.__name__) 

116 self.end = gro_common.get_end(self.properties, out_log, self.__class__.__name__) 

117 self.dt = gro_common.get_dt(self.properties, out_log, self.__class__.__name__) 

118 

119 @launchlogger 

120 def launch(self) -> int: 

121 """Execute the :class:`GMXTrjConvTrj <gromacs.gmx_trjconv_trj.GMXTrjConvTrj>` gromacs.gmx_trjconv_trj.GMXTrjConvTrj object.""" 

122 

123 # check input/output paths and parameters 

124 self.check_data_params(self.out_log, self.err_log) 

125 

126 # if not input_index_path and not input_top_path provided, selection must be empty, otherwise exit 

127 if not self.io_dict["in"]["input_index_path"] and not self.io_dict["in"]["input_top_path"] and self.selection != '': 

128 fu.log(self.__class__.__name__ + ': If not input_index_path and not input_top_path provided, selection must be empty', self.out_log) 

129 raise SystemExit(self.__class__.__name__ + ': If not input_index_path and not input_top_path provided, selection must be empty') 

130 

131 # Setup Biobb 

132 if self.check_restart(): 

133 return 0 

134 

135 # standard input 

136 self.io_dict['in']['stdin_file_path'] = fu.create_stdin_file(f'{self.selection}') 

137 self.stage_files() 

138 

139 self.cmd = [self.binary_path, 'trjconv', 

140 '-f', self.stage_io_dict["in"]["input_traj_path"], 

141 '-b', self.start, 

142 '-e', self.end, 

143 '-dt', self.dt, 

144 '-o', self.stage_io_dict["out"]["output_traj_path"]] 

145 

146 if "input_index_path" in self.stage_io_dict["in"]: 

147 self.cmd.extend(['-n', self.stage_io_dict["in"]["input_index_path"]]) 

148 

149 if "input_top_path" in self.stage_io_dict["in"]: 

150 self.cmd.extend(['-s', self.stage_io_dict["in"]["input_top_path"]]) 

151 

152 # Add stdin input file 

153 self.cmd.append('<') 

154 self.cmd.append(self.stage_io_dict["in"]["stdin_file_path"]) 

155 

156 # Run Biobb block 

157 self.run_biobb() 

158 

159 # Copy files to host 

160 self.copy_to_host() 

161 

162 self.tmp_files.extend([ 

163 self.stage_io_dict.get("unique_dir", ""), 

164 self.io_dict['in'].get("stdin_file_path", "") 

165 ]) 

166 self.remove_tmp_files() 

167 

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

169 

170 return self.return_code 

171 

172 

173def gmx_trjconv_trj(input_traj_path: str, output_traj_path: str, input_index_path: Optional[str] = None, input_top_path: Optional[str] = None, properties: Optional[dict] = None, **kwargs) -> int: 

174 """Execute the :class:`GMXTrjConvTrj <gromacs.gmx_trjconv_trj.GMXTrjConvTrj>` class and 

175 execute the :meth:`launch() <gromacs.gmx_trjconv_trj.GMXTrjConvTrj.launch>` method.""" 

176 

177 return GMXTrjConvTrj(input_traj_path=input_traj_path, 

178 output_traj_path=output_traj_path, 

179 input_index_path=input_index_path, 

180 input_top_path=input_top_path, 

181 properties=properties, **kwargs).launch() 

182 

183 

184def main(): 

185 """Command line execution of this building block. Please check the command line documentation.""" 

186 parser = argparse.ArgumentParser(description="Converts between GROMACS compatible trajectory file formats and/or extracts a selection of atoms.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

187 parser.add_argument('--config', required=False, help='Configuration file') 

188 

189 # Specific args of each building block 

190 required_args = parser.add_argument_group('required arguments') 

191 required_args.add_argument('--input_traj_path', required=True, help='Path to the GROMACS trajectory file. Accepted formats: xtc, trr, cpt, gro, g96, pdb, tng.') 

192 parser.add_argument('--input_index_path', required=False, help="Path to the GROMACS index file. Accepted formats: ndx.") 

193 parser.add_argument('--input_top_path', required=False, help='Path to the GROMACS input topology file. Accepted formats: tpr, gro, g96, pdb, brk, ent.') 

194 required_args.add_argument('--output_traj_path', required=True, help='Path to the output file. Accepted formats: xtc, trr, gro, g96, pdb, tng.') 

195 

196 args = parser.parse_args() 

197 args.config = args.config or "{}" 

198 properties = settings.ConfReader(config=args.config).get_prop_dic() 

199 

200 # Specific call of each building block 

201 gmx_trjconv_trj(input_traj_path=args.input_traj_path, 

202 output_traj_path=args.output_traj_path, 

203 input_index_path=args.input_index_path, 

204 input_top_path=args.input_top_path, 

205 properties=properties) 

206 

207 

208if __name__ == '__main__': 

209 main()