Coverage for biobb_flexserv/pcasuite/pcz_lindemann.py: 78%

60 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 PCZlindemann class and the command line interface.""" 

4import argparse 

5from typing import Optional 

6import shutil 

7import json 

8from pathlib import PurePath 

9from biobb_common.tools import file_utils as fu 

10from biobb_common.generic.biobb_object import BiobbObject 

11from biobb_common.configuration import settings 

12from biobb_common.tools.file_utils import launchlogger 

13 

14 

15class PCZlindemann(BiobbObject): 

16 """ 

17 | biobb_flexserv PCZlindemann 

18 | Extract Lindemann coefficient (an estimate of the solid-liquid behaviour of a protein) from a compressed PCZ file. 

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

20 

21 Args: 

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

23 output_json_path (str): Output json file with PCA Eigen Vectors. File type: output. `Sample file <https://github.com/bioexcel/biobb_flexserv/raw/master/biobb_flexserv/test/reference/pcasuite/pcz_lindemann.json>`_. Accepted formats: json (edam:format_3464). 

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

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

26 * **mask** (*str*) - ("all atoms") Residue mask, in the format ":resnum1, resnum2, resnum3" (e.g. ":10,21,33"). See https://mmb.irbbarcelona.org/software/pcasuite/ for the complete format specification. 

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

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

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

30 

31 Examples: 

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

33 

34 from biobb_flexserv.pcasuite.pcz_lindemann import pcz_lindemann 

35 prop = { 

36 'mask': ':10,12,15' 

37 } 

38 pcz_lindemann( input_pcz_path='/path/to/pcazip_input.pcz', 

39 output_json_path='/path/to/lindemann_report.json', 

40 properties=prop) 

41 

42 Info: 

43 * wrapped_software: 

44 * name: FlexServ PCAsuite 

45 * version: >=1.0 

46 * license: Apache-2.0 

47 * ontology: 

48 * name: EDAM 

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

50 

51 """ 

52 

53 def __init__(self, input_pcz_path: str, 

54 output_json_path: str, properties: Optional[dict] = None, **kwargs) -> None: 

55 

56 properties = properties or {} 

57 

58 # Call parent class constructor 

59 super().__init__(properties) 

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

61 

62 # Input/Output files 

63 self.io_dict = { 

64 'in': {'input_pcz_path': input_pcz_path}, 

65 'out': {'output_json_path': output_json_path} 

66 } 

67 

68 # Properties specific for BB 

69 self.properties = properties 

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

71 self.mask = properties.get('mask', '') 

72 

73 # Check the properties 

74 self.check_properties(properties) 

75 self.check_arguments() 

76 

77 @launchlogger 

78 def launch(self): 

79 """Launches the execution of the FlexServ pcz_lindemann module.""" 

80 

81 # Setup Biobb 

82 if self.check_restart(): 

83 return 0 

84 # self.stage_files() 

85 

86 # Internal file paths 

87 # try: 

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

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

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

91 # except ValueError: 

92 # # Container or remote case 

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

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

95 

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

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

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

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

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

101 

102 # Creating temporary folder 

103 self.tmp_folder = fu.create_unique_dir() 

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

105 

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

107 

108 # Temporary output 

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

110 temp_out = "output.dat" 

111 temp_json = "output.json" 

112 

113 # Command line 

114 # pczdump -i structure.ca.std.pcz --lindemann -M ":2-86" -o lindemann_report.txt 

115 # self.cmd = [self.binary_path, 

116 # "-i", input_pcz, 

117 # "-o", temp_out, 

118 # "--lindemann" 

119 # ] 

120 

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

122 self.binary_path, 

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

124 "-o", temp_out, 

125 "--lindemann" 

126 ] 

127 

128 if self.mask: 

129 self.cmd.append("-M {}".format(self.mask)) 

130 

131 # Run Biobb block 

132 self.run_biobb() 

133 

134 # Parse output Lindemann 

135 # 0.132891 

136 info_dict = {} 

137 with open(PurePath(self.tmp_folder).joinpath(temp_out), 'r') as file: 

138 for line in file: 

139 info = float(line.strip()) 

140 info_dict['lindemann'] = info 

141 

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

143 out_file.write(json.dumps(info_dict, indent=4)) 

144 

145 # Copy outputs from temporary folder to output path 

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

147 

148 # Copy files to host 

149 # self.copy_to_host() 

150 

151 # remove temporary folder(s) 

152 self.tmp_files.extend([ 

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

154 self.tmp_folder 

155 ]) 

156 self.remove_tmp_files() 

157 

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

159 

160 return self.return_code 

161 

162 

163def pcz_lindemann(input_pcz_path: str, output_json_path: str, 

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

165 """Create :class:`PCZlindemann <flexserv.pcasuite.pcz_lindemann>`flexserv.pcasuite.PCZlindemann class and 

166 execute :meth:`launch() <flexserv.pcasuite.pcz_lindemann.launch>` method""" 

167 

168 return PCZlindemann(input_pcz_path=input_pcz_path, 

169 output_json_path=output_json_path, 

170 properties=properties).launch() 

171 

172 pcz_lindemann.__doc__ = PCZlindemann.__doc__ 

173 

174 

175def main(): 

176 parser = argparse.ArgumentParser(description='Extract Lindemann coefficients from a compressed PCZ file.', formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

178 

179 # Specific args 

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

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

182 required_args.add_argument('--output_json_path', required=True, help='Output json file with Lindemann coefficient report. Accepted formats: json.') 

183 

184 args = parser.parse_args() 

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

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

187 

188 # Specific call 

189 pcz_lindemann(input_pcz_path=args.input_pcz_path, 

190 output_json_path=args.output_json_path, 

191 properties=properties) 

192 

193 

194if __name__ == '__main__': 

195 main()