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

96 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 import file_utils as fu 

9from biobb_common.tools.file_utils import launchlogger 

10from 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 

11 

12 

13class GMXImage(BiobbObject): 

14 """ 

15 | biobb_analysis GMXImage 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

43 

44 Examples: 

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

46 

47 from biobb_analysis.gromacs.gmx_image import gmx_image 

48 prop = { 

49 'fit_selection': 'System', 

50 'center_selection': 'Water_and_ions', 

51 'output_selection': 'System', 

52 'pbc': 'mol' 

53 } 

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

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

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

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

58 properties=prop) 

59 

60 Info: 

61 * wrapped_software: 

62 * name: GROMACS trjconv 

63 * version: >=2019.1 

64 * license: LGPL 2.1 

65 * ontology: 

66 * name: EDAM 

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

68 

69 """ 

70 

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

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

73 properties = properties or {} 

74 

75 # Call parent class constructor 

76 super().__init__(properties) 

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

78 

79 # Input/Output files 

80 self.io_dict = { 

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

82 "out": {"output_traj_path": output_traj_path} 

83 } 

84 

85 # Properties specific for BB 

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

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

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

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

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

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

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

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

94 self.properties = properties 

95 

96 # Properties common in all GROMACS BB 

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

98 

99 # Check the properties 

100 self.check_properties(properties) 

101 self.check_arguments() 

102 

103 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

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

110 if self.fit != 'none': 

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

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

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

114 if self.pbc == 'cluster': 

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

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

117 else: 

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

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

120 if self.pbc == 'cluster': 

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

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

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

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

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

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

127 

128 @launchlogger 

129 def launch(self) -> int: 

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

131 

132 # If fitting provided, echo fit_selection 

133 if self.fit == 'none': 

134 if self.center: 

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

136 elif self.pbc == 'cluster': 

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

138 else: 

139 selections = self.output_selection 

140 else: 

141 if self.center: 

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

143 else: 

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

145 

146 # check input/output paths and parameters 

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

148 

149 # Setup Biobb 

150 if self.check_restart(): 

151 return 0 

152 

153 # standard input 

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

155 self.stage_files() 

156 

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

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

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

160 '-fit', self.fit, 

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

162 

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

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

165 

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

167 

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

169 if self.fit == 'none': 

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

171 self.cmd.append(self.pbc) 

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

173 self.cmd.append(self.ur) 

174 

175 # Add stdin input file 

176 self.cmd.append('<') 

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

178 

179 # Run Biobb block 

180 self.run_biobb() 

181 

182 # Copy files to host 

183 self.copy_to_host() 

184 

185 self.tmp_files.extend([ 

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

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

188 ]) 

189 self.remove_tmp_files() 

190 

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

192 

193 return self.return_code 

194 

195 

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

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

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

199 

200 return GMXImage(input_traj_path=input_traj_path, 

201 input_top_path=input_top_path, 

202 output_traj_path=output_traj_path, 

203 input_index_path=input_index_path, 

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

205 

206 

207def main(): 

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

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

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

211 

212 # Specific args of each building block 

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

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

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

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

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

218 

219 args = parser.parse_args() 

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

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

222 

223 # Specific call of each building block 

224 gmx_image(input_traj_path=args.input_traj_path, 

225 input_top_path=args.input_top_path, 

226 output_traj_path=args.output_traj_path, 

227 input_index_path=args.input_index_path, 

228 properties=properties) 

229 

230 

231if __name__ == '__main__': 

232 main()