Coverage for biobb_structure_utils / utils / extract_chain.py: 84%
56 statements
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-22 13:23 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-22 13:23 +0000
1#!/usr/bin/env python3
3"""Module containing the ExtractChain class and the command line interface."""
4import shutil
5from typing import Optional
6from biobb_common.generic.biobb_object import BiobbObject
7from biobb_common.tools import file_utils as fu
8from biobb_common.tools.file_utils import launchlogger
10from biobb_structure_utils.utils.common import (
11 _from_string_to_list,
12 check_input_path,
13 check_output_path,
14)
17class ExtractChain(BiobbObject):
18 """
19 | biobb_structure_utils ExtractAtoms
20 | This class is a wrapper of the Structure Checking tool to extract a chain from a 3D structure.
21 | Wrapper for the `Structure Checking <https://github.com/bioexcel/biobb_structure_checking>`_ tool to extract a chain from a 3D structure.
23 Args:
24 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).
25 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).
26 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
27 * **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.
28 * **permissive** (*bool*) - (False) Use non standard PDB files.
29 * **binary_path** (*string*) - ("check_structure") path to the check_structure application
30 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
31 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
32 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
34 Examples:
35 This is a use example of how to use the building block from Python::
37 from biobb_structure_utils.utils.extract_chain import extract_chain
38 prop = {
39 'chains': [ 'A', 'B' ]
40 }
41 extract_chain(input_structure_path='/path/to/myStructure.pdb',
42 output_structure_path='/path/to/newStructure.pdb',
43 properties=prop)
45 Info:
46 * wrapped_software:
47 * name: Structure Checking from MDWeb
48 * version: >=3.0.3
49 * license: Apache-2.0
50 * ontology:
51 * name: EDAM
52 * schema: http://edamontology.org/EDAM.owl
54 """
56 def __init__(
57 self, input_structure_path, output_structure_path, properties=None, **kwargs
58 ) -> None:
59 properties = properties or {}
61 # Call parent class constructor
62 super().__init__(properties)
63 self.locals_var_dict = locals().copy()
65 # Input/Output files
66 self.io_dict = {
67 "in": {"input_structure_path": input_structure_path},
68 "out": {"output_structure_path": output_structure_path},
69 }
71 # Properties specific for BB
72 self.binary_path = properties.get("binary_path", "check_structure")
73 self.chains = _from_string_to_list(properties.get("chains", []))
74 self.permissive = properties.get("permissive", False)
75 self.properties = properties
77 # Check the properties
78 self.check_properties(properties)
79 self.check_arguments()
81 @launchlogger
82 def launch(self) -> int:
83 """Execute the :class:`ExtractChain <utils.extract_chain.ExtractChain>` utils.extract_chain.ExtractChain object."""
85 self.io_dict["in"]["input_structure_path"] = check_input_path(
86 self.io_dict["in"]["input_structure_path"],
87 self.out_log,
88 self.__class__.__name__,
89 )
90 self.io_dict["out"]["output_structure_path"] = check_output_path(
91 self.io_dict["out"]["output_structure_path"],
92 self.out_log,
93 self.__class__.__name__,
94 )
96 # Setup Biobb
97 if self.check_restart():
98 return 0
99 self.stage_files()
101 # check if user has passed chains properly
102 chains = check_format_chains(self.chains, self.out_log)
103 fu.log(f"Selected Chains: {chains}", self.out_log, self.global_log)
105 if self.permissive:
106 fu.log(
107 "Warning: Use permissive=True is a risky option use it under your own responsability",
108 self.out_log,
109 self.global_log,
110 )
111 if chains.upper() == "ALL":
112 shutil.copyfile(
113 self.io_dict["in"]["input_structure_path"],
114 self.io_dict["out"]["output_structure_path"],
115 )
116 else:
117 chain_list = chains.upper().replace(" ", "").split(",")
118 with open(
119 self.io_dict["in"]["input_structure_path"]
120 ) as structure_in, open(
121 self.io_dict["out"]["output_structure_path"], "w"
122 ) as structure_out:
123 for line in structure_in:
124 if (
125 line.strip().upper().startswith(("ATOM", "HETATM")) and line.strip().upper()[21] in chain_list
126 ):
127 structure_out.write(line)
129 else:
130 # run command line
131 self.cmd = [
132 self.binary_path,
133 "-i",
134 self.io_dict["in"]["input_structure_path"],
135 "-o",
136 self.io_dict["out"]["output_structure_path"],
137 "--force_save",
138 "chains",
139 "--select",
140 chains,
141 ]
143 # Run Biobb block
144 self.run_biobb()
146 # Copy files to host
147 self.copy_to_host()
149 # Remove temporal files
150 self.remove_tmp_files()
152 self.check_arguments(output_files_created=True, raise_exception=False)
154 return self.return_code
157def check_format_chains(chains, out_log):
158 """Check format of chains list"""
159 if not chains:
160 fu.log("Empty chains parameter, all chains will be returned.", out_log)
161 return "All"
163 if not isinstance(chains, list):
164 fu.log(
165 "Incorrect format of chains parameter, all chains will be returned.",
166 out_log,
167 )
168 return "All"
170 return ",".join(chains)
173def extract_chain(
174 input_structure_path: str,
175 output_structure_path: str,
176 properties: Optional[dict] = None,
177 **kwargs,
178) -> int:
179 """Create the :class:`ExtractChain <utils.extract_chain.ExtractChain>` class and
180 execute the :meth:`launch() <utils.extract_chain.ExtractChain.launch>` method."""
181 return ExtractChain(**dict(locals())).launch()
184extract_chain.__doc__ = ExtractChain.__doc__
185main = ExtractChain.get_main(extract_chain, "Extract a chain from a 3D structure.")
187if __name__ == "__main__":
188 main()