Coverage for biobb_analysis/ambertools/cpptraj_strip.py: 81%

85 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 Cpptraj Strip class and the command line interface.""" 

4import argparse 

5from typing import Optional 

6from pathlib import PurePath 

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.ambertools.common import get_default_value, check_top_path, check_traj_path, check_out_path, get_binary_path, get_in_parameters, get_out_parameters, copy_instructions_file_to_container, get_mask 

12 

13 

14class CpptrajStrip(BiobbObject): 

15 """ 

16 | biobb_analysis CpptrajStrip 

17 | Wrapper of the Ambertools Cpptraj module for stripping a defined set of atoms (mask) from a given cpptraj compatible trajectory. 

18 | Cpptraj (the successor to ptraj) is the main program in Ambertools for processing coordinate trajectories and data files. The parameter names and defaults are the same as the ones in the official `Cpptraj manual <https://amber-md.github.io/cpptraj/CPPTRAJ.xhtml>`_. 

19 

20 Args: 

21 input_top_path (str): Path to the input structure or topology file. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/ambertools/cpptraj.parm.top>`_. Accepted formats: top (edam:format_3881), pdb (edam:format_1476), prmtop (edam:format_3881), parmtop (edam:format_3881), zip (edam:format_3987). 

22 input_traj_path (str): Path to the input trajectory to be processed. File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/ambertools/cpptraj.traj.dcd>`_. Accepted formats: mdcrd (edam:format_3878), crd (edam:format_3878), cdf (edam:format_3650), netcdf (edam:format_3650), nc (edam:format_3650), restart (edam:format_3886), ncrestart (edam:format_3886), restartnc (edam:format_3886), dcd (edam:format_3878), charmm (edam:format_3887), cor (edam:format_2033), pdb (edam:format_1476), mol2 (edam:format_3816), trr (edam:format_3910), gro (edam:format_2033), binpos (edam:format_3885), xtc (edam:format_3875), cif (edam:format_1477), arc (edam:format_2333), sqm (edam:format_2033), sdf (edam:format_3814), conflib (edam:format_2033). 

23 output_cpptraj_path (str): Path to the output processed trajectory. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/ambertools/ref_cpptraj.strip.netcdf>`_. Accepted formats: mdcrd (edam:format_3878), crd (edam:format_3878), netcdf (edam:format_3650), nc (edam:format_3650), rst7 (edam:format_3886), ncrst (edam:format_2033), dcd (edam:format_3878), pdb (edam:format_1476), mol2 (edam:format_3816), binpos (edam:format_3885), trr (edam:format_3910), xtc (edam:format_3875), sqm (edam:format_2033). 

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

25 * **start** (*int*) - (1) [1~100000|1] Starting frame for slicing. 

26 * **end** (*int*) - (-1) [-1~100000|1] Ending frame for slicing. 

27 * **steps** (*int*) - (1) [1~100000|1] Step for slicing. 

28 * **mask** (*str*) - ("all-atoms") Mask definition. Values: c-alpha (All c-alpha atoms; protein only), backbone (Backbone atoms), all-atoms (All system atoms), heavy-atoms (System heavy atoms; not hydrogen), side-chain (All not backbone atoms), solute (All system atoms except solvent atoms), ions (All ion molecules), solvent (All solvent atoms), AnyAmberFromatMask (Amber atom selection syntax like `@*`). 

29 * **format** (*str*) - ("netcdf") Output trajectory format. Values: crd (AMBER trajectory format), cdf (Format used by netCDF software library for writing and reading chromatography-MS data files), netcdf (Format used by netCDF software library for writing and reading chromatography-MS data files), nc (Format used by netCDF software library for writing and reading chromatography-MS data files), restart (AMBER coordinate/restart file with 6 coordinates per line), ncrestart (AMBER coordinate/restart file with 6 coordinates per line), restartnc (AMBER coordinate/restart file with 6 coordinates per line), dcd (AMBER trajectory format), charmm (Format of CHARMM Residue Topology Files (RTF)), cor (Charmm COR), pdb (Protein Data Bank format), mol2 (Complete and portable representation of a SYBYL molecule), trr (Trajectory of a simulation experiment used by GROMACS), gro (GROMACS structure), binpos (Translation of the ASCII atom coordinate format to binary code), xtc (Portable binary format for trajectories produced by GROMACS package), cif (Entry format of PDB database in mmCIF format), arc (Tinker ARC), sqm (SQM Input), sdf (One of a family of chemical-data file formats developed by MDL Information Systems), conflib (LMOD Conflib). 

30 * **binary_path** (*str*) - ("cpptraj") Path to the cpptraj executable binary. 

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

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

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

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

35 * **container_image** (*str*) - ('afandiadib/ambertools:serial') 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.ambertools.cpptraj_strip import cpptraj_strip 

45 prop = { 

46 'start': 1, 

47 'end': -1, 

48 'steps': 1, 

49 'mask': 'c-alpha', 

50 'format': 'netcdf' 

51 } 

52 cpptraj_strip(input_top_path='/path/to/myTopology.top', 

53 input_traj_path='/path/to/myTrajectory.dcd', 

54 output_cpptraj_path='/path/to/newTrajectory.netcdf', 

55 properties=prop) 

56 

57 Info: 

58 * wrapped_software: 

59 * name: Ambertools Cpptraj 

60 * version: >=20.0 

61 * license: GNU 

62 * ontology: 

63 * name: EDAM 

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

65 

66 """ 

67 

68 def __init__(self, input_top_path, input_traj_path, output_cpptraj_path, 

69 properties=None, **kwargs) -> None: 

70 properties = properties or {} 

71 

72 # Call parent class constructor 

73 super().__init__(properties) 

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

75 

76 # Input/Output files 

77 self.io_dict = { 

78 "in": {"input_top_path": input_top_path, "input_traj_path": input_traj_path}, 

79 "out": {"output_cpptraj_path": output_cpptraj_path} 

80 } 

81 

82 # Properties specific for BB 

83 self.instructions_file = get_default_value('instructions_file') 

84 self.start = properties.get('start', 1) 

85 self.end = properties.get('end', -1) 

86 self.steps = properties.get('steps', 1) 

87 self.mask = properties.get('mask', 'all-atoms') 

88 self.format = properties.get('format', 'netcdf') 

89 self.properties = properties 

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_top_path"], self.input_top_path_orig = check_top_path(self.io_dict["in"]["input_top_path"], out_log, self.__class__.__name__) 

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

100 self.io_dict["out"]["output_cpptraj_path"] = check_out_path(self.io_dict["out"]["output_cpptraj_path"], out_log, self.__class__.__name__) 

101 self.in_parameters = {'start': self.start, 'end': self.end, 'step': self.steps, 'mask': self.mask} 

102 self.out_parameters = {'format': self.format} 

103 

104 def create_instructions_file(self, container_io_dict, out_log, err_log): 

105 """Creates an input file using the properties file settings""" 

106 instructions_list = [] 

107 # different path if container execution or not 

108 if self.container_path: 

109 self.instructions_file = str(PurePath(self.container_volume_path).joinpath(self.instructions_file)) 

110 else: 

111 self.instructions_file = str(PurePath(fu.create_unique_dir()).joinpath(self.instructions_file)) 

112 fu.create_name(prefix=self.prefix, step=self.step, name=self.instructions_file) 

113 

114 # parm 

115 instructions_list.append('parm ' + container_io_dict["in"]["input_top_path"]) 

116 

117 # trajin 

118 in_parameters = self.in_parameters 

119 in_params = '' 

120 if in_parameters: 

121 in_params = get_in_parameters(self.in_parameters, out_log, 'strip') 

122 instructions_list.append('trajin ' + container_io_dict["in"]["input_traj_path"] + ' ' + in_params) 

123 

124 # mask 

125 mask = self.in_parameters.get('mask', '') 

126 if not mask or mask == 'None': 

127 fu.log('No mask provided, exiting', out_log, self.global_log) 

128 raise SystemExit('Mask parameter is mandatory') 

129 strip_mask = get_mask(mask, out_log) 

130 instructions_list.append('strip ' + strip_mask) 

131 

132 # trajout 

133 out_params = get_out_parameters(self.out_parameters, out_log) 

134 instructions_list.append('trajout ' + container_io_dict["out"]["output_cpptraj_path"] + ' ' + out_params) 

135 

136 # create .in file 

137 with open(self.instructions_file, 'w') as mdp: 

138 for line in instructions_list: 

139 mdp.write(line.strip() + '\n') 

140 

141 return self.instructions_file 

142 

143 @launchlogger 

144 def launch(self) -> int: 

145 """Execute the :class:`CpptrajStrip <ambertools.cpptraj_strip.CpptrajStrip>` ambertools.cpptraj_strip.CpptrajStrip object.""" 

146 

147 # check input/output paths and parameters 

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

149 

150 # Setup Biobb 

151 if self.check_restart(): 

152 return 0 

153 self.stage_files() 

154 

155 # create instructions file 

156 self.create_instructions_file(self.stage_io_dict, self.out_log, self.err_log) 

157 

158 # if container execution, copy intructions file to container 

159 if self.container_path: 

160 copy_instructions_file_to_container(self.instructions_file, self.stage_io_dict['unique_dir']) 

161 

162 # create cmd and launch execution 

163 self.cmd = [self.binary_path, '-i', self.instructions_file] 

164 

165 # Run Biobb block 

166 self.run_biobb() 

167 

168 # Copy files to host 

169 self.copy_to_host() 

170 

171 # remove temporary folder(s) 

172 self.tmp_files.extend([ 

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

174 str(PurePath(self.instructions_file).parent) 

175 ]) 

176 self.remove_tmp_files() 

177 

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

179 

180 return self.return_code 

181 

182 

183def cpptraj_strip(input_top_path: str, input_traj_path: str, output_cpptraj_path: str, properties: Optional[dict] = None, **kwargs) -> int: 

184 """Execute the :class:`CpptrajStrip <ambertools.cpptraj_strip.CpptrajStrip>` class and 

185 execute the :meth:`launch() <ambertools.cpptraj_strip.CpptrajStrip.launch>` method.""" 

186 

187 return CpptrajStrip(input_top_path=input_top_path, 

188 input_traj_path=input_traj_path, 

189 output_cpptraj_path=output_cpptraj_path, 

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

191 

192 

193def main(): 

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

195 parser = argparse.ArgumentParser(description="Strips a defined set of atoms (mask) from a given cpptraj compatible trajectory.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

197 

198 # Specific args of each building block 

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

200 required_args.add_argument('--input_top_path', required=True, help='Path to the input structure or topology file. Accepted formats: top, pdb, prmtop, parmtop, zip.') 

201 required_args.add_argument('--input_traj_path', required=True, help='Path to the input trajectory to be processed. Accepted formats: crd, cdf, netcdf, restart, ncrestart, restartnc, dcd, charmm, cor, pdb, mol2, trr, gro, binpos, xtc, cif, arc, sqm, sdf, conflib.') 

202 required_args.add_argument('--output_cpptraj_path', required=True, help='Path to the output processed trajectory.') 

203 

204 args = parser.parse_args() 

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

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

207 

208 # Specific call of each building block 

209 cpptraj_strip(input_top_path=args.input_top_path, 

210 input_traj_path=args.input_traj_path, 

211 output_cpptraj_path=args.output_cpptraj_path, 

212 properties=properties) 

213 

214 

215if __name__ == '__main__': 

216 main()