Coverage for biobb_analysis/gromacs/gmx_image.py: 68%

96 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_image_selection, get_selection_index_file, check_out_traj_path, get_pbc, get_center, get_ur, get_fit 

10 

11 

12class GMXImage(BiobbObject): 

13 """ 

14 | biobb_analysis GMXImage 

15 | Wrapper of the GROMACS trjconv module for correcting periodicity (image) from a given GROMACS compatible trajectory file. 

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_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_image.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). 

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

24 * **fit_selection** (*str*) - ("System") Group where the fitting 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 * **center_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 * **cluster_selection** (*str*) - ("System") Group assigned to be the cluster, onto which all atoms are wrapped around the box, such that they are closest to the center of mass of the cluster, which is iteratively updated. 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). 

27 * **output_selection** (*str*) - ("System") Group that is going to be written in the output trajectory. 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). 

28 * **pbc** (*str*) - ("mol") PBC treatment (see help text for full description). Values: none (No PBC treatment), mol (Puts the center of mass of molecules in the box), res (Puts the center of mass of residues in the box), atom (Puts all the atoms in the box), nojump (Checks if atoms jump across the box and then puts them back), cluster (Clusters all the atoms in the selected index such that they are all closest to the center of mass of the cluster which is iteratively updated), whole (Only makes broken molecules whole). 

29 * **center** (*bool*) - (True) Center atoms in box. 

30 * **ur** (*str*) - ("compact") Unit-cell representation. Values: rect (It's the ordinary brick shape), tric (It's the triclinic unit cell), compact (Puts all atoms at the closest distance from the center of the box). 

31 * **fit** (*str*) - ("none") Fit molecule to ref structure in the structure file. Values: none, rot+trans, rotxy+transxy, translation, transxy, progressive. 

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

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

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

35 * **container_path** (*str*) - (None) Container path definition. 

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

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

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

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

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

41 

42 Examples: 

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

44 

45 from biobb_analysis.gromacs.gmx_image import gmx_image 

46 prop = { 

47 'fit_selection': 'System', 

48 'center_selection': 'Water_and_ions', 

49 'output_selection': 'System', 

50 'pbc': 'mol' 

51 } 

52 gmx_image(input_traj_path='/path/to/myTrajectory.trr', 

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

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

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

56 properties=prop) 

57 

58 Info: 

59 * wrapped_software: 

60 * name: GROMACS trjconv 

61 * version: >=2019.1 

62 * license: LGPL 2.1 

63 * ontology: 

64 * name: EDAM 

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

66 

67 """ 

68 

69 def __init__(self, input_traj_path, input_top_path, output_traj_path, 

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

71 properties = properties or {} 

72 

73 # Call parent class constructor 

74 super().__init__(properties) 

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

76 

77 # Input/Output files 

78 self.io_dict = { 

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

80 "out": {"output_traj_path": output_traj_path} 

81 } 

82 

83 # Properties specific for BB 

84 self.fit_selection = properties.get('fit_selection', "System") 

85 self.center_selection = properties.get('center_selection', "System") 

86 self.cluster_selection = properties.get('cluster_selection', "System") 

87 self.output_selection = properties.get('output_selection', "System") 

88 self.pbc = properties.get('pbc', "mol") 

89 self.center = properties.get('dista', True) 

90 self.ur = properties.get('ur', "compact") 

91 self.fit = properties.get('fit', "none") 

92 self.properties = properties 

93 

94 # Properties common in all GROMACS BB 

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

96 

97 # Check the properties 

98 self.check_properties(properties) 

99 self.check_arguments() 

100 

101 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

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

108 if self.fit != 'none': 

109 self.fit_selection = get_image_selection(self.properties, 'fit_selection', out_log, self.__class__.__name__) 

110 if self.fit != 'none' or not self.center: 

111 self.center_selection = get_image_selection(self.properties, 'center_selection', out_log, self.__class__.__name__) 

112 if self.pbc == 'cluster': 

113 self.cluster_selection = get_image_selection(self.properties, 'cluster_selection', out_log, self.__class__.__name__) 

114 self.output_selection = get_image_selection(self.properties, 'output_selection', out_log, self.__class__.__name__) 

115 else: 

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

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

118 if self.pbc == 'cluster': 

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

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

121 self.pbc = get_pbc(self.properties, out_log, self.__class__.__name__) 

122 self.center = get_center(self.properties, out_log, self.__class__.__name__) 

123 self.ur = get_ur(self.properties, out_log, self.__class__.__name__) 

124 self.fit = get_fit(self.properties, out_log, self.__class__.__name__) 

125 

126 @launchlogger 

127 def launch(self) -> int: 

128 """Execute the :class:`GMXImage <gromacs.gmx_image.GMXImage>` gromacs.gmx_image.GMXImage object.""" 

129 

130 # If fitting provided, echo fit_selection 

131 if self.fit == 'none': 

132 if self.center: 

133 selections = self.center_selection + ' ' + self.output_selection 

134 elif self.pbc == 'cluster': 

135 selections = self.cluster_selection + ' ' + self.output_selection 

136 else: 

137 selections = self.output_selection 

138 else: 

139 if self.center: 

140 selections = self.fit_selection + ' ' + self.center_selection + ' ' + self.output_selection 

141 else: 

142 selections = self.fit_selection + ' ' + self.output_selection 

143 

144 # check input/output paths and parameters 

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

146 

147 # Setup Biobb 

148 if self.check_restart(): 

149 return 0 

150 

151 # standard input 

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

153 self.stage_files() 

154 

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

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

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

158 '-fit', self.fit, 

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

160 

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

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

163 

164 self.cmd.append('-center' if self.center else '-nocenter') 

165 

166 # Unit-cell representation, PBC treatment is incompatible with fitting 

167 if self.fit == 'none': 

168 self.cmd.append('-pbc') 

169 self.cmd.append(self.pbc) 

170 self.cmd.append('-ur') 

171 self.cmd.append(self.ur) 

172 

173 # Add stdin input file 

174 self.cmd.append('<') 

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

176 

177 # Run Biobb block 

178 self.run_biobb() 

179 

180 # Copy files to host 

181 self.copy_to_host() 

182 

183 self.tmp_files.extend([ 

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

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

186 ]) 

187 self.remove_tmp_files() 

188 

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

190 

191 return self.return_code 

192 

193 

194def gmx_image(input_traj_path: str, input_top_path: str, output_traj_path: str, input_index_path: str = None, properties: dict = None, **kwargs) -> int: 

195 """Execute the :class:`GMXImage <gromacs.gmx_image.GMXImage>` class and 

196 execute the :meth:`launch() <gromacs.gmx_image.GMXImage.launch>` method.""" 

197 

198 return GMXImage(input_traj_path=input_traj_path, 

199 input_top_path=input_top_path, 

200 output_traj_path=output_traj_path, 

201 input_index_path=input_index_path, 

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

203 

204 

205def main(): 

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

207 parser = argparse.ArgumentParser(description="Corrects periodicity (image) from a given GROMACS compatible trajectory file.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

209 

210 # Specific args of each building block 

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

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

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

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

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

216 

217 args = parser.parse_args() 

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

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

220 

221 # Specific call of each building block 

222 gmx_image(input_traj_path=args.input_traj_path, 

223 input_top_path=args.input_top_path, 

224 output_traj_path=args.output_traj_path, 

225 input_index_path=args.input_index_path, 

226 properties=properties) 

227 

228 

229if __name__ == '__main__': 

230 main()