Coverage for biobb_analysis/ambertools/cpptraj_snapshot.py: 82%

78 statements  

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

1#!/usr/bin/env python3 

2 

3"""Module containing the Cpptraj Snapshot class and the command line interface.""" 

4import argparse 

5from pathlib import PurePath 

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

11 

12 

13class CpptrajSnapshot(BiobbObject): 

14 """ 

15 | biobb_analysis CpptrajSnapshot 

16 | Wrapper of the Ambertools Cpptraj module for extracting a particular snapshot from a given cpptraj compatible trajectory. 

17 | 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>`_. 

18 

19 Args: 

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

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

22 output_cpptraj_path (str): Path to the output processed structure. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/ambertools/ref_cpptraj.snapshot.pdb>`_. 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). 

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

24 * **snapshot** (*int*) - (1) [1~100000|1] Frame to be captured for snapshot 

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

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

27 * **binary_path** (*str*) - ("cpptraj") Path to the cpptraj 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 * **container_path** (*str*) - (None) Container path definition. 

31 * **container_image** (*str*) - ('afandiadib/ambertools:serial') Container image definition. 

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

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

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

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

36 

37 Examples: 

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

39 

40 from biobb_analysis.ambertools.cpptraj_snapshot import cpptraj_snapshot 

41 prop = { 

42 'snapshot': 12, 

43 'mask': 'c-alpha', 

44 'format': 'pdb' 

45 } 

46 cpptraj_snapshot(input_top_path='/path/to/myTopology.top', 

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

48 output_cpptraj_path='/path/to/newStructure.pdb', 

49 properties=prop) 

50 

51 Info: 

52 * wrapped_software: 

53 * name: Ambertools Cpptraj 

54 * version: >=20.0 

55 * license: GNU 

56 * ontology: 

57 * name: EDAM 

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

59 

60 """ 

61 

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

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

64 properties = properties or {} 

65 

66 # Call parent class constructor 

67 super().__init__(properties) 

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

69 

70 # Input/Output files 

71 self.io_dict = { 

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

73 "out": {"output_cpptraj_path": output_cpptraj_path} 

74 } 

75 

76 # Properties specific for BB 

77 self.instructions_file = get_default_value('instructions_file') 

78 self.snapshot = properties.get('snapshot', 1) 

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

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

81 self.properties = properties 

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

83 

84 # Check the properties 

85 self.check_properties(properties) 

86 self.check_arguments() 

87 

88 def check_data_params(self, out_log, err_log): 

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

90 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__) 

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

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

93 self.in_parameters = {'snapshot': self.snapshot, 'mask': self.mask} 

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

95 

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

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

98 instructions_list = [] 

99 # different path if container execution or not 

100 if self.container_path: 

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

102 else: 

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

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

105 

106 # parm 

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

108 

109 # trajin 

110 in_params = get_in_parameters(self.in_parameters, out_log, 'snapshot') 

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

112 

113 # mask 

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

115 if mask: 

116 strip_mask = get_negative_mask(mask, out_log) 

117 instructions_list.append('strip ' + strip_mask) 

118 

119 # trajout 

120 out_params = get_out_parameters(self.out_parameters, out_log) 

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

122 

123 # create .in file 

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

125 for line in instructions_list: 

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

127 

128 return self.instructions_file 

129 

130 @launchlogger 

131 def launch(self) -> int: 

132 """Execute the :class:`CpptrajSnapshot <ambertools.cpptraj_snapshot.CpptrajSnapshot>` ambertools.cpptraj_snapshot.CpptrajSnapshot object.""" 

133 

134 # check input/output paths and parameters 

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

136 

137 # Setup Biobb 

138 if self.check_restart(): 

139 return 0 

140 self.stage_files() 

141 

142 # create instructions file 

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

144 

145 # if container execution, copy intructions file to container 

146 if self.container_path: 

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

148 

149 # create cmd and launch execution 

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

151 

152 # Run Biobb block 

153 self.run_biobb() 

154 

155 # Copy files to host 

156 self.copy_to_host() 

157 

158 # remove temporary folder(s) 

159 self.tmp_files.extend([ 

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

161 PurePath(self.instructions_file).parent 

162 ]) 

163 self.remove_tmp_files() 

164 

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

166 

167 return self.return_code 

168 

169 

170def cpptraj_snapshot(input_top_path: str, input_traj_path: str, output_cpptraj_path: str, properties: dict = None, **kwargs) -> int: 

171 """Execute the :class:`CpptrajSnapshot <ambertools.cpptraj_snapshot.CpptrajSnapshot>` class and 

172 execute the :meth:`launch() <ambertools.cpptraj_snapshot.CpptrajSnapshot.launch>` method.""" 

173 

174 return CpptrajSnapshot(input_top_path=input_top_path, 

175 input_traj_path=input_traj_path, 

176 output_cpptraj_path=output_cpptraj_path, 

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

178 

179 

180def main(): 

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

182 parser = argparse.ArgumentParser(description="Extracts a particular snapshot from a given cpptraj compatible trajectory.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

183 parser.add_argument('--config', required=True, help='Configuration file') 

184 

185 # Specific args of each building block 

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

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

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

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

190 

191 args = parser.parse_args() 

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

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

194 

195 # Specific call of each building block 

196 cpptraj_snapshot(input_top_path=args.input_top_path, 

197 input_traj_path=args.input_traj_path, 

198 output_cpptraj_path=args.output_cpptraj_path, 

199 properties=properties) 

200 

201 

202if __name__ == '__main__': 

203 main()