Coverage for biobb_structure_utils/utils/extract_chain.py: 72%
67 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-28 11:54 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-28 11:54 +0000
1#!/usr/bin/env python3
3"""Module containing the ExtractChain class and the command line interface."""
5import argparse
6import shutil
7from typing import Optional
9from biobb_common.configuration import settings
10from biobb_common.generic.biobb_object import BiobbObject
11from biobb_common.tools import file_utils as fu
12from biobb_common.tools.file_utils import launchlogger
14from biobb_structure_utils.utils.common import (
15 _from_string_to_list,
16 check_input_path,
17 check_output_path,
18)
21class ExtractChain(BiobbObject):
22 """
23 | biobb_structure_utils ExtractAtoms
24 | This class is a wrapper of the Structure Checking tool to extract a chain from a 3D structure.
25 | Wrapper for the `Structure Checking <https://github.com/bioexcel/biobb_structure_checking>`_ tool to extract a chain from a 3D structure.
27 Args:
28 input_structure_path (str): Input structure file path. File type: input. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/data/utils/extract_chain.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476).
29 output_structure_path (str): Output structure file path. File type: output. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/reference/utils/ref_extract_chain.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476).
30 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
31 * **chains** (*list*) - (None) List of chains to be extracted from the input_structure_path file. If empty, all the chains of the structure will be returned.
32 * **permissive** (*bool*) - (False) Use non standard PDB files.
33 * **binary_path** (*string*) - ("check_structure") path to the check_structure application
34 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
35 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
36 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
38 Examples:
39 This is a use example of how to use the building block from Python::
41 from biobb_structure_utils.utils.extract_chain import extract_chain
42 prop = {
43 'chains': [ 'A', 'B' ]
44 }
45 extract_chain(input_structure_path='/path/to/myStructure.pdb',
46 output_structure_path='/path/to/newStructure.pdb',
47 properties=prop)
49 Info:
50 * wrapped_software:
51 * name: Structure Checking from MDWeb
52 * version: >=3.0.3
53 * license: Apache-2.0
54 * ontology:
55 * name: EDAM
56 * schema: http://edamontology.org/EDAM.owl
58 """
60 def __init__(
61 self, input_structure_path, output_structure_path, properties=None, **kwargs
62 ) -> None:
63 properties = properties or {}
65 # Call parent class constructor
66 super().__init__(properties)
67 self.locals_var_dict = locals().copy()
69 # Input/Output files
70 self.io_dict = {
71 "in": {"input_structure_path": input_structure_path},
72 "out": {"output_structure_path": output_structure_path},
73 }
75 # Properties specific for BB
76 self.binary_path = properties.get("binary_path", "check_structure")
77 self.chains = _from_string_to_list(properties.get("chains", []))
78 self.permissive = properties.get("permissive", False)
79 self.properties = properties
81 # Check the properties
82 self.check_properties(properties)
83 self.check_arguments()
85 @launchlogger
86 def launch(self) -> int:
87 """Execute the :class:`ExtractChain <utils.extract_chain.ExtractChain>` utils.extract_chain.ExtractChain object."""
89 self.io_dict["in"]["input_structure_path"] = check_input_path(
90 self.io_dict["in"]["input_structure_path"],
91 self.out_log,
92 self.__class__.__name__,
93 )
94 self.io_dict["out"]["output_structure_path"] = check_output_path(
95 self.io_dict["out"]["output_structure_path"],
96 self.out_log,
97 self.__class__.__name__,
98 )
100 # Setup Biobb
101 if self.check_restart():
102 return 0
103 self.stage_files()
105 # check if user has passed chains properly
106 chains = check_format_chains(self.chains, self.out_log)
107 fu.log(f"Selected Chains: {chains}", self.out_log, self.global_log)
109 if self.permissive:
110 fu.log(
111 "Warning: Use permissive=True is a risky option use it under your own responsability",
112 self.out_log,
113 self.global_log,
114 )
115 if chains.upper() == "ALL":
116 shutil.copyfile(
117 self.io_dict["in"]["input_structure_path"],
118 self.io_dict["out"]["output_structure_path"],
119 )
120 else:
121 chain_list = chains.upper().replace(" ", "").split(",")
122 with open(
123 self.io_dict["in"]["input_structure_path"]
124 ) as structure_in, open(
125 self.io_dict["out"]["output_structure_path"], "w"
126 ) as structure_out:
127 for line in structure_in:
128 if (
129 line.strip().upper().startswith(("ATOM", "HETATM")) and line.strip().upper()[21] in chain_list
130 ):
131 structure_out.write(line)
133 else:
134 # run command line
135 self.cmd = [
136 self.binary_path,
137 "-i",
138 self.io_dict["in"]["input_structure_path"],
139 "-o",
140 self.io_dict["out"]["output_structure_path"],
141 "--force_save",
142 "chains",
143 "--select",
144 chains,
145 ]
147 # Run Biobb block
148 self.run_biobb()
150 # Copy files to host
151 self.copy_to_host()
153 # Remove temporal files
154 # self.tmp_files.append(self.stage_io_dict.get("unique_dir", ""))
155 self.remove_tmp_files()
157 self.check_arguments(output_files_created=True, raise_exception=False)
159 return self.return_code
162def check_format_chains(chains, out_log):
163 """Check format of chains list"""
164 if not chains:
165 fu.log("Empty chains parameter, all chains will be returned.", out_log)
166 return "All"
168 if not isinstance(chains, list):
169 fu.log(
170 "Incorrect format of chains parameter, all chains will be returned.",
171 out_log,
172 )
173 return "All"
175 return ",".join(chains)
178def extract_chain(
179 input_structure_path: str,
180 output_structure_path: str,
181 properties: Optional[dict] = None,
182 **kwargs,
183) -> int:
184 """Execute the :class:`ExtractChain <utils.extract_chain.ExtractChain>` class and
185 execute the :meth:`launch() <utils.extract_chain.ExtractChain.launch>` method."""
187 return ExtractChain(
188 input_structure_path=input_structure_path,
189 output_structure_path=output_structure_path,
190 properties=properties,
191 **kwargs,
192 ).launch()
194 extract_chain.__doc__ = ExtractChain.__doc__
197def main():
198 """Command line execution of this building block. Please check the command line documentation."""
199 parser = argparse.ArgumentParser(
200 description="Extract a chain from a 3D structure.",
201 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999),
202 )
203 parser.add_argument(
204 "-c",
205 "--config",
206 required=False,
207 help="This file can be a YAML file, JSON file or JSON string",
208 )
210 # Specific args of each building block
211 required_args = parser.add_argument_group("required arguments")
212 required_args.add_argument(
213 "-i",
214 "--input_structure_path",
215 required=True,
216 help="Input structure file path. Accepted formats: pdb.",
217 )
218 required_args.add_argument(
219 "-o",
220 "--output_structure_path",
221 required=True,
222 help="Output structure file path. Accepted formats: pdb.",
223 )
225 args = parser.parse_args()
226 config = args.config if args.config else None
227 properties = settings.ConfReader(config=config).get_prop_dic()
229 # Specific call of each building block
230 extract_chain(
231 input_structure_path=args.input_structure_path,
232 output_structure_path=args.output_structure_path,
233 properties=properties,
234 )
237if __name__ == "__main__":
238 main()