Coverage for biobb_analysis/gromacs/gmx_trjconv_str.py: 73%

73 statements  

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

1#!/usr/bin/env python3 

2 

3# AFEGIR PARÀMETRES DE GMX_IMAGE: PBC, CENTER, UR, FIT (NOMÉS APPEND SI L'USUARI ELS AFEGEIX) 

4 

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

6import argparse 

7from biobb_common.generic.biobb_object import BiobbObject 

8from biobb_common.configuration import settings 

9from biobb_common.tools import file_utils as fu 

10from biobb_common.tools.file_utils import launchlogger 

11from 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_traj_path 

12 

13 

14class GMXTrjConvStr(BiobbObject): 

15 """ 

16 | biobb_analysis GMXTrjConvStr 

17 | Wrapper of the GROMACS trjconv module for converting between GROMACS compatible structure file formats and/or extracting a selection of atoms. 

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

19 

20 Args: 

21 input_structure_path (str): Path to the input structure 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). 

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

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

24 output_str_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.pdb>`_. Accepted formats: pdb (edam:format_1476), xtc (edam:format_3875), trr (edam:format_3910), cpt (edam:format_2333), gro (edam:format_2033), g96 (edam:format_2033), tng (edam:format_3876). 

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

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

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

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

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

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 import gmx_trjconv_str 

45 prop = { 

46 'selection': 'System' 

47 } 

48 gmx_trjconv_str(input_structure_path='/path/to/myStructure.trr', 

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

50 output_str_path='/path/to/newStructure.pdb', 

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_structure_path, input_top_path, output_str_path, 

66 input_index_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_structure_path": input_structure_path, "input_top_path": input_top_path, "input_index_path": input_index_path}, 

76 "out": {"output_str_path": output_str_path} 

77 } 

78 

79 # Properties specific for BB 

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

81 self.pbc = properties.get('pbc', None) 

82 self.center = properties.get('dista', None) 

83 self.ur = properties.get('ur', None) 

84 self.fit = properties.get('fit', None) 

85 self.properties = properties 

86 

87 # Properties common in all GROMACS BB 

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

89 

90 # Check the properties 

91 self.check_properties(properties) 

92 self.check_arguments() 

93 

94 def check_data_params(self, out_log, err_log): 

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

96 self.io_dict["in"]["input_structure_path"] = check_traj_path(self.io_dict["in"]["input_structure_path"], out_log, self.__class__.__name__) 

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

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

99 self.io_dict["out"]["output_str_path"] = check_out_traj_path(self.io_dict["out"]["output_str_path"], out_log, self.__class__.__name__) 

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

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

102 else: 

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

104 

105 @launchlogger 

106 def launch(self) -> int: 

107 """Execute the :class:`GMXTrjConvStr <gromacs.gmx_trjconv_str.GMXTrjConvStr>` gromacs.gmx_trjconv_str.GMXTrjConvStr object.""" 

108 

109 # check input/output paths and parameters 

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

111 

112 # Setup Biobb 

113 if self.check_restart(): 

114 return 0 

115 

116 # standard input 

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

118 self.stage_files() 

119 

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

121 '-f', self.stage_io_dict["in"]["input_structure_path"], 

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

123 '-o', self.stage_io_dict["out"]["output_str_path"]] 

124 

125 if self.pbc: 

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

127 self.cmd.append(self.pbc) 

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

129 if self.ur: 

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

131 self.cmd.append(self.ur) 

132 if self.fit: 

133 self.cmd.append('-fit') 

134 self.cmd.append(self.fit) 

135 

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

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

138 

139 # Add stdin input file 

140 self.cmd.append('<') 

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

142 

143 # Run Biobb block 

144 self.run_biobb() 

145 

146 # Copy files to host 

147 self.copy_to_host() 

148 

149 self.tmp_files.extend([ 

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

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

152 ]) 

153 self.remove_tmp_files() 

154 

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

156 

157 

158def gmx_trjconv_str(input_structure_path: str, input_top_path: str, output_str_path: str, input_index_path: str = None, properties: dict = None, **kwargs) -> int: 

159 """Execute the :class:`GMXTrjConvStr <gromacs.gmx_trjconv_str.GMXTrjConvStr>` class and 

160 execute the :meth:`launch() <gromacs.gmx_trjconv_str.GMXTrjConvStr.launch>` method.""" 

161 

162 return GMXTrjConvStr(input_structure_path=input_structure_path, 

163 input_top_path=input_top_path, 

164 output_str_path=output_str_path, 

165 input_index_path=input_index_path, 

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

167 

168 

169def main(): 

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

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

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

173 

174 # Specific args of each building block 

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

176 required_args.add_argument('--input_structure_path', required=True, help='Path to the input structure file. Accepted formats: xtc, trr, cpt, gro, g96, pdb, tng.') 

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

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

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

180 

181 args = parser.parse_args() 

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

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

184 

185 # Specific call of each building block 

186 gmx_trjconv_str(input_structure_path=args.input_structure_path, 

187 input_top_path=args.input_top_path, 

188 output_str_path=args.output_str_path, 

189 input_index_path=args.input_index_path, 

190 properties=properties) 

191 

192 

193if __name__ == '__main__': 

194 main()