Coverage for biobb_cmip/cmip/cmip_titration.py: 23%

82 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-01-28 09:52 +0000

1#!/usr/bin/env python3 

2 

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

4import os 

5import argparse 

6from typing import Optional 

7from typing import Any 

8from pathlib import Path 

9from biobb_common.generic.biobb_object import BiobbObject 

10from biobb_common.configuration import settings 

11from biobb_common.tools import file_utils as fu 

12from biobb_common.tools.file_utils import launchlogger 

13from biobb_cmip.cmip.common import create_params_file 

14from biobb_cmip.cmip.common import params_preset 

15from biobb_cmip.cmip.common import get_pdb_total_charge 

16 

17 

18class CmipTitration(BiobbObject): 

19 """ 

20 | biobb_cmip Titration 

21 | Wrapper class for the CMIP titration module. 

22 | The CMIP titration module. CMIP titration module adds water molecules, positive ions (Na+) and negative ions (Cl-) in the energetically most favorable structure locations. 

23 

24 Args: 

25 input_pdb_path (str): Path to the input PDB file. File type: input. `Sample file <https://raw.githubusercontent.com/bioexcel/biobb_cmip/master/biobb_cmip/test/data/cmip/1kim_h.pdb>`_. Accepted formats: pdb (edam:format_1476). 

26 output_pdb_path (str): Path to the output PDB file. File type: output. `Sample file <https://raw.githubusercontent.com/bioexcel/biobb_cmip/master/biobb_cmip/test/reference/cmip/1kim_neutral.pdb>`_. Accepted formats: pdb (edam:format_1476). 

27 input_vdw_params_path (str) (Optional): Path to the CMIP input Van der Waals force parameters, if not provided the CMIP conda installation one is used ("$CONDA_PREFIX/share/cmip/dat/vdwprm"). File type: input. Accepted formats: txt (edam:format_2330). 

28 input_params_path (str) (Optional): Path to the CMIP input parameters file. File type: input. Accepted formats: txt (edam:format_2330). 

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

30 * **params** (*dict*) - ({}) CMIP options specification. 

31 * **energy_cutoff** (*float*) - (9999.9) Energy cutoff, extremely hight value to enable the addition of all the ions and waters before reaching the cutoff. 

32 * **num_wats** (*int*) - (10) Number of water molecules to be added. 

33 * **neutral** (*bool*) - (False) Neutralize the charge of the system. If selected *num_positive_ions* and *num_negative_ions* values will not be taken into account. 

34 * **num_positive_ions** (*int*) - (10) Number of positive ions to be added (Tipatom IP=Na+). 

35 * **num_negative_ions** (*int*) - (10) Number of negative ions to be added (Tipatom IM=Cl-). 

36 * **binary_path** (*str*) - ("titration") Path to the CMIP Titration executable binary. 

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

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

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

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

41 * **container_image** (*str*) - ("cmip/cmip:latest") Container Image identifier. 

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

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

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

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

46 

47 

48 Examples: 

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

50 

51 from biobb_cmip.cmip.titration import titration 

52 prop = { 'binary_path': 'titration' } 

53 titration(input_pdb_path='/path/to/myStructure.pdb', 

54 output_pdb_path='/path/to/newStructure.pdb', 

55 properties=prop) 

56 

57 Info: 

58 * wrapped_software: 

59 * name: CMIP Titration 

60 * version: 2.7.0 

61 * license: Apache-2.0 

62 * ontology: 

63 * name: EDAM 

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

65 """ 

66 

67 def __init__(self, input_pdb_path: str, output_pdb_path: str, 

68 input_vdw_params_path: Optional[str] = None, input_params_path: Optional[str] = None, 

69 properties: Optional[dict] = 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_pdb_path": input_pdb_path, "input_vdw_params_path": input_vdw_params_path, 

79 "input_params_path": input_params_path}, 

80 "out": {"output_pdb_path": output_pdb_path} 

81 } 

82 

83 # Properties specific for BB 

84 self.neutral = properties.get('neutral', False) 

85 self.num_wats = properties.get('num_wats') 

86 self.num_positive_ions = properties.get('num_positive_ions') 

87 self.num_negative_ions = properties.get('num_negative_ions') 

88 self.binary_path = properties.get('binary_path', 'titration') 

89 self.output_params_path = properties.get('output_params_path', 'params') 

90 if not self.io_dict['in'].get('input_vdw_params_path'): 

91 self.io_dict['in']['input_vdw_params_path'] = f"{os.environ.get('CONDA_PREFIX')}/share/cmip/dat/vdwprm" 

92 self.params: dict[str, Any] = {k: str(v) for k, v in properties.get('params', dict()).items()} 

93 self.energy_cutoff = properties.get('energy_cutoff', 9999.9) 

94 

95 # Check the properties 

96 self.check_properties(properties) 

97 self.check_arguments() 

98 

99 @launchlogger 

100 def launch(self) -> int: 

101 """Execute the :class:`Titration <cmip.titration.Titration>` object.""" 

102 # Setup Biobb 

103 if self.check_restart(): 

104 return 0 

105 

106 # Check if output_pdb_path ends with ".pdb" 

107 if not self.io_dict['out']['output_pdb_path'].endswith('.pdb'): 

108 fu.log('ERROR: output_pdb_path name must end in .pdb', self.out_log, self.global_log) 

109 raise ValueError("ERROR: output_pdb_path name must end in .pdb") 

110 

111 # Adding neutral, num_negative_ions, num_positive_ions, num_wats, cutoff 

112 if self.num_wats: 

113 self.params['titwat'] = str(self.num_wats) 

114 if self.num_positive_ions: 

115 self.params['titip'] = str(self.num_positive_ions) 

116 if self.num_negative_ions: 

117 self.params['titim'] = str(self.num_negative_ions) 

118 if self.neutral: 

119 charge = get_pdb_total_charge(self.io_dict['in']['input_pdb_path']) 

120 self.params['titip'] = '0' 

121 self.params['titim'] = '0' 

122 if int(round(charge)) > 0: 

123 self.params['titim'] = str(int(round(charge))) 

124 elif int(round(charge)) < 0: 

125 self.params['titip'] = abs(int(round(charge))) 

126 else: 

127 fu.log(f'Neutral flag activated however no positive or negative ions will be added because the system ' 

128 f'is already neutralized. System charge: {round(charge, 3)}', self.out_log, self.global_log) 

129 fu.log(f'Neutral flag activated. Current system charge: {round(charge, 3)}, ' 

130 f'positive ions to be added: {self.params["titip"]}, ' 

131 f'negative ions to be added: {self.params["titim"]}, ' 

132 f'final residual charge: {round(charge + int(self.params["titip"]) - int(self.params["titim"]), 3)}', 

133 self.out_log, self.global_log) 

134 if self.energy_cutoff: 

135 self.params['titcut'] = str(self.energy_cutoff) 

136 

137 combined_params_dir = fu.create_unique_dir() 

138 self.io_dict['in']['combined_params_path'] = create_params_file( 

139 output_params_path=str(Path(combined_params_dir).joinpath(self.output_params_path)), 

140 input_params_path=self.io_dict['in']['input_params_path'], 

141 params_preset_dict=params_preset(execution_type='titration'), 

142 params_properties_dict=self.params) 

143 

144 self.stage_files() 

145 

146 self.cmd = [self.binary_path, 

147 '-i', self.stage_io_dict['in']['combined_params_path'], 

148 '-vdw', self.stage_io_dict['in']['input_vdw_params_path'], 

149 '-hs', self.stage_io_dict['in']['input_pdb_path'], 

150 '-outpdb', self.stage_io_dict['out']['output_pdb_path'][:-4]] 

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 combined_params_dir 

162 ]) 

163 self.remove_tmp_files() 

164 

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

166 return self.return_code 

167 

168 

169def cmip_titration(input_pdb_path: str, output_pdb_path: str, 

170 input_vdw_params_path: Optional[str] = None, input_params_path: Optional[str] = None, 

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

172 """Create :class:`Titration <cmip.titration.Titration>` class and 

173 execute the :meth:`launch() <cmip.titration.Titration.launch>` method.""" 

174 

175 return CmipTitration(input_pdb_path=input_pdb_path, output_pdb_path=output_pdb_path, 

176 input_vdw_params_path=input_vdw_params_path, input_params_path=input_params_path, 

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

178 

179 cmip_titration.__doc__ = CmipTitration.__doc__ 

180 

181 

182def main(): 

183 parser = argparse.ArgumentParser(description="Wrapper of the CMIP Titration module.", 

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

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

186 

187 # Specific args of each building block 

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

189 required_args.add_argument('--input_pdb_path', required=True) 

190 required_args.add_argument('--output_pdb_path', required=True) 

191 parser.add_argument('--input_vdw_params_path', required=False) 

192 parser.add_argument('--input_params_path', required=False) 

193 

194 args = parser.parse_args() 

195 config = args.config if args.config else None 

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

197 

198 # Specific call of each building block 

199 cmip_titration(input_pdb_path=args.input_pdb_path, output_pdb_path=args.output_pdb_path, 

200 input_vdw_params_path=args.input_vdw_params_path, input_params_path=args.input_params_path, 

201 properties=properties) 

202 

203 

204if __name__ == '__main__': 

205 main()