Coverage for biobb_flexserv/pcasuite/pcz_info.py: 84%
73 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-19 15:08 +0000
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-19 15:08 +0000
1#!/usr/bin/env python3
3"""Module containing the PCZinfo 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
15class PCZinfo(BiobbObject):
16 """
17 | biobb_flexserv PCZinfo
18 | Extract PCA info (variance, Dimensionality) from a compressed PCZ file.
19 | Wrapper of the pczdump tool from the PCAsuite FlexServ module.
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 info such as number of components, variance and dimensionality. File type: output. `Sample file <https://github.com/bioexcel/biobb_flexserv/raw/master/biobb_flexserv/test/reference/pcasuite/pcz_info.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 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
27 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
28 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
30 Examples:
31 This is a use example of how to use the building block from Python::
33 from biobb_flexserv.pcasuite.pcz_info import pcz_info
35 pcz_info( input_pcz_path='/path/to/pcazip_input.pcz',
36 output_json_path='/path/to/pcz_info.json')
38 Info:
39 * wrapped_software:
40 * name: FlexServ PCAsuite
41 * version: >=1.0
42 * license: Apache-2.0
43 * ontology:
44 * name: EDAM
45 * schema: http://edamontology.org/EDAM.owl
47 """
49 def __init__(self, input_pcz_path: str,
50 output_json_path: str, properties: Optional[dict] = None, **kwargs) -> None:
52 properties = properties or {}
54 # Call parent class constructor
55 super().__init__(properties)
56 self.locals_var_dict = locals().copy()
58 # Input/Output files
59 self.io_dict = {
60 'in': {'input_pcz_path': input_pcz_path},
61 'out': {'output_json_path': output_json_path}
62 }
64 # Properties specific for BB
65 self.properties = properties
66 self.binary_path = properties.get('binary_path', 'pczdump')
68 # Check the properties
69 self.check_properties(properties)
70 self.check_arguments()
72 @launchlogger
73 def launch(self):
74 """Launches the execution of the FlexServ pcz_info module."""
76 # Setup Biobb
77 if self.check_restart():
78 return 0
79 # self.stage_files()
81 # Internal file paths
82 # try:
83 # # Using rel paths to shorten the amount of characters due to fortran path length limitations
84 # input_pcz = str(Path(self.stage_io_dict["in"]["input_pcz_path"]).relative_to(Path.cwd()))
85 # output_json = str(Path(self.stage_io_dict["out"]["output_json_path"]).relative_to(Path.cwd()))
86 # except ValueError:
87 # # Container or remote case
88 # input_pcz = self.stage_io_dict["in"]["input_pcz_path"]
89 # output_json = self.stage_io_dict["out"]["output_json_path"]
91 # Manually creating a Sandbox to avoid issues with input parameters buffer overflow:
92 # Long strings defining a file path makes Fortran or C compiled programs crash if the string
93 # declared is shorter than the input parameter path (string) length.
94 # Generating a temporary folder and working inside this folder (sandbox) fixes this problem.
95 # The problem was found in Galaxy executions, launching Singularity containers (May 2023).
97 # Creating temporary folder
98 self.tmp_folder = fu.create_unique_dir()
99 fu.log('Creating %s temporary folder' % self.tmp_folder, self.out_log)
101 shutil.copy2(self.io_dict["in"]["input_pcz_path"], self.tmp_folder)
103 # Temporary output
104 # temp_out_1 = str(Path(self.stage_io_dict.get("unique_dir", "")).joinpath("output1.dat"))
105 # temp_out_2 = str(Path(self.stage_io_dict.get("unique_dir", "")).joinpath("output2.dat"))
106 temp_out_1 = "output1.dat"
107 temp_out_2 = "output2.dat"
108 temp_json = "output.json"
110 # Command line
111 # pczdump -i structure.ca.std.pcz --info -o pcz.info
112 # self.cmd = [self.binary_path,
113 # "-i", input_pcz,
114 # "-o", temp_out_1,
115 # "--info", ';',
116 # self.binary_path,
117 # "-i", input_pcz,
118 # "-o", temp_out_2,
119 # "--evals"
120 # ]
122 self.cmd = ['cd', self.tmp_folder, ';',
123 self.binary_path,
124 "-i", PurePath(self.io_dict["in"]["input_pcz_path"]).name,
125 "-o", temp_out_1,
126 "--info", ';',
127 self.binary_path,
128 "-i", PurePath(self.io_dict["in"]["input_pcz_path"]).name,
129 "-o", temp_out_2,
130 "--evals"
131 ]
133 # Run Biobb block
134 self.run_biobb()
136 # Parse output info
137 # Title : MC generated trajectory
138 # Atoms : 85
139 # Vectors : 4
140 # Frames : 1000
141 # Total variance : 1137.20
142 # Explained variance: 1043.32
143 # Quality : 91.74%
144 # Dimensionality : 21
145 # RMSd type : Standard RMSd
146 # Have atom names : True
147 info_dict = {}
148 with open(PurePath(self.tmp_folder).joinpath(temp_out_1), 'r') as file:
149 for line in file:
150 info = line.split(':')
151 info_dict[info[0].strip().replace(' ', '_')] = info[1].strip()
153 # Parse output evals
154 # 744.201782
155 # 170.061981
156 # 89.214905
157 # 39.836308
158 info_dict['Eigen_Values'] = []
159 info_dict['Eigen_Values_dimensionality_vs_total'] = []
160 info_dict['Eigen_Values_dimensionality_vs_explained'] = []
161 accum_tot = 0
162 accum_exp = 0
163 with open(PurePath(self.tmp_folder).joinpath(temp_out_2), 'r') as file:
164 for line in file:
165 eval = float(line.strip())
166 eval_var = (eval / float(info_dict['Total_variance']))*100
167 accum_tot = accum_tot + eval_var
168 eval_dim = (eval / float(info_dict['Explained_variance']))*100
169 accum_exp = accum_exp + eval_dim
170 info_dict['Eigen_Values'].append(eval)
171 info_dict['Eigen_Values_dimensionality_vs_total'].append(accum_tot)
172 info_dict['Eigen_Values_dimensionality_vs_explained'].append(accum_exp)
174 with open(PurePath(self.tmp_folder).joinpath(temp_json), 'w') as out_file:
175 out_file.write(json.dumps(info_dict, indent=4))
177 # Copy outputs from temporary folder to output path
178 shutil.copy2(PurePath(self.tmp_folder).joinpath(temp_json), PurePath(self.io_dict["out"]["output_json_path"]))
180 # Copy files to host
181 # self.copy_to_host()
183 # remove temporary folder(s)
184 self.tmp_files.extend([
185 # self.stage_io_dict.get("unique_dir", ""),
186 self.tmp_folder
187 ])
188 self.remove_tmp_files()
190 self.check_arguments(output_files_created=True, raise_exception=False)
192 return self.return_code
195def pcz_info(input_pcz_path: str, output_json_path: str,
196 properties: Optional[dict] = None, **kwargs) -> int:
197 """Create :class:`PCZinfo <flexserv.pcasuite.pcz_info>`flexserv.pcasuite.PCZinfo class and
198 execute :meth:`launch() <flexserv.pcasuite.pcz_info.launch>` method"""
200 return PCZinfo(input_pcz_path=input_pcz_path,
201 output_json_path=output_json_path,
202 properties=properties).launch()
204 pcz_info.__doc__ = PCZinfo.__doc__
207def main():
208 parser = argparse.ArgumentParser(description='Extract PCA info from a compressed PCZ file.', formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
209 parser.add_argument('--config', required=False, help='Configuration file')
211 # Specific args
212 required_args = parser.add_argument_group('required arguments')
213 required_args.add_argument('--input_pcz_path', required=True, help='Input compressed trajectory file. Accepted formats: pcz.')
214 required_args.add_argument('--output_json_path', required=True, help='Output json file with PCA info such as number of components, variance and dimensionality. Accepted formats: json.')
216 args = parser.parse_args()
217 args.config = args.config or "{}"
218 properties = settings.ConfReader(config=args.config).get_prop_dic()
220 # Specific call
221 pcz_info(input_pcz_path=args.input_pcz_path,
222 output_json_path=args.output_json_path,
223 properties=properties)
226if __name__ == '__main__':
227 main()