Coverage for biobb_chemistry/babelm/babel_minimize.py: 86%
84 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-12 09:28 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-12 09:28 +0000
1#!/usr/bin/env python3
3"""Module containing the BabelMinimize class and the command line interface."""
4import argparse
5from typing import Optional
6from pathlib import PurePath
7from biobb_common.generic.biobb_object import BiobbObject
8from biobb_common.configuration import settings
9from biobb_common.tools.file_utils import launchlogger
10from biobb_chemistry.babelm.common import check_minimize_property, check_input_path_minimize, check_output_path_minimize
13class BabelMinimize(BiobbObject):
14 """
15 | biobb_chemistry BabelMinimize
16 | This class is a wrapper of the Open Babel tool.
17 | Energetically minimizes small molecules. Open Babel is a chemical toolbox designed to speak the many languages of chemical data. It's an open, collaborative project allowing anyone to search, convert, analyze, or store data from molecular modeling, chemistry, solid-state materials, biochemistry, or related areas. `Visit the official page <http://openbabel.org/wiki/Main_Page>`_.
19 Args:
20 input_path (str): Path to the input file. File type: input. `Sample file <https://github.com/bioexcel/biobb_chemistry/raw/master/biobb_chemistry/test/data/babel/babel.minimize.pdb>`_. Accepted formats: pdb (edam:format_1476), mol2 (edam:format_3816).
21 output_path (str): Path to the output file. File type: output. `Sample file <https://github.com/bioexcel/biobb_chemistry/raw/master/biobb_chemistry/test/reference/babel/ref_babel.minimize.pdb>`_. Accepted formats: pdb (edam:format_1476), mol2 (edam:format_3816).
22 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
23 * **criteria** (*float*) - (1e-6) Convergence criteria
24 * **method** (*str*) - ("cg") Method. Values: cg (conjugate gradients algorithm), sd (steepest descent algorithm).
25 * **force_field** (*str*) - (None) Force field. Values: GAFF (General Amber Force Field), Ghemical (Ghemical force field), MMFF94 (MMFF94 force field), MMFF94s (MMFF94s force field), UFF (Universal Force Field).
26 * **hydrogens** (*bool*) - (False) Add hydrogen atoms.
27 * **steps** (*int*) - (2500) [0~5000|1] Maximum number of steps.
28 * **cutoff** (*bool*) - (False) Use cut-off.
29 * **rvdw** (*float*) - (6.0) [0~50|1.0] VDW cut-off distance.
30 * **rele** (*float*) - (10.0) [0~50|1.0] Electrostatic cut-off distance.
31 * **frequency** (*int*) - (10) [0~50|1] Frequency to update the non-bonded pairs.
32 * **binary_path** (*str*) - ("obminimize") Path to the obminimize executable binary.
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.
36 * **container_path** (*str*) - (None) Container path definition.
37 * **container_image** (*str*) - ('informaticsmatters/obabel:latest') Container image definition.
38 * **container_volume_path** (*str*) - ('/tmp') Container volume path definition.
39 * **container_working_dir** (*str*) - (None) Container working directory definition.
40 * **container_user_id** (*str*) - (None) Container user_id definition.
41 * **container_shell_path** (*str*) - ('/bin/bash') Path to default shell inside the container.
43 Examples:
44 This is a use example of how to use the building block from Python::
46 from biobb_chemistry.babelm.babel_minimize import babel_minimize
47 prop = {
48 'criteria': 1e-6,
49 'method': 'cg',
50 'force_field': 'GAFF'
51 }
52 babel_minimize(input_path='/path/to/myStructure.mol2',
53 output_path='/path/to/newStructure.mol2',
54 properties=prop)
56 Info:
57 * wrapped_software:
58 * name: Open Babel
59 * version: 2.4.1
60 * license: GNU
61 * ontology:
62 * name: EDAM
63 * schema: http://edamontology.org/EDAM.owl
65 """
67 def __init__(self, input_path, output_path,
68 properties=None, **kwargs) -> None:
69 properties = properties or {}
71 # Call parent class constructor
72 super().__init__(properties)
73 self.locals_var_dict = locals().copy()
75 # Input/Output files
76 self.io_dict = {
77 "in": {"input_path": input_path},
78 "out": {"output_path": output_path}
79 }
81 # Properties specific for BB
82 self.criteria = properties.get('criteria', '')
83 self.method = properties.get('method', '')
84 self.force_field = properties.get('force_field', '')
85 self.hydrogens = properties.get('hydrogens', '')
86 self.steps = properties.get('steps', '')
87 self.cutoff = properties.get('cutoff', '')
88 self.rvdw = properties.get('rvdw', '')
89 self.rele = properties.get('rele', '')
90 self.frequency = properties.get('frequency', '')
91 self.binary_path = properties.get('binary_path', 'obminimize')
92 self.properties = properties
94 # Check the properties
95 self.check_properties(properties)
96 self.check_arguments()
98 def check_data_params(self, out_log, err_log):
99 """ Checks all the input/output paths and parameters """
100 self.io_dict["in"]["input_path"] = check_input_path_minimize(self.io_dict["in"]["input_path"], out_log, self.__class__.__name__)
101 self.io_dict["out"]["output_path"] = check_output_path_minimize(self.io_dict["out"]["output_path"], out_log, self.__class__.__name__)
103 def create_cmd(self, container_io_dict, out_log, err_log):
104 """Creates the command line instruction using the properties file settings"""
105 instructions_list = []
107 # executable path
108 instructions_list.append(self.binary_path)
110 # check all properties
111 if check_minimize_property("criteria", self.criteria, out_log):
112 instructions_list.append('-c ' + str(self.criteria))
114 if check_minimize_property("method", self.method, out_log):
115 instructions_list.append('-' + self.method)
117 if check_minimize_property("force_field", self.force_field, out_log):
118 instructions_list.append('-ff ' + self.force_field)
120 if check_minimize_property("hydrogens", self.hydrogens, out_log):
121 instructions_list.append('-h')
123 if check_minimize_property("steps", self.steps, out_log):
124 instructions_list.append('-n ' + str(self.steps))
126 if check_minimize_property("cutoff", self.cutoff, out_log):
127 instructions_list.append('-cut')
129 if check_minimize_property("rvdw", self.rvdw, out_log):
130 instructions_list.append('-rvdw ' + str(self.rvdw))
132 if check_minimize_property("rele", self.rele, out_log):
133 instructions_list.append('-rele ' + str(self.rele))
135 if check_minimize_property("frequency", self.frequency, out_log):
136 instructions_list.append('-pf ' + str(self.frequency))
138 iextension = PurePath(container_io_dict["in"]["input_path"]).suffix
139 oextension = PurePath(container_io_dict["out"]["output_path"]).suffix
141 instructions_list.append('-i' + iextension[1:] + ' ' + container_io_dict["in"]["input_path"])
143 instructions_list.append('-o' + oextension[1:])
145 instructions_list.append('>')
147 instructions_list.append(container_io_dict["out"]["output_path"])
149 return instructions_list
151 @launchlogger
152 def launch(self) -> int:
153 """Execute the :class:`BabelMinimize <babelm.babel_minimize.BabelMinimize>` babelm.babel_minimize.BabelMinimize object."""
155 # check input/output paths and parameters
156 self.check_data_params(self.out_log, self.err_log)
158 # Setup Biobb
159 if self.check_restart():
160 return 0
161 self.stage_files()
163 # create command line instruction
164 self.cmd = self.create_cmd(self.stage_io_dict, self.out_log, self.err_log)
166 # Run Biobb block
167 self.run_biobb()
169 # Copy files to host
170 self.copy_to_host()
172 # remove temporary folder(s)
173 '''self.tmp_files.extend([
174 self.stage_io_dict.get("unique_dir", "")
175 ])'''
176 self.remove_tmp_files()
178 self.check_arguments(output_files_created=True, raise_exception=False)
180 return self.return_code
183def babel_minimize(input_path: str, output_path: str, properties: Optional[dict] = None, **kwargs) -> int:
184 """Execute the :class:`BabelMinimize <babelm.babel_minimize.BabelMinimize>` class and
185 execute the :meth:`launch() <babelm.babel_minimize.BabelMinimize.launch>` method."""
187 return BabelMinimize(input_path=input_path,
188 output_path=output_path,
189 properties=properties, **kwargs).launch()
191 babel_minimize.__doc__ = BabelMinimize.__doc__
194def main():
195 """Command line execution of this building block. Please check the command line documentation."""
196 parser = argparse.ArgumentParser(description="Energetically minimize small molecules.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
197 parser.add_argument('--config', required=False, help='Configuration file')
199 # Specific args of each building block
200 required_args = parser.add_argument_group('required arguments')
201 required_args.add_argument('--input_path', required=True, help='Path to the input file. Accepted formats: pdb, mol2.')
202 required_args.add_argument('--output_path', required=True, help='Path to the output file. Accepted formats: pdb, mol2.')
204 args = parser.parse_args()
205 args.config = args.config or "{}"
206 properties = settings.ConfReader(config=args.config).get_prop_dic()
208 # Specific call of each building block
209 babel_minimize(input_path=args.input_path,
210 output_path=args.output_path,
211 properties=properties)
214if __name__ == '__main__':
215 main()