Coverage for biobb_analysis/ambertools/cpptraj_slice.py: 94%

65 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-06-02 08:53 +0000

1#!/usr/bin/env python3 

2 

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

4 

5from typing import Optional 

6from pathlib import PurePath 

7from biobb_common.generic.biobb_object import BiobbObject 

8from biobb_common.tools.file_utils import launchlogger 

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

10 

11 

12class CpptrajSlice(BiobbObject): 

13 """ 

14 | biobb_analysis CpptrajSlice 

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

16 | 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://raw.githubusercontent.com/Amber-MD/cpptraj/master/doc/CpptrajManual.pdf>`_. 

17 

18 Args: 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

38 

39 Examples: 

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

41 

42 from biobb_analysis.ambertools.cpptraj_slice import cpptraj_slice 

43 prop = { 

44 'start': 1, 

45 'end': -1, 

46 'steps': 1, 

47 'mask': 'c-alpha', 

48 'format': 'netcdf' 

49 } 

50 cpptraj_slice(input_top_path='/path/to/myTopology.top', 

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

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

53 properties=prop) 

54 

55 Info: 

56 * wrapped_software: 

57 * name: Ambertools Cpptraj 

58 * version: >=22.5 

59 * license: GNU 

60 * ontology: 

61 * name: EDAM 

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

63 

64 """ 

65 

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

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

68 properties = properties or {} 

69 

70 # Call parent class constructor 

71 super().__init__(properties) 

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

73 

74 # Input/Output files 

75 self.io_dict = { 

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

77 "out": {"output_cpptraj_path": output_cpptraj_path} 

78 } 

79 

80 # Properties specific for BB 

81 self.instructions_file = get_default_value('instructions_file') 

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

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

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

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

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

87 self.properties = properties 

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

89 

90 # Check the properties 

91 self.check_init(properties) 

92 

93 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

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

100 

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

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

103 instructions_list = [] 

104 # different path if container execution or not 

105 if self.container_path: 

106 self.instructions_file = str(PurePath(self.stage_io_dict['unique_dir']).joinpath("cpptraj.in")) 

107 self.instructions_file_path = str(PurePath(self.container_volume_path).joinpath("cpptraj.in")) 

108 else: 

109 self.instructions_file = self.create_tmp_file(self.instructions_file) 

110 self.instructions_file_path = self.instructions_file 

111 

112 # parm 

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

114 

115 # trajin 

116 in_params = get_in_parameters(self.in_parameters, out_log) 

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

118 

119 # mask 

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

121 if mask: 

122 strip_mask = get_negative_mask(mask, out_log) 

123 instructions_list.append('strip ' + strip_mask) 

124 

125 # trajout 

126 out_params = get_out_parameters(self.out_parameters, out_log) 

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

128 

129 # create .in file 

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

131 for line in instructions_list: 

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

133 

134 return self.instructions_file_path 

135 

136 @launchlogger 

137 def launch(self) -> int: 

138 """Execute the :class:`CpptrajSlice <ambertools.cpptraj_slice.CpptrajSlice>` object.""" 

139 

140 # check input/output paths and parameters 

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

142 

143 # Setup Biobb 

144 if self.check_restart(): 

145 return 0 

146 self.stage_files() 

147 

148 # create instructions file 

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

150 

151 # create cmd and launch execution 

152 self.cmd = [self.binary_path, '-i', self.instructions_file_path] 

153 

154 # Run Biobb block 

155 self.run_biobb() 

156 

157 # Copy files to host 

158 self.copy_to_host() 

159 

160 # remove temporary folder(s) 

161 self.remove_tmp_files() 

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

163 

164 return self.return_code 

165 

166 

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

168 """Create the :class:`CpptrajSlice <ambertools.cpptraj_slice.CpptrajSlice>` class and 

169 execute the :meth:`launch() <ambertools.cpptraj_slice.CpptrajSlice.launch>` method.""" 

170 return CpptrajSlice(**dict(locals())).launch() 

171 

172 

173cpptraj_slice.__doc__ = CpptrajSlice.__doc__ 

174main = CpptrajSlice.get_main(cpptraj_slice, "Extracts a particular trajectory slice from a given cpptraj compatible trajectory.") 

175 

176if __name__ == '__main__': 

177 main()