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

74 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-14 14:38 +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 typing import Optional 

8from biobb_common.generic.biobb_object import BiobbObject 

9from biobb_common.configuration import settings 

10from biobb_common.tools import file_utils as fu 

11from biobb_common.tools.file_utils import launchlogger 

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

13 

14 

15class GMXTrjConvStr(BiobbObject): 

16 """ 

17 | biobb_analysis GMXTrjConvStr 

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

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

20 

21 Args: 

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

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

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

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

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

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

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 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

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

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

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

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

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

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

42 

43 Examples: 

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

45 

46 from biobb_analysis.gromacs.gmx_trjconv_str import gmx_trjconv_str 

47 prop = { 

48 'selection': 'System' 

49 } 

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

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

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

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

54 properties=prop) 

55 

56 Info: 

57 * wrapped_software: 

58 * name: GROMACS trjconv 

59 * version: >=2019.1 

60 * license: LGPL 2.1 

61 * ontology: 

62 * name: EDAM 

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

64 

65 """ 

66 

67 def __init__(self, input_structure_path, input_top_path, output_str_path, 

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

69 properties = properties or {} 

70 

71 # Call parent class constructor 

72 super().__init__(properties) 

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

74 

75 # Input/Output files 

76 self.io_dict = { 

77 "in": {"input_structure_path": input_structure_path, "input_top_path": input_top_path, "input_index_path": input_index_path}, 

78 "out": {"output_str_path": output_str_path} 

79 } 

80 

81 # Properties specific for BB 

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

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

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

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

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

87 self.properties = properties 

88 

89 # Properties common in all GROMACS BB 

90 self.binary_path = 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_structure_path"] = check_traj_path(self.io_dict["in"]["input_structure_path"], out_log, self.__class__.__name__) 

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

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

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

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

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

104 else: 

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

106 

107 @launchlogger 

108 def launch(self) -> int: 

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

110 

111 # check input/output paths and parameters 

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

113 

114 # Setup Biobb 

115 if self.check_restart(): 

116 return 0 

117 

118 # standard input 

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

120 self.stage_files() 

121 

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

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

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

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

126 

127 if self.pbc: 

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

129 self.cmd.append(self.pbc) 

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

131 if self.ur: 

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

133 self.cmd.append(self.ur) 

134 if self.fit: 

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

136 self.cmd.append(self.fit) 

137 

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

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

140 

141 # Add stdin input file 

142 self.cmd.append('<') 

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

144 

145 # Run Biobb block 

146 self.run_biobb() 

147 

148 # Copy files to host 

149 self.copy_to_host() 

150 

151 self.tmp_files.extend([ 

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

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

154 ]) 

155 self.remove_tmp_files() 

156 

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

158 return self.return_code 

159 

160 

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

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

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

164 

165 return GMXTrjConvStr(input_structure_path=input_structure_path, 

166 input_top_path=input_top_path, 

167 output_str_path=output_str_path, 

168 input_index_path=input_index_path, 

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

170 

171 

172def main(): 

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

174 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)) 

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

176 

177 # Specific args of each building block 

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

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

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

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

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

183 

184 args = parser.parse_args() 

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

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

187 

188 # Specific call of each building block 

189 gmx_trjconv_str(input_structure_path=args.input_structure_path, 

190 input_top_path=args.input_top_path, 

191 output_str_path=args.output_str_path, 

192 input_index_path=args.input_index_path, 

193 properties=properties) 

194 

195 

196if __name__ == '__main__': 

197 main()