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

71 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 Bfactor 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, setup_structure, get_negative_mask, get_mask, get_reference 

10 

11 

12class CpptrajBfactor(BiobbObject): 

13 """ 

14 | biobb_analysis CpptrajBfactor 

15 | Wrapper of the Ambertools Cpptraj module for calculating the Bfactor fluctuations of 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 input_exp_path (str) (Optional): Path to the experimental reference file (required if reference = experimental). File type: input. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/data/ambertools/experimental.1e5t.pdb>`_. Accepted formats: pdb (edam:format_1476). 

22 output_cpptraj_path (str): Path to the output processed analysis. File type: output. `Sample file <https://github.com/bioexcel/biobb_analysis/raw/master/biobb_analysis/test/reference/ambertools/ref_cpptraj.bfactor.first.dat>`_. Accepted formats: dat (edam:format_1637), agr (edam:format_2033), xmgr (edam:format_2033), gnu (edam:format_2033). 

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

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

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

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

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

28 * **reference** (*str*) - ("first") Reference definition. Values: first (Use the first trajectory frame as reference), average (Use the average of all trajectory frames as reference), experimental (Use the experimental structure as reference). 

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

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

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

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

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

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

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

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

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

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

39 

40 Examples: 

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

42 

43 from biobb_analysis.ambertools.cpptraj_bfactor import cpptraj_bfactor 

44 prop = { 

45 'start': 1, 

46 'end': -1, 

47 'steps': 1, 

48 'mask': 'c-alpha', 

49 'reference': 'first' 

50 } 

51 cpptraj_bfactor(input_top_path='/path/to/myTopology.top', 

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

53 output_cpptraj_path='/path/to/newAnalysis.dat', 

54 input_exp_path= '/path/to/myExpStructure.pdb', 

55 properties=prop) 

56 

57 Info: 

58 * wrapped_software: 

59 * name: Ambertools Cpptraj 

60 * version: >=22.5 

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 input_exp_path=None, 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, 

79 "input_traj_path": input_traj_path, 

80 "input_exp_path": input_exp_path}, 

81 "out": {"output_cpptraj_path": output_cpptraj_path} 

82 } 

83 

84 # Properties specific for BB 

85 self.instructions_file = get_default_value('instructions_file') 

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

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

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

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

90 self.reference = properties.get('reference', 'first') 

91 self.properties = properties 

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

93 

94 # Check the properties 

95 self.check_init(properties) 

96 

97 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

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.stage_io_dict['unique_dir']).joinpath("cpptraj.in")) 

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

111 else: 

112 self.instructions_file = self.create_tmp_file(self.instructions_file) 

113 self.instructions_file_path = self.instructions_file 

114 

115 # parm 

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

117 

118 # trajin 

119 in_params = get_in_parameters(self.in_parameters, out_log) 

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

121 

122 # Set up 

123 instructions_list += setup_structure(self) 

124 

125 # mask 

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

127 ref_mask = '' 

128 if mask: 

129 strip_mask = get_negative_mask(mask, out_log) 

130 ref_mask = get_mask(mask, out_log) 

131 instructions_list.append('strip ' + strip_mask) 

132 

133 # reference 

134 reference = self.in_parameters.get('reference', '') 

135 inp_exp_pth = None 

136 if "input_exp_path" in container_io_dict["in"]: 

137 inp_exp_pth = container_io_dict["in"]["input_exp_path"] 

138 instructions_list += get_reference(reference, container_io_dict["out"]["output_cpptraj_path"], inp_exp_pth, ref_mask, False, self.__class__.__name__, out_log) 

139 instructions_list.append('atomicfluct out ' + container_io_dict["out"]["output_cpptraj_path"] + ' byres bfactor') 

140 

141 # create .in file 

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

143 for line in instructions_list: 

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

145 

146 return self.instructions_file_path 

147 

148 @launchlogger 

149 def launch(self) -> int: 

150 """Execute the :class:`CpptrajBfactor <ambertools.cpptraj_bfactor.CpptrajBfactor>` object.""" 

151 

152 # check input/output paths and parameters 

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

154 

155 # Setup Biobb 

156 if self.check_restart(): 

157 return 0 

158 self.stage_files() 

159 

160 # Create instructions file 

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

162 

163 # Create cmd and launch execution 

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

165 

166 # Run Biobb block 

167 self.run_biobb() 

168 # Copy files to host 

169 self.copy_to_host() 

170 # Remove temporary folder 

171 self.remove_tmp_files() 

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

173 

174 return self.return_code 

175 

176 

177def cpptraj_bfactor(input_top_path: str, 

178 input_traj_path: str, 

179 output_cpptraj_path: str, 

180 input_exp_path: Optional[str] = None, 

181 properties: Optional[dict] = None, **kwargs) -> int: 

182 """Create the :class:`CpptrajBfactor <ambertools.cpptraj_bfactor.CpptrajBfactor>` class and 

183 execute the :meth:`launch() <ambertools.cpptraj_bfactor.CpptrajBfactor.launch>` method.""" 

184 return CpptrajBfactor(**dict(locals())).launch() 

185 

186 

187cpptraj_bfactor.__doc__ = CpptrajBfactor.__doc__ 

188main = CpptrajBfactor.get_main( 

189 cpptraj_bfactor, 

190 "Calculates the Bfactor fluctuations of a given cpptraj compatible trajectory." 

191) 

192 

193if __name__ == '__main__': 

194 main()