Coverage for biobb_structure_utils/utils/extract_chain.py: 73%
66 statements
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-14 19:03 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2024-06-14 19:03 +0000
1#!/usr/bin/env python3
3"""Module containing the ExtractChain class and the command line interface."""
4import argparse
5import shutil
6from biobb_common.configuration import settings
7from biobb_common.generic.biobb_object import BiobbObject
8from biobb_common.tools import file_utils as fu
9from biobb_common.tools.file_utils import launchlogger
10from biobb_structure_utils.utils.common import check_input_path, check_output_path
13class ExtractChain(BiobbObject):
14 """
15 | biobb_structure_utils ExtractAtoms
16 | This class is a wrapper of the Structure Checking tool to extract a chain from a 3D structure.
17 | Wrapper for the `Structure Checking <https://github.com/bioexcel/biobb_structure_checking>`_ tool to extract a chain from a 3D structure.
19 Args:
20 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).
21 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).
22 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
23 * **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.
24 * **permissive** (*bool*) - (False) Use non standard PDB files.
25 * **binary_path** (*string*) - ("check_structure") path to the check_structure application
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_structure_utils.utils.extract_chain import extract_chain
34 prop = {
35 'chains': [ 'A', 'B' ]
36 }
37 extract_chain(input_structure_path='/path/to/myStructure.pdb',
38 output_structure_path='/path/to/newStructure.pdb',
39 properties=prop)
41 Info:
42 * wrapped_software:
43 * name: Structure Checking from MDWeb
44 * version: >=3.0.3
45 * license: Apache-2.0
46 * ontology:
47 * name: EDAM
48 * schema: http://edamontology.org/EDAM.owl
50 """
52 def __init__(self, input_structure_path, output_structure_path, properties=None, **kwargs) -> None:
53 properties = properties or {}
55 # Call parent class constructor
56 super().__init__(properties)
57 self.locals_var_dict = locals().copy()
59 # Input/Output files
60 self.io_dict = {
61 "in": {"input_structure_path": input_structure_path},
62 "out": {"output_structure_path": output_structure_path}
63 }
65 # Properties specific for BB
66 self.binary_path = properties.get('binary_path', 'check_structure')
67 self.chains = properties.get('chains', [])
68 self.permissive = properties.get('permissive', False)
69 self.properties = properties
71 # Check the properties
72 self.check_properties(properties)
73 self.check_arguments()
75 @launchlogger
76 def launch(self) -> int:
77 """Execute the :class:`ExtractChain <utils.extract_chain.ExtractChain>` utils.extract_chain.ExtractChain object."""
79 self.io_dict['in']['input_structure_path'] = check_input_path(self.io_dict['in']['input_structure_path'],
80 self.out_log, self.__class__.__name__)
81 self.io_dict['out']['output_structure_path'] = check_output_path(self.io_dict['out']['output_structure_path'],
82 self.out_log, self.__class__.__name__)
84 # Setup Biobb
85 if self.check_restart():
86 return 0
87 self.stage_files()
89 # check if user has passed chains properly
90 chains = check_format_chains(self.chains, self.out_log)
91 fu.log(f"Selected Chains: {chains}", self.out_log, self.global_log)
93 if self.permissive:
94 fu.log('Warning: Use permissive=True is a risky option use it under your own responsability', self.out_log, self.global_log)
95 if chains.upper() == 'ALL':
96 shutil.copyfile(self.io_dict['in']['input_structure_path'], self.io_dict['out']['output_structure_path'])
97 else:
98 chain_list = chains.upper().replace(" ", "").split(",")
99 with open(self.io_dict['in']['input_structure_path']) as structure_in, open(self.io_dict['out']['output_structure_path'], 'w') as structure_out:
100 for line in structure_in:
101 if line.strip().upper().startswith(('ATOM', 'HETATM')) and line.strip().upper()[21] in chain_list:
102 structure_out.write(line)
104 else:
105 # run command line
106 self.cmd = [self.binary_path,
107 '-i', self.io_dict['in']['input_structure_path'],
108 '-o', self.io_dict['out']['output_structure_path'],
109 '--force_save',
110 'chains', '--select', chains]
112 # Run Biobb block
113 self.run_biobb()
115 # Copy files to host
116 self.copy_to_host()
118 # Remove temporal files
119 self.tmp_files.append(self.stage_io_dict.get("unique_dir"))
120 self.remove_tmp_files()
122 self.check_arguments(output_files_created=True, raise_exception=False)
124 return self.return_code
127def check_format_chains(chains, out_log):
128 """ Check format of chains list """
129 if not chains:
130 fu.log('Empty chains parameter, all chains will be returned.', out_log)
131 return 'All'
133 if not isinstance(chains, list):
134 fu.log('Incorrect format of chains parameter, all chains will be returned.', out_log)
135 return 'All'
137 return ','.join(chains)
140def extract_chain(input_structure_path: str, output_structure_path: str, properties: dict = None, **kwargs) -> int:
141 """Execute the :class:`ExtractChain <utils.extract_chain.ExtractChain>` class and
142 execute the :meth:`launch() <utils.extract_chain.ExtractChain.launch>` method."""
144 return ExtractChain(input_structure_path=input_structure_path,
145 output_structure_path=output_structure_path,
146 properties=properties, **kwargs).launch()
149def main():
150 """Command line execution of this building block. Please check the command line documentation."""
151 parser = argparse.ArgumentParser(description="Extract a chain from a 3D structure.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
152 parser.add_argument('-c', '--config', required=False, help="This file can be a YAML file, JSON file or JSON string")
154 # Specific args of each building block
155 required_args = parser.add_argument_group('required arguments')
156 required_args.add_argument('-i', '--input_structure_path', required=True, help="Input structure file path. Accepted formats: pdb.")
157 required_args.add_argument('-o', '--output_structure_path', required=True, help="Output structure file path. Accepted formats: pdb.")
159 args = parser.parse_args()
160 config = args.config if args.config else None
161 properties = settings.ConfReader(config=config).get_prop_dic()
163 # Specific call of each building block
164 extract_chain(input_structure_path=args.input_structure_path,
165 output_structure_path=args.output_structure_path,
166 properties=properties)
169if __name__ == '__main__':
170 main()