Coverage for biobb_flexserv/pcasuite/pcz_hinges.py: 55%

130 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-19 15:08 +0000

1#!/usr/bin/env python3 

2 

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

4import argparse 

5from typing import Optional 

6import shutil 

7import json 

8import re 

9from pathlib import PurePath 

10from biobb_common.tools import file_utils as fu 

11from biobb_common.generic.biobb_object import BiobbObject 

12from biobb_common.configuration import settings 

13from biobb_common.tools.file_utils import launchlogger 

14 

15 

16class PCZhinges(BiobbObject): 

17 """ 

18 | biobb_flexserv PCZhinges 

19 | Compute possible hinge regions (residues around which large protein movements are organized) of a molecule from a compressed PCZ file. 

20 | Wrapper of the pczdump tool from the PCAsuite FlexServ module. 

21 

22 Args: 

23 input_pcz_path (str): Input compressed trajectory file. File type: input. `Sample file <https://github.com/bioexcel/biobb_flexserv/raw/master/biobb_flexserv/test/data/pcasuite/pcazip.pcz>`_. Accepted formats: pcz (edam:format_3874). 

24 output_json_path (str): Output hinge regions x PCA mode file. File type: output. `Sample file <https://github.com/bioexcel/biobb_flexserv/raw/master/biobb_flexserv/test/reference/pcasuite/hinges.json>`_. Accepted formats: json (edam:format_3464). 

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

26 * **binary_path** (*str*) - ("pczdump") pczdump binary path to be used. 

27 * **eigenvector** (*int*) - (0) PCA mode (eigenvector) from which to extract bfactor values per residue (0 means average over all modes). 

28 * **method** (*str*) - ("Dynamic_domain") Method to compute the hinge regions (Options: Bfactor_slope, Force_constant, Dynamic_domain) 

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 

33 Examples: 

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

35 

36 from biobb_flexserv.pcasuite.pcz_hinges import pcz_hinges 

37 prop = { 

38 'eigenvector': 1, 

39 'pdb': True 

40 } 

41 pcz_hinges( input_pcz_path='/path/to/pcazip_input.pcz', 

42 output_json_path='/path/to/hinges.json', 

43 properties=prop) 

44 

45 Info: 

46 * wrapped_software: 

47 * name: FlexServ PCAsuite 

48 * version: >=1.0 

49 * license: Apache-2.0 

50 * ontology: 

51 * name: EDAM 

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

53 

54 """ 

55 

56 def __init__(self, input_pcz_path: str, output_json_path: str, 

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

58 

59 properties = properties or {} 

60 

61 # Call parent class constructor 

62 super().__init__(properties) 

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

64 

65 # Input/Output files 

66 self.io_dict = { 

67 'in': {'input_pcz_path': input_pcz_path}, 

68 'out': {'output_json_path': output_json_path} 

69 } 

70 

71 # Properties specific for BB 

72 self.properties = properties 

73 self.binary_path = properties.get('binary_path', 'pczdump') 

74 self.eigenvector = properties.get('eigenvector', 1) 

75 self.method = properties.get('method', "Bfactor_slope") 

76 

77 # Check the properties 

78 self.check_properties(properties) 

79 self.check_arguments() 

80 

81 def parse_output(self, output_file): 

82 """ Parses FlexServ hinges methods output file report """ 

83 

84 method = '' 

85 if self.method == "Bfactor_slope": 

86 method = "#### Distance variation method" 

87 elif self.method == "Force_constant": 

88 method = "#### Force constant" 

89 elif self.method == "Dynamic_domain": 

90 method = "#### Lavery method" 

91 else: 

92 print("Method not recognised ({}), please check it and try again. ".format(self.method)) 

93 

94 start = False 

95 out_data = '' 

96 with open(output_file, 'r') as file: 

97 for line in file: 

98 if method in line: 

99 start = True 

100 elif "####" in line: 

101 start = False 

102 if start: 

103 out_data += line 

104 

105 dict_out = {} 

106 dict_out["method"] = self.method 

107 if self.method == "Force_constant": 

108 dict_out["values_per_residue"] = [] 

109 for line in out_data.split("\n"): 

110 if line and "#" not in line: 

111 dict_out["values_per_residue"].append(float(line.strip())) 

112 if "possible hinge" in line: # Peak constant (possible hinge): residue 64 (16.740) 

113 residue = int(line.split(' ')[6]) 

114 dict_out["hinge_residues"] = residue 

115 elif self.method == "Bfactor_slope": 

116 dict_out["hinge_residues"] = [] 

117 for line in out_data.split("\n"): 

118 if "Window" in line: # Window 28: residue 54 seems a downhill hinge point 

119 residue = int(re.split(r'\s+', line)[3]) 

120 dict_out["hinge_residues"].append(residue) 

121 if "Consensus" in line: # Consensus Downhill hinge point : 23.7 ( 64.965) 

122 hinge_point = float(line.split(':')[1].split('(')[0]) 

123 dict_out["consensus_hinge"] = hinge_point 

124 elif self.method == "Dynamic_domain": 

125 start = 0 

126 dict_out["clusters"] = [] 

127 for line in out_data.split("\n"): 

128 if "threshold" not in line and "nClusters" in line: # nClusters: 2 

129 nclusters = int(line.split(':')[1]) 

130 dict_out["nClusters"] = nclusters 

131 if "Threshold" in line: # *** Threshold defined: 0.300000 

132 threshold = float(line.split(':')[1]) 

133 dict_out["threshold"] = threshold 

134 if "Min. drij" in line: # *** Min. drij: 0.000322 

135 minValue = float(line.split(':')[1]) 

136 dict_out["minValue"] = minValue 

137 if "Max. drij" in line: # *** Max. drij: 6.385425 

138 maxValue = float(line.split(':')[1]) 

139 dict_out["maxValue"] = maxValue 

140 if "threshold" in line: # nClusters: 2 threshold: 3.192873 

141 final_threshold = float(line.split(':')[2]) 

142 dict_out["final_threshold"] = final_threshold 

143 if "Cluster" in line and "elements" in line: # Cluster 0 (74 elements) 

144 clusterLine = line.split() 

145 clusterNum = int(clusterLine[1]) 

146 clusterElems = int(clusterLine[2].replace('(', '')) 

147 cluster = {"clusterNum": clusterNum, "clusterElems": clusterElems} 

148 dict_out["clusters"].append(cluster) 

149 start = start + 1 

150 if start and "[" in line: 

151 # dict_out["clusters"][start-1]["residues"] = list(map(int,list(line.replace(", ]", "").replace(" [","").split(', ')))) 

152 dict_out["clusters"][start-1]["residues"] = eval(line) 

153 # Interacting regions: 13 14 30 31 69 70 84 85 112 113 114 115 116 166 167 199 200 

154 if "Interacting regions" in line: 

155 nums = line.split(':')[1] 

156 dict_out["interacting_regions"] = list(map(int, nums.split())) 

157 # Hinge residues: 13 14 30 31 69 70 84 85 112 113 114 115 116 166 167 199 200 

158 if "Hinge residues" in line: 

159 nums = line.split(':')[1] 

160 dict_out["hinge_residues"] = list(map(int, nums.split())) 

161 

162 return dict_out 

163 

164 @launchlogger 

165 def launch(self): 

166 """Launches the execution of the FlexServ pcz_hinges module.""" 

167 

168 # Setup Biobb 

169 if self.check_restart(): 

170 return 0 

171 # self.stage_files() 

172 

173 # Internal file paths 

174 # try: 

175 # # Using rel paths to shorten the amount of characters due to fortran path length limitations 

176 # input_pcz = str(Path(self.stage_io_dict["in"]["input_pcz_path"]).relative_to(Path.cwd())) 

177 # output_json = str(Path(self.stage_io_dict["out"]["output_json_path"]).relative_to(Path.cwd())) 

178 # except ValueError: 

179 # # Container or remote case 

180 # input_pcz = self.stage_io_dict["in"]["input_pcz_path"] 

181 # output_json = self.stage_io_dict["out"]["output_json_path"] 

182 

183 # Manually creating a Sandbox to avoid issues with input parameters buffer overflow: 

184 # Long strings defining a file path makes Fortran or C compiled programs crash if the string 

185 # declared is shorter than the input parameter path (string) length. 

186 # Generating a temporary folder and working inside this folder (sandbox) fixes this problem. 

187 # The problem was found in Galaxy executions, launching Singularity containers (May 2023). 

188 

189 # Creating temporary folder 

190 self.tmp_folder = fu.create_unique_dir() 

191 fu.log('Creating %s temporary folder' % self.tmp_folder, self.out_log) 

192 

193 shutil.copy2(self.io_dict["in"]["input_pcz_path"], self.tmp_folder) 

194 

195 # Temporary output 

196 # temp_out = str(Path(self.stage_io_dict.get("unique_dir", "")).joinpath("output.dat")) 

197 temp_out = "output.dat" 

198 temp_log = "output.log" 

199 temp_json = "output.json" 

200 

201 # Command line (1: dat file) 

202 # pczdump -i structure.ca.std.pcz --fluc=1 -o bfactor_1.dat 

203 # self.cmd = [self.binary_path, 

204 # "-i", input_pcz, 

205 # "-o", temp_out, 

206 # "-t", "0.3", 

207 # "--hinge={}".format(self.eigenvector), 

208 # ">&", "pcz_dump.hinges.log" 

209 # ] 

210 

211 self.cmd = ['cd', self.tmp_folder, ';', 

212 self.binary_path, 

213 '-i', PurePath(self.io_dict["in"]["input_pcz_path"]).name, 

214 '-o', temp_out, 

215 "-t", "0.3", 

216 "--hinge={}".format(self.eigenvector), 

217 ">&", temp_log 

218 ] 

219 

220 # Run Biobb block 

221 self.run_biobb() 

222 

223 # Parsing output file and extracting results for the given method 

224 dict_out = self.parse_output(PurePath(self.tmp_folder).joinpath(temp_out)) 

225 

226 with open(PurePath(self.tmp_folder).joinpath(temp_json), 'w') as out_file: 

227 out_file.write(json.dumps(dict_out, indent=4)) 

228 

229 # Copy outputs from temporary folder to output path 

230 shutil.copy2(PurePath(self.tmp_folder).joinpath(temp_json), PurePath(self.io_dict["out"]["output_json_path"])) 

231 

232 # Copy files to host 

233 # self.copy_to_host() 

234 

235 # remove temporary folder(s) 

236 self.tmp_files.extend([ 

237 # self.stage_io_dict.get("unique_dir", ""), 

238 self.tmp_folder 

239 ]) 

240 self.remove_tmp_files() 

241 

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

243 

244 return self.return_code 

245 

246 

247def pcz_hinges(input_pcz_path: str, output_json_path: str, 

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

249 """Create :class:`PCZhinges <flexserv.pcasuite.pcz_hinges>`flexserv.pcasuite.PCZhinges class and 

250 execute :meth:`launch() <flexserv.pcasuite.pcz_hinges.launch>` method""" 

251 

252 return PCZhinges(input_pcz_path=input_pcz_path, 

253 output_json_path=output_json_path, 

254 properties=properties).launch() 

255 

256 pcz_hinges.__doc__ = PCZhinges.__doc__ 

257 

258 

259def main(): 

260 parser = argparse.ArgumentParser(description='Compute possible hinge regions (residues around which large protein movements are organized) of a molecule from a compressed PCZ file.', formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

262 

263 # Specific args 

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

265 required_args.add_argument('--input_pcz_path', required=True, help='Input compressed trajectory file. Accepted formats: pcz.') 

266 required_args.add_argument('--output_json_path', required=True, help='Output hinge regions x PCA mode file. Accepted formats: json.') 

267 

268 args = parser.parse_args() 

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

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

271 

272 # Specific call 

273 pcz_hinges(input_pcz_path=args.input_pcz_path, 

274 output_json_path=args.output_json_path, 

275 properties=properties) 

276 

277 

278if __name__ == '__main__': 

279 main()