Coverage for biobb_flexserv/pcasuite/pcz_stiffness.py: 84%

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

4import argparse 

5from typing import Optional 

6import shutil 

7import json 

8import math 

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 PCZstiffness(BiobbObject): 

17 """ 

18 | biobb_flexserv PCZstiffness 

19 | Extract PCA stiffness 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 json file with PCA Stiffness. File type: output. `Sample file <https://github.com/bioexcel/biobb_flexserv/raw/master/biobb_flexserv/test/reference/pcasuite/pcz_stiffness.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 stiffness. 

28 * **temperature** (*int*) - (300) Temperature with which compute the apparent stiffness. 

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_stiffness import pcz_stiffness 

37 

38 prop = { 

39 'eigenvector': 1 

40 } 

41 

42 pcz_stiffness( input_pcz_path='/path/to/pcazip_input.pcz', 

43 output_json_path='/path/to/pcz_stiffness.json', 

44 properties=prop) 

45 

46 Info: 

47 * wrapped_software: 

48 * name: FlexServ PCAsuite 

49 * version: >=1.0 

50 * license: Apache-2.0 

51 * ontology: 

52 * name: EDAM 

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

54 

55 """ 

56 

57 def __init__(self, input_pcz_path: str, 

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

59 

60 properties = properties or {} 

61 

62 # Call parent class constructor 

63 super().__init__(properties) 

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

65 

66 # Input/Output files 

67 self.io_dict = { 

68 'in': {'input_pcz_path': input_pcz_path}, 

69 'out': {'output_json_path': output_json_path} 

70 } 

71 

72 # Properties specific for BB 

73 self.properties = properties 

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

75 self.eigenvector = properties.get('eigenvector', 0) 

76 self.temperature = properties.get('temperature', 300) 

77 

78 # Check the properties 

79 self.check_properties(properties) 

80 self.check_arguments() 

81 

82 @launchlogger 

83 def launch(self): 

84 """Launches the execution of the FlexServ pcz_stiffness module.""" 

85 

86 # Setup Biobb 

87 if self.check_restart(): 

88 return 0 

89 # self.stage_files() 

90 

91 # Internal file paths 

92 # try: 

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

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

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

96 # except ValueError: 

97 # # Container or remote case 

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

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

100 

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

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

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

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

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

106 

107 # Creating temporary folder 

108 self.tmp_folder = fu.create_unique_dir() 

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

110 

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

112 

113 # Temporary output 

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

115 temp_out = "output.dat" 

116 temp_json = "output.json" 

117 

118 # Command line 

119 # pczdump -i structure.ca.std.pcz --stiffness -o pcz.stiffness 

120 # self.cmd = [self.binary_path, 

121 # "-i", input_pcz, 

122 # "-o", temp_out, 

123 # "--stiff={}".format(self.eigenvector), 

124 # "--temperature={}".format(self.temperature) 

125 # ] 

126 

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

128 self.binary_path, 

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

130 "-o", temp_out, 

131 "--stiff={}".format(self.eigenvector), 

132 "--temperature={}".format(self.temperature) 

133 ] 

134 

135 # Run Biobb block 

136 self.run_biobb() 

137 

138 # Parse output stiffness 

139 info_dict = {} 

140 info_dict['stiffness'] = [] 

141 info_dict['stiffness_log'] = [] 

142 row = 0 

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

144 for line in file: 

145 info = line.strip().split(',') 

146 line_array = [] 

147 line_array_log = [] 

148 for nums in info: 

149 if nums: 

150 line_array.append(float(nums)) 

151 if float(nums) != 0: 

152 line_array_log.append(math.log10(float(nums))) 

153 else: 

154 line_array_log.append(float(nums)) 

155 

156 info_dict['stiffness'].append(line_array) 

157 info_dict['stiffness'][row][row] = float('inf') 

158 info_dict['stiffness_log'].append(line_array_log) 

159 info_dict['stiffness_log'][row][row] = float('inf') 

160 row += 1 

161 

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

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

164 

165 # Copy outputs from temporary folder to output path 

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

167 

168 # Copy files to host 

169 # self.copy_to_host() 

170 

171 # remove temporary folder(s) 

172 self.tmp_files.extend([ 

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

174 self.tmp_folder 

175 ]) 

176 self.remove_tmp_files() 

177 

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

179 

180 return self.return_code 

181 

182 

183def pcz_stiffness(input_pcz_path: str, output_json_path: str, 

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

185 """Create :class:`PCZstiffness <flexserv.pcasuite.pcz_stiffness>`flexserv.pcasuite.PCZstiffness class and 

186 execute :meth:`launch() <flexserv.pcasuite.pcz_stiffness.launch>` method""" 

187 

188 return PCZstiffness(input_pcz_path=input_pcz_path, 

189 output_json_path=output_json_path, 

190 properties=properties).launch() 

191 

192 pcz_stiffness.__doc__ = PCZstiffness.__doc__ 

193 

194 

195def main(): 

196 parser = argparse.ArgumentParser(description='Extract PCA Stiffness from a compressed PCZ file.', formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

198 

199 # Specific args 

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

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

202 required_args.add_argument('--output_json_path', required=True, help='Output json file with PCA stiffness. Accepted formats: json.') 

203 

204 args = parser.parse_args() 

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

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

207 

208 # Specific call 

209 pcz_stiffness(input_pcz_path=args.input_pcz_path, 

210 output_json_path=args.output_json_path, 

211 properties=properties) 

212 

213 

214if __name__ == '__main__': 

215 main()