Coverage for biobb_gromacs/gromacs/trjcat.py: 78%

67 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-25 09:23 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the Trjcat class and the command line interface.""" 

4import shutil 

5import argparse 

6from typing import Optional 

7from pathlib import Path 

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_gromacs.gromacs.common import get_gromacs_version 

13 

14 

15class Trjcat(BiobbObject): 

16 """ 

17 | biobb_gromacs Trjcat 

18 | Wrapper class for the `GROMACS trjcat <http://manual.gromacs.org/current/onlinehelp/gmx-trjcat.html>`_ module. 

19 | The GROMACS solvate module generates a box around the selected structure. 

20 

21 Args: 

22 input_trj_zip_path (str): Path the input GROMACS trajectories (xtc, trr, cpt, gro, pdb, tng) to concatenate in zip format. File type: input. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/data/gromacs/trjcat.zip>`_. Accepted formats: zip (edam:format_3987). 

23 output_trj_path (str): Path to the output trajectory file. File type: output. `Sample file <https://github.com/bioexcel/biobb_gromacs/raw/master/biobb_gromacs/test/reference/gromacs/ref_trjcat.trr>`_. Accepted formats: pdb (edam:format_1476), gro (edam:format_2033), xtc (edam:format_3875), trr (edam:format_3910), tng (edam:format_3876). 

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

25 * **concatenate** (*bool*) - (True) Only concatenate the files without removal of frames with identical timestamps. 

26 * **gmx_lib** (*str*) - (None) Path set GROMACS GMXLIB environment variable. 

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

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

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

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

31 * **container_path** (*str*) - (None) Path to the binary executable of your container. 

32 * **container_image** (*str*) - (None) Container Image identifier. 

33 * **container_volume_path** (*str*) - ("/data") Path to an internal directory in the container. 

34 * **container_working_dir** (*str*) - (None) Path to the internal CWD in the container. 

35 * **container_user_id** (*str*) - (None) User number id to be mapped inside the container. 

36 * **container_shell_path** (*str*) - ("/bin/bash") Path to the binary executable of the container shell. 

37 

38 Examples: 

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

40 

41 from biobb_gromacs.gromacs.trjcat import trjcat 

42 prop = { 'concatenate': True } 

43 trjcat(input_trj_zip_path='/path/to/trajectory_bundle.zip', 

44 output_gro_path='/path/to/concatenated_trajectories.xtc', 

45 properties=prop) 

46 

47 Info: 

48 * wrapped_software: 

49 * name: GROMACS trjcat 

50 * version: 2024.5 

51 * license: LGPL 2.1 

52 * ontology: 

53 * name: EDAM 

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

55 """ 

56 

57 def __init__(self, input_trj_zip_path: str, output_trj_path: str, properties: Optional[dict] = None, **kwargs) -> None: 

58 properties = properties or {} 

59 

60 # Call parent class constructor 

61 super().__init__(properties) 

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

63 

64 # Input/Output files 

65 self.io_dict: dict = { 

66 "in": {}, 

67 "out": {"output_trj_path": output_trj_path} 

68 } 

69 

70 # Should not be copied inside container 

71 self.input_trj_zip_path = input_trj_zip_path 

72 

73 # Properties specific for BB 

74 self.concatenate: bool = properties.get('concatenate', True) 

75 

76 # Properties common in all GROMACS BB 

77 self.gmx_lib = properties.get('gmx_lib', None) 

78 self.binary_path = properties.get('binary_path', 'gmx') 

79 self.gmx_nobackup = properties.get('gmx_nobackup', True) 

80 self.gmx_nocopyright = properties.get('gmx_nocopyright', True) 

81 if self.gmx_nobackup: 

82 self.binary_path += ' -nobackup' 

83 if self.gmx_nocopyright: 

84 self.binary_path += ' -nocopyright' 

85 if not self.container_path: 

86 self.gmx_version = get_gromacs_version(self.binary_path) 

87 

88 # Check the properties 

89 self.check_properties(properties) 

90 self.check_arguments() 

91 

92 @launchlogger 

93 def launch(self) -> int: 

94 """Execute the :class:`Trjcat <gromacs.trjcat.Trjcat>` object.""" 

95 

96 # Setup Biobb 

97 if self.check_restart(): 

98 return 0 

99 self.stage_files() 

100 

101 # Unzip trajectory bundle 

102 trj_dir: str = fu.create_unique_dir() 

103 trj_list: list[str] = fu.unzip_list(self.input_trj_zip_path, trj_dir, self.out_log) 

104 

105 # Copy trajectories to container 

106 if self.container_path: 

107 for index, trajectory_file_path in enumerate(trj_list): 

108 shutil.copy2(trajectory_file_path, self.stage_io_dict.get("unique_dir", "")) 

109 trj_list[index] = str(Path(self.container_volume_path).joinpath(Path(trajectory_file_path).name)) 

110 

111 # Create command line 

112 self.cmd = [self.binary_path, 'trjcat', 

113 '-f', " ".join(trj_list), 

114 '-o', self.stage_io_dict["out"]["output_trj_path"]] 

115 

116 if self.concatenate: 

117 self.cmd.append('-cat') 

118 fu.log('Only concatenate the files without removal of frames with identical timestamps.', self.out_log, self.global_log) 

119 

120 if self.gmx_lib: 

121 self.env_vars_dict['GMXLIB'] = self.gmx_lib 

122 

123 # Run Biobb block 

124 self.run_biobb() 

125 

126 # Copy files to host 

127 self.copy_to_host() 

128 

129 # Remove temporal files 

130 self.tmp_files.extend([ 

131 # self.stage_io_dict.get("unique_dir", ""), 

132 trj_dir 

133 ]) 

134 self.remove_tmp_files() 

135 

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

137 return self.return_code 

138 

139 

140def trjcat(input_trj_zip_path: str, output_trj_path: str, properties: Optional[dict] = None, **kwargs) -> int: 

141 """Create :class:`Trjcat <gromacs.trjcat.Trjcat>` class and 

142 execute the :meth:`launch() <gromacs.trjcat.Trjcat.launch>` method.""" 

143 

144 return Trjcat(input_trj_zip_path=input_trj_zip_path, output_trj_path=output_trj_path, 

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

146 

147 

148trjcat.__doc__ = Trjcat.__doc__ 

149 

150 

151def main(): 

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

153 parser = argparse.ArgumentParser(description="Wrapper of the GROMACS gmx trjcat module.", 

154 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

155 parser.add_argument('-c', '--config', required=False, help="This file can be a YAML file, JSON file or JSON string") 

156 

157 # Specific args of each building block 

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

159 required_args.add_argument('--input_trj_zip_path', required=True) 

160 required_args.add_argument('--output_trj_path', required=True) 

161 

162 args = parser.parse_args() 

163 config = args.config if args.config else None 

164 properties = settings.ConfReader(config=config).get_prop_dic() 

165 

166 # Specific call of each building block 

167 trjcat(input_trj_zip_path=args.input_trj_zip_path, output_trj_path=args.output_trj_path, 

168 properties=properties) 

169 

170 

171if __name__ == '__main__': 

172 main()