Coverage for biobb_analysis/gromacs/gmx_trjconv_str_ens.py: 80%

81 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-06 15:22 +0000

1#!/usr/bin/env python3 

2 

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

4import argparse 

5from biobb_common.generic.biobb_object import BiobbObject 

6from biobb_common.configuration import settings 

7from biobb_common.tools import file_utils as fu 

8from biobb_common.tools.file_utils import launchlogger 

9from biobb_analysis.gromacs.common import get_binary_path, check_input_path, check_traj_path, check_index_path, get_selection_index_file, get_selection, check_out_str_ens_path, get_skip, get_start, get_end, get_dt, get_ot_str_ens, process_output_trjconv_str_ens 

10 

11 

12class GMXTrjConvStrEns(BiobbObject): 

13 """ 

14 | biobb_analysis GMXTrjConvStrEns 

15 | Wrapper of the GROMACS trjconv module for extracting an ensemble of frames containing a selection of atoms from GROMACS compatible trajectory files. 

16 | 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. 

17 

18 Args: 

19 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). 

20 input_top_path (str): 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). 

21 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). 

22 output_str_ens_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.str.ens.zip>`_. Accepted formats: zip (edam:format_3987). 

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

24 * **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). 

25 * **skip** (*int*) - (1) [0~10000|1] Only write every nr-th frame. 

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 * **output_name** (*str*) - ("output") File name for ensemble of output files. 

30 * **output_type** (*str*) - ("pdb") File type for ensemble of output files. Values: gro (Contains a molecular structure in Gromos87 format), g96 (Can be a GROMOS-96 initial/final configuration file or a coordinate trajectory file or a combination of both), pdb (Molecular structure files in the protein databank file format). 

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 * **container_path** (*str*) - (None) Container path definition. 

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

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

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

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

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

40 

41 Examples: 

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

43 

44 from biobb_analysis.gromacs.gmx_trjconv_str_ens import gmx_trjconv_str_ens 

45 prop = { 

46 'selection': 'System', 

47 'start': 0, 

48 'end': 10, 

49 'dt': 1 

50 } 

51 gmx_trjconv_str_ens(input_traj_path='/path/to/myStructure.trr', 

52 input_top_path='/path/to/myTopology.tpr', 

53 output_str_ens_path='/path/to/newStructureEnsemble.zip', 

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

55 properties=prop) 

56 

57 Info: 

58 * wrapped_software: 

59 * name: GROMACS trjconv 

60 * version: >=2019.1 

61 * license: LGPL 2.1 

62 * ontology: 

63 * name: EDAM 

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

65 

66 """ 

67 

68 def __init__(self, input_traj_path, input_top_path, output_str_ens_path, 

69 input_index_path=None, properties=None, **kwargs) -> None: 

70 properties = properties or {} 

71 

72 # Call parent class constructor 

73 super().__init__(properties) 

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

75 

76 # Input/Output files 

77 self.io_dict = { 

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

79 "out": {"output_str_ens_path": output_str_ens_path} 

80 } 

81 

82 # Properties specific for BB 

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

84 self.skip = properties.get('skip', 1) 

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

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

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

88 self.output_name = properties.get('output_name', "output") 

89 self.output_type = properties.get('output_type', "pdb") 

90 self.properties = properties 

91 

92 # Properties common in all GROMACS BB 

93 self.binary_path = get_binary_path(properties, 'binary_path') 

94 

95 # Check the properties 

96 self.check_properties(properties) 

97 self.check_arguments() 

98 

99 def check_data_params(self, out_log, err_log): 

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

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

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

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

104 self.io_dict["out"]["output_str_ens_path"] = check_out_str_ens_path(self.io_dict["out"]["output_str_ens_path"], out_log, self.__class__.__name__) 

105 if not self.io_dict["in"]["input_index_path"]: 

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

107 else: 

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

109 self.skip = get_skip(self.properties, out_log, self.__class__.__name__) 

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

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

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

113 self.output_name = self.properties.get('output_name', 'output') 

114 self.output_type = get_ot_str_ens(self.properties, out_log, self.__class__.__name__) 

115 

116 @launchlogger 

117 def launch(self) -> int: 

118 """Execute the :class:`GMXTrjConvStrEns <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns>` gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns object.""" 

119 

120 # check input/output paths and parameters 

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

122 

123 # Setup Biobb 

124 if self.check_restart(): 

125 return 0 

126 

127 # standard input 

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

129 self.stage_files() 

130 

131 # if container execution, output to container_volume_path, else to unique_dir 

132 if self.container_path: 

133 output = self.container_volume_path + '/' + self.output_name + '.' + self.output_type 

134 else: 

135 output = self.stage_io_dict.get("unique_dir") + '/' + self.output_name + '.' + self.output_type 

136 

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

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

139 '-s', self.stage_io_dict["in"]["input_top_path"], 

140 '-skip', self.skip, 

141 '-b', self.start, 

142 '-dt', self.dt, 

143 '-sep', 

144 '-o', output] 

145 

146 # checking 'end' gromacs 'bug' 

147 if not str(self.end) == "0": 

148 self.cmd.append('-e') 

149 self.cmd.append(self.end) 

150 

151 if self.stage_io_dict["in"].get("input_index_path"): 

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

153 

154 # Add stdin input file 

155 self.cmd.append('<') 

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

157 

158 # Run Biobb block 

159 self.run_biobb() 

160 

161 # Copy files to host 

162 self.copy_to_host() 

163 

164 if self.container_path: 

165 process_output_trjconv_str_ens(self.stage_io_dict['unique_dir'], 

166 self.io_dict["out"]["output_str_ens_path"], 

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

168 self.output_name + '*', self.out_log) 

169 else: 

170 process_output_trjconv_str_ens(self.stage_io_dict.get("unique_dir"), 

171 self.stage_io_dict["out"]["output_str_ens_path"], 

172 self.io_dict["out"]["output_str_ens_path"], 

173 self.output_name + '*.pdb', self.out_log) 

174 

175 self.tmp_files.extend([ 

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

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

178 ]) 

179 self.remove_tmp_files() 

180 

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

182 

183 return self.return_code 

184 

185 

186def gmx_trjconv_str_ens(input_traj_path: str, input_top_path: str, output_str_ens_path: str, input_index_path: str = None, properties: dict = None, **kwargs) -> int: 

187 """Execute the :class:`GMXTrjConvStrEns <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns>` class and 

188 execute the :meth:`launch() <gromacs.gmx_trjconv_str_ens.GMXTrjConvStrEns.launch>` method.""" 

189 

190 return GMXTrjConvStrEns(input_traj_path=input_traj_path, 

191 input_top_path=input_top_path, 

192 output_str_ens_path=output_str_ens_path, 

193 input_index_path=input_index_path, 

194 properties=properties).launch() 

195 

196 

197def main(): 

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

199 parser = argparse.ArgumentParser(description="Extracts an ensemble of frames containing a selection of atoms from GROMACS compatible trajectory files.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

201 

202 # Specific args of each building block 

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

204 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.') 

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

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

207 required_args.add_argument('--output_str_ens_path', required=True, help='Path to the output file. Accepted formats: zip.') 

208 

209 args = parser.parse_args() 

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

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

212 

213 # Specific call of each building block 

214 gmx_trjconv_str_ens(input_traj_path=args.input_traj_path, 

215 input_top_path=args.input_top_path, 

216 output_str_ens_path=args.output_str_ens_path, 

217 input_index_path=args.input_index_path, 

218 properties=properties) 

219 

220 

221if __name__ == '__main__': 

222 main()