Coverage for biobb_structure_utils / utils / extract_molecule.py: 90%
50 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 ExtractMolecule class and the command line interface."""
4from typing import Optional
5from biobb_common.generic.biobb_object import BiobbObject
6from biobb_common.tools import file_utils as fu
7from biobb_common.tools.file_utils import launchlogger
9from biobb_structure_utils.utils.common import (
10 _from_string_to_list,
11 check_input_path,
12 check_output_path,
13)
16class ExtractMolecule(BiobbObject):
17 """
18 | biobb_structure_utils ExtractMolecule
19 | This class is a wrapper of the Structure Checking tool to extract a molecule from a 3D structure.
20 | Wrapper for the `Structure Checking <https://github.com/bioexcel/biobb_structure_checking>`_ tool to extract a molecule from a 3D structure.
22 Args:
23 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).
24 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).
25 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
26 * **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.
27 * **chains** (*list*) - (None) if chains selected in **molecule_type**, specify them here, e.g: ["A", "C", "N"].
28 * **binary_path** (*string*) - ("check_structure") path to the check_structure application
29 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
30 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
31 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
33 Examples:
34 This is a use example of how to use the building block from Python::
36 from biobb_structure_utils.utils.extract_molecule import extract_molecule
37 prop = {
38 'molecule_type': 'chains',
39 'chains': ['A', 'N', 'F']
40 }
41 extract_molecule(input_structure_path='/path/to/myStructure.pdb',
42 output_molecule_path='/path/to/newMolecule.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_molecule_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_molecule_path": output_molecule_path},
69 }
71 # Properties specific for BB
72 self.molecule_type = properties.get("molecule_type", "all")
73 self.chains = _from_string_to_list(properties.get("chains", []))
74 self.binary_path = properties.get("binary_path", "check_structure")
75 self.properties = properties
77 # Check the properties
78 self.check_properties(properties)
79 self.check_arguments()
81 def create_command_list(self, command_list_path):
82 """Creates a command list file as a input for structure checking"""
83 instructions_list = ["ligands --remove All", "water --remove Yes"]
85 if self.molecule_type != "all":
86 if self.molecule_type == "chains":
87 instructions_list.append("chains --select " + ",".join(self.chains))
88 else:
89 instructions_list.append("chains --select " + self.molecule_type)
91 with open(command_list_path, "w") as clp:
92 for line in instructions_list:
93 clp.write(line.strip() + "\n")
95 return command_list_path
97 @launchlogger
98 def launch(self) -> int:
99 """Execute the :class:`ExtractMolecule <utils.extract_molecule.ExtractMolecule>` utils.extract_molecule.ExtractMolecule object."""
101 self.io_dict["in"]["input_structure_path"] = check_input_path(
102 self.io_dict["in"]["input_structure_path"],
103 self.out_log,
104 self.__class__.__name__,
105 )
106 self.io_dict["out"]["output_molecule_path"] = check_output_path(
107 self.io_dict["out"]["output_molecule_path"],
108 self.out_log,
109 self.__class__.__name__,
110 )
112 # Setup Biobb
113 if self.check_restart():
114 return 0
115 self.stage_files()
117 # create temporary folder
118 tmp_folder = fu.create_unique_dir()
119 fu.log("Creating %s temporary folder" % tmp_folder, self.out_log)
121 # create command list file
122 command_list_file = self.create_command_list(tmp_folder + "/extract_prot.lst")
124 # run command line
125 self.cmd = [
126 self.binary_path,
127 "-i",
128 self.io_dict["in"]["input_structure_path"],
129 "-o",
130 self.io_dict["out"]["output_molecule_path"],
131 "--force_save",
132 "--non_interactive",
133 "command_list",
134 "--list",
135 command_list_file,
136 ]
138 # Run Biobb block
139 self.run_biobb()
141 # Copy files to host
142 self.copy_to_host()
144 # Remove temporal files
145 self.tmp_files.append(tmp_folder)
146 self.remove_tmp_files()
148 self.check_arguments(output_files_created=True, raise_exception=False)
150 return self.return_code
153def extract_molecule(
154 input_structure_path: str,
155 output_molecule_path: str,
156 properties: Optional[dict] = None,
157 **kwargs,
158) -> int:
159 """Create the :class:`ExtractMolecule <utils.extract_molecule.ExtractMolecule>` class and
160 execute the :meth:`launch() <utils.extract_molecule.ExtractMolecule.launch>` method."""
161 return ExtractMolecule(**dict(locals())).launch()
164extract_molecule.__doc__ = ExtractMolecule.__doc__
165main = ExtractMolecule.get_main(extract_molecule, "Extract a molecule from a 3D structure.")
167if __name__ == "__main__":
168 main()