Coverage for biobb_structure_utils/utils/extract_molecule.py: 75%
61 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 ExtractMolecule class and the command line interface."""
5import argparse
6from typing import Optional
8from biobb_common.configuration import settings
9from biobb_common.generic.biobb_object import BiobbObject
10from biobb_common.tools import file_utils as fu
11from biobb_common.tools.file_utils import launchlogger
13from biobb_structure_utils.utils.common import (
14 _from_string_to_list,
15 check_input_path,
16 check_output_path,
17)
20class ExtractMolecule(BiobbObject):
21 """
22 | biobb_structure_utils ExtractMolecule
23 | This class is a wrapper of the Structure Checking tool to extract a molecule from a 3D structure.
24 | Wrapper for the `Structure Checking <https://github.com/bioexcel/biobb_structure_checking>`_ tool to extract a molecule from a 3D structure.
26 Args:
27 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_molecule.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476).
28 output_molecule_path (str): Output molecule file path. File type: output. `Sample file <https://github.com/bioexcel/biobb_structure_utils/raw/master/biobb_structure_utils/test/reference/utils/ref_extract_molecule.pdb>`_. Accepted formats: pdb (edam:format_1476), pdbqt (edam:format_1476).
29 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
30 * **molecule_type** (*string*) - ("all") type of molecule to be extracted. If all, only waters and ligands will be removed from the original structure. Values: all, protein, na, dna, rna, chains.
31 * **chains** (*list*) - (None) if chains selected in **molecule_type**, specify them here, e.g: ["A", "C", "N"].
32 * **binary_path** (*string*) - ("check_structure") path to the check_structure application
33 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
34 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
35 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
37 Examples:
38 This is a use example of how to use the building block from Python::
40 from biobb_structure_utils.utils.extract_molecule import extract_molecule
41 prop = {
42 'molecule_type': 'chains',
43 'chains': ['A', 'N', 'F']
44 }
45 extract_molecule(input_structure_path='/path/to/myStructure.pdb',
46 output_molecule_path='/path/to/newMolecule.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_molecule_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_molecule_path": output_molecule_path},
73 }
75 # Properties specific for BB
76 self.molecule_type = properties.get("molecule_type", "all")
77 self.chains = _from_string_to_list(properties.get("chains", []))
78 self.binary_path = properties.get("binary_path", "check_structure")
79 self.properties = properties
81 # Check the properties
82 self.check_properties(properties)
83 self.check_arguments()
85 def create_command_list(self, command_list_path):
86 """Creates a command list file as a input for structure checking"""
87 instructions_list = ["ligands --remove All", "water --remove Yes"]
89 if self.molecule_type != "all":
90 if self.molecule_type == "chains":
91 instructions_list.append("chains --select " + ",".join(self.chains))
92 else:
93 instructions_list.append("chains --select " + self.molecule_type)
95 with open(command_list_path, "w") as clp:
96 for line in instructions_list:
97 clp.write(line.strip() + "\n")
99 return command_list_path
101 @launchlogger
102 def launch(self) -> int:
103 """Execute the :class:`ExtractMolecule <utils.extract_molecule.ExtractMolecule>` utils.extract_molecule.ExtractMolecule object."""
105 self.io_dict["in"]["input_structure_path"] = check_input_path(
106 self.io_dict["in"]["input_structure_path"],
107 self.out_log,
108 self.__class__.__name__,
109 )
110 self.io_dict["out"]["output_molecule_path"] = check_output_path(
111 self.io_dict["out"]["output_molecule_path"],
112 self.out_log,
113 self.__class__.__name__,
114 )
116 # Setup Biobb
117 if self.check_restart():
118 return 0
119 self.stage_files()
121 # create temporary folder
122 tmp_folder = fu.create_unique_dir()
123 fu.log("Creating %s temporary folder" % tmp_folder, self.out_log)
125 # create command list file
126 command_list_file = self.create_command_list(tmp_folder + "/extract_prot.lst")
128 # run command line
129 self.cmd = [
130 self.binary_path,
131 "-i",
132 self.io_dict["in"]["input_structure_path"],
133 "-o",
134 self.io_dict["out"]["output_molecule_path"],
135 "--force_save",
136 "--non_interactive",
137 "command_list",
138 "--list",
139 command_list_file,
140 ]
142 # Run Biobb block
143 self.run_biobb()
145 # Copy files to host
146 self.copy_to_host()
148 # Remove temporal files
149 self.tmp_files.extend([
150 self.stage_io_dict.get("unique_dir", ""),
151 # tmp_folder
152 ])
153 self.remove_tmp_files()
155 self.check_arguments(output_files_created=True, raise_exception=False)
157 return self.return_code
160def extract_molecule(
161 input_structure_path: str,
162 output_molecule_path: str,
163 properties: Optional[dict] = None,
164 **kwargs,
165) -> int:
166 """Execute the :class:`ExtractMolecule <utils.extract_molecule.ExtractMolecule>` class and
167 execute the :meth:`launch() <utils.extract_molecule.ExtractMolecule.launch>` method."""
169 return ExtractMolecule(
170 input_structure_path=input_structure_path,
171 output_molecule_path=output_molecule_path,
172 properties=properties,
173 **kwargs,
174 ).launch()
176 extract_molecule.__doc__ = ExtractMolecule.__doc__
179def main():
180 """Command line execution of this building block. Please check the command line documentation."""
181 parser = argparse.ArgumentParser(
182 description="Extract a molecule from a 3D structure.",
183 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999),
184 )
185 parser.add_argument(
186 "-c",
187 "--config",
188 required=False,
189 help="This file can be a YAML file, JSON file or JSON string",
190 )
192 # Specific args of each building block
193 required_args = parser.add_argument_group("required arguments")
194 required_args.add_argument(
195 "-i",
196 "--input_structure_path",
197 required=True,
198 help="Input structure file path. Accepted formats: pdb.",
199 )
200 required_args.add_argument(
201 "-o",
202 "--output_molecule_path",
203 required=True,
204 help="Output heteroatom file path. Accepted formats: pdb.",
205 )
207 args = parser.parse_args()
208 config = args.config if args.config else None
209 properties = settings.ConfReader(config=config).get_prop_dic()
211 # Specific call of each building block
212 extract_molecule(
213 input_structure_path=args.input_structure_path,
214 output_molecule_path=args.output_molecule_path,
215 properties=properties,
216 )
219if __name__ == "__main__":
220 main()